diff options
Diffstat (limited to 'Doc/howto/logging-cookbook.rst')
-rw-r--r-- | Doc/howto/logging-cookbook.rst | 1561 |
1 files changed, 59 insertions, 1502 deletions
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst index 17f4ff6..50ff76e 100644 --- a/Doc/howto/logging-cookbook.rst +++ b/Doc/howto/logging-cookbook.rst @@ -72,9 +72,7 @@ Here is the auxiliary module:: def some_function(): module_logger.info('received a call to "some_function"') -The output looks like this: - -.. code-block:: none +The output looks like this:: 2005-03-23 23:47:11,663 - spam_application - INFO - creating an instance of auxiliary_module.Auxiliary @@ -101,7 +99,7 @@ Logging from multiple threads ----------------------------- Logging from multiple threads requires no special effort. The following example -shows logging from the main (initial) thread and another thread:: +shows logging from the main (initIal) thread and another thread:: import logging import threading @@ -129,9 +127,7 @@ shows logging from the main (initial) thread and another thread:: if __name__ == '__main__': main() -When run, the script should print something like the following: - -.. code-block:: none +When run, the script should print something like the following:: 0 Thread-1 Hi from myfunc 3 MainThread Hello from main @@ -186,7 +182,7 @@ previous simple module-based configuration example:: # 'application' code logger.debug('debug message') logger.info('info message') - logger.warning('warn message') + logger.warn('warn message') logger.error('error message') logger.critical('critical message') @@ -244,18 +240,14 @@ messages should not. Here's how you can achieve this:: logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') -When you run this, on the console you will see - -.. code-block:: none +When you run this, on the console you will see :: root : INFO Jackdaws love my big sphinx of quartz. myapp.area1 : INFO How quickly daft jumping zebras vex. myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. myapp.area2 : ERROR The five boxing wizards jump quickly. -and in the file you will see something like - -.. code-block:: none +and in the file you will see something like :: 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. @@ -295,7 +287,7 @@ Here is an example of a module using the logging configuration server:: while True: logger.debug('debug message') logger.info('info message') - logger.warning('warn message') + logger.warn('warn message') logger.error('error message') logger.critical('critical message') time.sleep(5) @@ -326,81 +318,6 @@ configuration:: print('complete') -Dealing with handlers that block --------------------------------- - -.. currentmodule:: logging.handlers - -Sometimes you have to get your logging handlers to do their work without -blocking the thread you're logging from. This is common in Web applications, -though of course it also occurs in other scenarios. - -A common culprit which demonstrates sluggish behaviour is the -:class:`SMTPHandler`: sending emails can take a long time, for a -number of reasons outside the developer's control (for example, a poorly -performing mail or network infrastructure). But almost any network-based -handler can block: Even a :class:`SocketHandler` operation may do a -DNS query under the hood which is too slow (and this query can be deep in the -socket library code, below the Python layer, and outside your control). - -One solution is to use a two-part approach. For the first part, attach only a -:class:`QueueHandler` to those loggers which are accessed from -performance-critical threads. They simply write to their queue, which can be -sized to a large enough capacity or initialized with no upper bound to their -size. The write to the queue will typically be accepted quickly, though you -will probably need to catch the :exc:`queue.Full` exception as a precaution -in your code. If you are a library developer who has performance-critical -threads in their code, be sure to document this (together with a suggestion to -attach only ``QueueHandlers`` to your loggers) for the benefit of other -developers who will use your code. - -The second part of the solution is :class:`QueueListener`, which has been -designed as the counterpart to :class:`QueueHandler`. A -:class:`QueueListener` is very simple: it's passed a queue and some handlers, -and it fires up an internal thread which listens to its queue for LogRecords -sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that -matter). The ``LogRecords`` are removed from the queue and passed to the -handlers for processing. - -The advantage of having a separate :class:`QueueListener` class is that you -can use the same instance to service multiple ``QueueHandlers``. This is more -resource-friendly than, say, having threaded versions of the existing handler -classes, which would eat up one thread per handler for no particular benefit. - -An example of using these two classes follows (imports omitted):: - - que = queue.Queue(-1) # no limit on size - queue_handler = QueueHandler(que) - handler = logging.StreamHandler() - listener = QueueListener(que, handler) - root = logging.getLogger() - root.addHandler(queue_handler) - formatter = logging.Formatter('%(threadName)s: %(message)s') - handler.setFormatter(formatter) - listener.start() - # The log output will display the thread which generated - # the event (the main thread) rather than the internal - # thread which monitors the internal queue. This is what - # you want to happen. - root.warning('Look out!') - listener.stop() - -which, when run, will produce: - -.. code-block:: none - - MainThread: Look out! - -.. versionchanged:: 3.5 - Prior to Python 3.5, the :class:`QueueListener` always passed every message - received from the queue to every handler it was initialized with. (This was - because it was assumed that level filtering was all done on the other side, - where the queue is filled.) From 3.5 onwards, this behaviour can be changed - by passing a keyword argument ``respect_handler_level=True`` to the - listener's constructor. When this is done, the listener compares the level - of each message with the handler's level, and only passes a message to a - handler if it's appropriate to do so. - .. _network-logging: Sending and receiving logging events across a network @@ -434,17 +351,17 @@ the receiving end. A simple way of doing this is attaching a logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') -At the receiving end, you can set up a receiver using the :mod:`socketserver` +At the receiving end, you can set up a receiver using the :mod:`SocketServer` module. Here is a basic working example:: import pickle import logging import logging.handlers - import socketserver + import SocketServer import struct - class LogRecordStreamHandler(socketserver.StreamRequestHandler): + class LogRecordStreamHandler(SocketServer.StreamRequestHandler): """Handler for a streaming logging request. This basically logs the record using whatever logging policy is @@ -486,17 +403,17 @@ module. Here is a basic working example:: # cycles and network bandwidth! logger.handle(record) - class LogRecordSocketReceiver(socketserver.ThreadingTCPServer): + class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): """ Simple TCP socket-based logging receiver suitable for testing. """ - allow_reuse_address = True + allow_reuse_address = 1 def __init__(self, host='localhost', port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, handler=LogRecordStreamHandler): - socketserver.ThreadingTCPServer.__init__(self, (host, port), handler) + SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) self.abort = 0 self.timeout = 1 self.logname = None @@ -523,9 +440,7 @@ module. Here is a basic working example:: main() First run the server, and then the client. On the client side, nothing is -printed on the console; on the server side, you should see something like: - -.. code-block:: none +printed on the console; on the server side, you should see something like:: About to start TCP server... 59 root INFO Jackdaws love my big sphinx of quartz. @@ -546,6 +461,8 @@ serialization. Adding contextual information to your logging output ---------------------------------------------------- +.. currentmodule:: logging + Sometimes you want logging output to contain contextual information in addition to the parameters passed to the logging call. For example, in a networked application, it may be desirable to log client-specific information @@ -579,7 +496,7 @@ information. When you call one of the logging methods on an instance of information in the delegated call. Here's a snippet from the code of :class:`LoggerAdapter`:: - def debug(self, msg, /, *args, **kwargs): + def debug(self, msg, *args, **kwargs): """ Delegate a debug call to the underlying logger, after adding contextual information from this adapter instance. @@ -685,9 +602,7 @@ script:: lvlname = logging.getLevelName(lvl) a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters') -which, when run, produces something like: - -.. code-block:: none +which, when run, produces something like:: 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters @@ -721,267 +636,15 @@ existing processes to perform this function.) includes a working socket receiver which can be used as a starting point for you to adapt in your own applications. -You could also write your own handler which uses the :class:`~multiprocessing.Lock` -class from the :mod:`multiprocessing` module to serialize access to the +If you are using a recent version of Python which includes the +:mod:`multiprocessing` module, you could write your own handler which uses the +:class:`~multiprocessing.Lock` class from this module to serialize access to the file from your processes. The existing :class:`FileHandler` and subclasses do not make use of :mod:`multiprocessing` at present, though they may do so in the future. Note that at present, the :mod:`multiprocessing` module does not provide working lock functionality on all platforms (see https://bugs.python.org/issue3770). -.. currentmodule:: logging.handlers - -Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send -all logging events to one of the processes in your multi-process application. -The following example script demonstrates how you can do this; in the example -a separate listener process listens for events sent by other processes and logs -them according to its own logging configuration. Although the example only -demonstrates one way of doing it (for example, you may want to use a listener -thread rather than a separate listener process -- the implementation would be -analogous) it does allow for completely different logging configurations for -the listener and the other processes in your application, and can be used as -the basis for code meeting your own specific requirements:: - - # You'll need these imports in your own code - import logging - import logging.handlers - import multiprocessing - - # Next two import lines for this demo only - from random import choice, random - import time - - # - # Because you'll want to define the logging configurations for listener and workers, the - # listener and worker process functions take a configurer parameter which is a callable - # for configuring logging for that process. These functions are also passed the queue, - # which they use for communication. - # - # In practice, you can configure the listener however you want, but note that in this - # simple example, the listener does not apply level or filter logic to received records. - # In practice, you would probably want to do this logic in the worker processes, to avoid - # sending events which would be filtered out between processes. - # - # The size of the rotated files is made small so you can see the results easily. - def listener_configurer(): - root = logging.getLogger() - h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10) - f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s') - h.setFormatter(f) - root.addHandler(h) - - # This is the listener process top-level loop: wait for logging events - # (LogRecords)on the queue and handle them, quit when you get a None for a - # LogRecord. - def listener_process(queue, configurer): - configurer() - while True: - try: - record = queue.get() - if record is None: # We send this as a sentinel to tell the listener to quit. - break - logger = logging.getLogger(record.name) - logger.handle(record) # No level or filter logic applied - just do it! - except Exception: - import sys, traceback - print('Whoops! Problem:', file=sys.stderr) - traceback.print_exc(file=sys.stderr) - - # Arrays used for random selections in this demo - - LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL] - - LOGGERS = ['a.b.c', 'd.e.f'] - - MESSAGES = [ - 'Random message #1', - 'Random message #2', - 'Random message #3', - ] - - # The worker configuration is done at the start of the worker process run. - # Note that on Windows you can't rely on fork semantics, so each process - # will run the logging configuration code when it starts. - def worker_configurer(queue): - h = logging.handlers.QueueHandler(queue) # Just the one handler needed - root = logging.getLogger() - root.addHandler(h) - # send all messages, for demo; no other level or filter logic applied. - root.setLevel(logging.DEBUG) - - # This is the worker process top-level loop, which just logs ten events with - # random intervening delays before terminating. - # The print messages are just so you know it's doing something! - def worker_process(queue, configurer): - configurer(queue) - name = multiprocessing.current_process().name - print('Worker started: %s' % name) - for i in range(10): - time.sleep(random()) - logger = logging.getLogger(choice(LOGGERS)) - level = choice(LEVELS) - message = choice(MESSAGES) - logger.log(level, message) - print('Worker finished: %s' % name) - - # Here's where the demo gets orchestrated. Create the queue, create and start - # the listener, create ten workers and start them, wait for them to finish, - # then send a None to the queue to tell the listener to finish. - def main(): - queue = multiprocessing.Queue(-1) - listener = multiprocessing.Process(target=listener_process, - args=(queue, listener_configurer)) - listener.start() - workers = [] - for i in range(10): - worker = multiprocessing.Process(target=worker_process, - args=(queue, worker_configurer)) - workers.append(worker) - worker.start() - for w in workers: - w.join() - queue.put_nowait(None) - listener.join() - - if __name__ == '__main__': - main() - -A variant of the above script keeps the logging in the main process, in a -separate thread:: - - import logging - import logging.config - import logging.handlers - from multiprocessing import Process, Queue - import random - import threading - import time - - def logger_thread(q): - while True: - record = q.get() - if record is None: - break - logger = logging.getLogger(record.name) - logger.handle(record) - - - def worker_process(q): - qh = logging.handlers.QueueHandler(q) - root = logging.getLogger() - root.setLevel(logging.DEBUG) - root.addHandler(qh) - levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, - logging.CRITICAL] - loggers = ['foo', 'foo.bar', 'foo.bar.baz', - 'spam', 'spam.ham', 'spam.ham.eggs'] - for i in range(100): - lvl = random.choice(levels) - logger = logging.getLogger(random.choice(loggers)) - logger.log(lvl, 'Message no. %d', i) - - if __name__ == '__main__': - q = Queue() - d = { - 'version': 1, - 'formatters': { - 'detailed': { - 'class': 'logging.Formatter', - 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' - } - }, - 'handlers': { - 'console': { - 'class': 'logging.StreamHandler', - 'level': 'INFO', - }, - 'file': { - 'class': 'logging.FileHandler', - 'filename': 'mplog.log', - 'mode': 'w', - 'formatter': 'detailed', - }, - 'foofile': { - 'class': 'logging.FileHandler', - 'filename': 'mplog-foo.log', - 'mode': 'w', - 'formatter': 'detailed', - }, - 'errors': { - 'class': 'logging.FileHandler', - 'filename': 'mplog-errors.log', - 'mode': 'w', - 'level': 'ERROR', - 'formatter': 'detailed', - }, - }, - 'loggers': { - 'foo': { - 'handlers': ['foofile'] - } - }, - 'root': { - 'level': 'DEBUG', - 'handlers': ['console', 'file', 'errors'] - }, - } - workers = [] - for i in range(5): - wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,)) - workers.append(wp) - wp.start() - logging.config.dictConfig(d) - lp = threading.Thread(target=logger_thread, args=(q,)) - lp.start() - # At this point, the main process could do some useful work of its own - # Once it's done that, it can wait for the workers to terminate... - for wp in workers: - wp.join() - # And now tell the logging thread to finish up, too - q.put(None) - lp.join() - -This variant shows how you can e.g. apply configuration for particular loggers -- e.g. the ``foo`` logger has a special handler which stores all events in the -``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging -machinery in the main process (even though the logging events are generated in -the worker processes) to direct the messages to the appropriate destinations. - -Using concurrent.futures.ProcessPoolExecutor -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If you want to use :class:`concurrent.futures.ProcessPoolExecutor` to start -your worker processes, you need to create the queue slightly differently. -Instead of - -.. code-block:: python - - queue = multiprocessing.Queue(-1) - -you should use - -.. code-block:: python - - queue = multiprocessing.Manager().Queue(-1) # also works with the examples above - -and you can then replace the worker creation from this:: - - workers = [] - for i in range(10): - worker = multiprocessing.Process(target=worker_process, - args=(queue, worker_configurer)) - workers.append(worker) - worker.start() - for w in workers: - w.join() - -to this (remembering to first import :mod:`concurrent.futures`):: - - with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor: - for i in range(10): - executor.submit(worker_process, queue, worker_configurer) - Using file rotation ------------------- @@ -1022,9 +685,7 @@ logging package provides a :class:`~handlers.RotatingFileHandler`:: print(filename) The result should be 6 separate files, each with part of the log history for the -application: - -.. code-block:: none +application:: logging_rotatingfile_example.out logging_rotatingfile_example.out.1 @@ -1041,329 +702,6 @@ and each time it reaches the size limit it is renamed with the suffix Obviously this example sets the log length much too small as an extreme example. You would want to set *maxBytes* to an appropriate value. -.. _format-styles: - -Use of alternative formatting styles ------------------------------------- - -When logging was added to the Python standard library, the only way of -formatting messages with variable content was to use the %-formatting -method. Since then, Python has gained two new formatting approaches: -:class:`string.Template` (added in Python 2.4) and :meth:`str.format` -(added in Python 2.6). - -Logging (as of 3.2) provides improved support for these two additional -formatting styles. The :class:`Formatter` class been enhanced to take an -additional, optional keyword parameter named ``style``. This defaults to -``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond -to the other two formatting styles. Backwards compatibility is maintained by -default (as you would expect), but by explicitly specifying a style parameter, -you get the ability to specify format strings which work with -:meth:`str.format` or :class:`string.Template`. Here's an example console -session to show the possibilities: - -.. code-block:: pycon - - >>> import logging - >>> root = logging.getLogger() - >>> root.setLevel(logging.DEBUG) - >>> handler = logging.StreamHandler() - >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}', - ... style='{') - >>> handler.setFormatter(bf) - >>> root.addHandler(handler) - >>> logger = logging.getLogger('foo.bar') - >>> logger.debug('This is a DEBUG message') - 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message - >>> logger.critical('This is a CRITICAL message') - 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message - >>> df = logging.Formatter('$asctime $name ${levelname} $message', - ... style='$') - >>> handler.setFormatter(df) - >>> logger.debug('This is a DEBUG message') - 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message - >>> logger.critical('This is a CRITICAL message') - 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message - >>> - -Note that the formatting of logging messages for final output to logs is -completely independent of how an individual logging message is constructed. -That can still use %-formatting, as shown here:: - - >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message') - 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message - >>> - -Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take -positional parameters for the actual logging message itself, with keyword -parameters used only for determining options for how to handle the actual -logging call (e.g. the ``exc_info`` keyword parameter to indicate that -traceback information should be logged, or the ``extra`` keyword parameter -to indicate additional contextual information to be added to the log). So -you cannot directly make logging calls using :meth:`str.format` or -:class:`string.Template` syntax, because internally the logging package -uses %-formatting to merge the format string and the variable arguments. -There would be no changing this while preserving backward compatibility, since -all logging calls which are out there in existing code will be using %-format -strings. - -There is, however, a way that you can use {}- and $- formatting to construct -your individual log messages. Recall that for a message you can use an -arbitrary object as a message format string, and that the logging package will -call ``str()`` on that object to get the actual format string. Consider the -following two classes:: - - class BraceMessage: - def __init__(self, fmt, /, *args, **kwargs): - self.fmt = fmt - self.args = args - self.kwargs = kwargs - - def __str__(self): - return self.fmt.format(*self.args, **self.kwargs) - - class DollarMessage: - def __init__(self, fmt, /, **kwargs): - self.fmt = fmt - self.kwargs = kwargs - - def __str__(self): - from string import Template - return Template(self.fmt).substitute(**self.kwargs) - -Either of these can be used in place of a format string, to allow {}- or -$-formatting to be used to build the actual "message" part which appears in the -formatted log output in place of "%(message)s" or "{message}" or "$message". -It's a little unwieldy to use the class names whenever you want to log -something, but it's quite palatable if you use an alias such as __ (double -underscore --- not to be confused with _, the single underscore used as a -synonym/alias for :func:`gettext.gettext` or its brethren). - -The above classes are not included in Python, though they're easy enough to -copy and paste into your own code. They can be used as follows (assuming that -they're declared in a module called ``wherever``): - -.. code-block:: pycon - - >>> from wherever import BraceMessage as __ - >>> print(__('Message with {0} {name}', 2, name='placeholders')) - Message with 2 placeholders - >>> class Point: pass - ... - >>> p = Point() - >>> p.x = 0.5 - >>> p.y = 0.5 - >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', - ... point=p)) - Message with coordinates: (0.50, 0.50) - >>> from wherever import DollarMessage as __ - >>> print(__('Message with $num $what', num=2, what='placeholders')) - Message with 2 placeholders - >>> - -While the above examples use ``print()`` to show how the formatting works, you -would of course use ``logger.debug()`` or similar to actually log using this -approach. - -One thing to note is that you pay no significant performance penalty with this -approach: the actual formatting happens not when you make the logging call, but -when (and if) the logged message is actually about to be output to a log by a -handler. So the only slightly unusual thing which might trip you up is that the -parentheses go around the format string and the arguments, not just the format -string. That's because the __ notation is just syntax sugar for a constructor -call to one of the XXXMessage classes. - -If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect -to the above, as in the following example:: - - import logging - - class Message: - def __init__(self, fmt, args): - self.fmt = fmt - self.args = args - - def __str__(self): - return self.fmt.format(*self.args) - - class StyleAdapter(logging.LoggerAdapter): - def __init__(self, logger, extra=None): - super(StyleAdapter, self).__init__(logger, extra or {}) - - def log(self, level, msg, /, *args, **kwargs): - if self.isEnabledFor(level): - msg, kwargs = self.process(msg, kwargs) - self.logger._log(level, Message(msg, args), (), **kwargs) - - logger = StyleAdapter(logging.getLogger(__name__)) - - def main(): - logger.debug('Hello, {}', 'world!') - - if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - main() - -The above script should log the message ``Hello, world!`` when run with -Python 3.2 or later. - - -.. currentmodule:: logging - -.. _custom-logrecord: - -Customizing ``LogRecord`` -------------------------- - -Every logging event is represented by a :class:`LogRecord` instance. -When an event is logged and not filtered out by a logger's level, a -:class:`LogRecord` is created, populated with information about the event and -then passed to the handlers for that logger (and its ancestors, up to and -including the logger where further propagation up the hierarchy is disabled). -Before Python 3.2, there were only two places where this creation was done: - -* :meth:`Logger.makeRecord`, which is called in the normal process of - logging an event. This invoked :class:`LogRecord` directly to create an - instance. -* :func:`makeLogRecord`, which is called with a dictionary containing - attributes to be added to the LogRecord. This is typically invoked when a - suitable dictionary has been received over the network (e.g. in pickle form - via a :class:`~handlers.SocketHandler`, or in JSON form via an - :class:`~handlers.HTTPHandler`). - -This has usually meant that if you need to do anything special with a -:class:`LogRecord`, you've had to do one of the following. - -* Create your own :class:`Logger` subclass, which overrides - :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass` - before any loggers that you care about are instantiated. -* Add a :class:`Filter` to a logger or handler, which does the - necessary special manipulation you need when its - :meth:`~Filter.filter` method is called. - -The first approach would be a little unwieldy in the scenario where (say) -several different libraries wanted to do different things. Each would attempt -to set its own :class:`Logger` subclass, and the one which did this last would -win. - -The second approach works reasonably well for many cases, but does not allow -you to e.g. use a specialized subclass of :class:`LogRecord`. Library -developers can set a suitable filter on their loggers, but they would have to -remember to do this every time they introduced a new logger (which they would -do simply by adding new packages or modules and doing :: - - logger = logging.getLogger(__name__) - -at module level). It's probably one too many things to think about. Developers -could also add the filter to a :class:`~logging.NullHandler` attached to their -top-level logger, but this would not be invoked if an application developer -attached a handler to a lower-level library logger --- so output from that -handler would not reflect the intentions of the library developer. - -In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a -factory, which you can specify. The factory is just a callable you can set with -:func:`~logging.setLogRecordFactory`, and interrogate with -:func:`~logging.getLogRecordFactory`. The factory is invoked with the same -signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord` -is the default setting for the factory. - -This approach allows a custom factory to control all aspects of LogRecord -creation. For example, you could return a subclass, or just add some additional -attributes to the record once created, using a pattern similar to this:: - - old_factory = logging.getLogRecordFactory() - - def record_factory(*args, **kwargs): - record = old_factory(*args, **kwargs) - record.custom_attribute = 0xdecafbad - return record - - logging.setLogRecordFactory(record_factory) - -This pattern allows different libraries to chain factories together, and as -long as they don't overwrite each other's attributes or unintentionally -overwrite the attributes provided as standard, there should be no surprises. -However, it should be borne in mind that each link in the chain adds run-time -overhead to all logging operations, and the technique should only be used when -the use of a :class:`Filter` does not provide the desired result. - - -.. _zeromq-handlers: - -Subclassing QueueHandler - a ZeroMQ example -------------------------------------------- - -You can use a :class:`QueueHandler` subclass to send messages to other kinds -of queues, for example a ZeroMQ 'publish' socket. In the example below,the -socket is created separately and passed to the handler (as its 'queue'):: - - import zmq # using pyzmq, the Python binding for ZeroMQ - import json # for serializing records portably - - ctx = zmq.Context() - sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value - sock.bind('tcp://*:5556') # or wherever - - class ZeroMQSocketHandler(QueueHandler): - def enqueue(self, record): - self.queue.send_json(record.__dict__) - - - handler = ZeroMQSocketHandler(sock) - - -Of course there are other ways of organizing this, for example passing in the -data needed by the handler to create the socket:: - - class ZeroMQSocketHandler(QueueHandler): - def __init__(self, uri, socktype=zmq.PUB, ctx=None): - self.ctx = ctx or zmq.Context() - socket = zmq.Socket(self.ctx, socktype) - socket.bind(uri) - super().__init__(socket) - - def enqueue(self, record): - self.queue.send_json(record.__dict__) - - def close(self): - self.queue.close() - - -Subclassing QueueListener - a ZeroMQ example --------------------------------------------- - -You can also subclass :class:`QueueListener` to get messages from other kinds -of queues, for example a ZeroMQ 'subscribe' socket. Here's an example:: - - class ZeroMQSocketListener(QueueListener): - def __init__(self, uri, /, *handlers, **kwargs): - self.ctx = kwargs.get('ctx') or zmq.Context() - socket = zmq.Socket(self.ctx, zmq.SUB) - socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to everything - socket.connect(uri) - super().__init__(socket, *handlers, **kwargs) - - def dequeue(self): - msg = self.queue.recv_json() - return logging.makeLogRecord(msg) - - -.. seealso:: - - Module :mod:`logging` - API reference for the logging module. - - Module :mod:`logging.config` - Configuration API for the logging module. - - Module :mod:`logging.handlers` - Useful handlers included with the logging module. - - :ref:`A basic logging tutorial <logging-basic-tutorial>` - - :ref:`A more advanced logging tutorial <logging-advanced-tutorial>` - - An example dictionary-based configuration ----------------------------------------- @@ -1427,280 +765,24 @@ For more information about this configuration, you can see the `relevant section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_ of the Django documentation. -.. _cookbook-rotator-namer: - -Using a rotator and namer to customize log rotation processing --------------------------------------------------------------- - -An example of how you can define a namer and rotator is given in the following -snippet, which shows zlib-based compression of the log file:: - - def namer(name): - return name + ".gz" - - def rotator(source, dest): - with open(source, "rb") as sf: - data = sf.read() - compressed = zlib.compress(data, 9) - with open(dest, "wb") as df: - df.write(compressed) - os.remove(source) - - rh = logging.handlers.RotatingFileHandler(...) - rh.rotator = rotator - rh.namer = namer - -These are not "true" .gz files, as they are bare compressed data, with no -"container" such as you’d find in an actual gzip file. This snippet is just -for illustration purposes. - -A more elaborate multiprocessing example ----------------------------------------- - -The following working example shows how logging can be used with multiprocessing -using configuration files. The configurations are fairly simple, but serve to -illustrate how more complex ones could be implemented in a real multiprocessing -scenario. - -In the example, the main process spawns a listener process and some worker -processes. Each of the main process, the listener and the workers have three -separate configurations (the workers all share the same configuration). We can -see logging in the main process, how the workers log to a QueueHandler and how -the listener implements a QueueListener and a more complex logging -configuration, and arranges to dispatch events received via the queue to the -handlers specified in the configuration. Note that these configurations are -purely illustrative, but you should be able to adapt this example to your own -scenario. - -Here's the script - the docstrings and the comments hopefully explain how it -works:: - - import logging - import logging.config - import logging.handlers - from multiprocessing import Process, Queue, Event, current_process - import os - import random - import time - - class MyHandler: - """ - A simple handler for logging events. It runs in the listener process and - dispatches events to loggers based on the name in the received record, - which then get dispatched, by the logging system, to the handlers - configured for those loggers. - """ - - def handle(self, record): - if record.name == "root": - logger = logging.getLogger() - else: - logger = logging.getLogger(record.name) - - if logger.isEnabledFor(record.levelno): - # The process name is transformed just to show that it's the listener - # doing the logging to files and console - record.processName = '%s (for %s)' % (current_process().name, record.processName) - logger.handle(record) - - def listener_process(q, stop_event, config): - """ - This could be done in the main process, but is just done in a separate - process for illustrative purposes. - - This initialises logging according to the specified configuration, - starts the listener and waits for the main process to signal completion - via the event. The listener is then stopped, and the process exits. - """ - logging.config.dictConfig(config) - listener = logging.handlers.QueueListener(q, MyHandler()) - listener.start() - if os.name == 'posix': - # On POSIX, the setup logger will have been configured in the - # parent process, but should have been disabled following the - # dictConfig call. - # On Windows, since fork isn't used, the setup logger won't - # exist in the child, so it would be created and the message - # would appear - hence the "if posix" clause. - logger = logging.getLogger('setup') - logger.critical('Should not appear, because of disabled logger ...') - stop_event.wait() - listener.stop() - - def worker_process(config): - """ - A number of these are spawned for the purpose of illustration. In - practice, they could be a heterogeneous bunch of processes rather than - ones which are identical to each other. - - This initialises logging according to the specified configuration, - and logs a hundred messages with random levels to randomly selected - loggers. - - A small sleep is added to allow other processes a chance to run. This - is not strictly needed, but it mixes the output from the different - processes a bit more than if it's left out. - """ - logging.config.dictConfig(config) - levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, - logging.CRITICAL] - loggers = ['foo', 'foo.bar', 'foo.bar.baz', - 'spam', 'spam.ham', 'spam.ham.eggs'] - if os.name == 'posix': - # On POSIX, the setup logger will have been configured in the - # parent process, but should have been disabled following the - # dictConfig call. - # On Windows, since fork isn't used, the setup logger won't - # exist in the child, so it would be created and the message - # would appear - hence the "if posix" clause. - logger = logging.getLogger('setup') - logger.critical('Should not appear, because of disabled logger ...') - for i in range(100): - lvl = random.choice(levels) - logger = logging.getLogger(random.choice(loggers)) - logger.log(lvl, 'Message no. %d', i) - time.sleep(0.01) - - def main(): - q = Queue() - # The main process gets a simple configuration which prints to the console. - config_initial = { - 'version': 1, - 'handlers': { - 'console': { - 'class': 'logging.StreamHandler', - 'level': 'INFO' - } - }, - 'root': { - 'handlers': ['console'], - 'level': 'DEBUG' - } - } - # The worker process configuration is just a QueueHandler attached to the - # root logger, which allows all messages to be sent to the queue. - # We disable existing loggers to disable the "setup" logger used in the - # parent process. This is needed on POSIX because the logger will - # be there in the child following a fork(). - config_worker = { - 'version': 1, - 'disable_existing_loggers': True, - 'handlers': { - 'queue': { - 'class': 'logging.handlers.QueueHandler', - 'queue': q - } - }, - 'root': { - 'handlers': ['queue'], - 'level': 'DEBUG' - } - } - # The listener process configuration shows that the full flexibility of - # logging configuration is available to dispatch events to handlers however - # you want. - # We disable existing loggers to disable the "setup" logger used in the - # parent process. This is needed on POSIX because the logger will - # be there in the child following a fork(). - config_listener = { - 'version': 1, - 'disable_existing_loggers': True, - 'formatters': { - 'detailed': { - 'class': 'logging.Formatter', - 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' - }, - 'simple': { - 'class': 'logging.Formatter', - 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s' - } - }, - 'handlers': { - 'console': { - 'class': 'logging.StreamHandler', - 'formatter': 'simple', - 'level': 'INFO' - }, - 'file': { - 'class': 'logging.FileHandler', - 'filename': 'mplog.log', - 'mode': 'w', - 'formatter': 'detailed' - }, - 'foofile': { - 'class': 'logging.FileHandler', - 'filename': 'mplog-foo.log', - 'mode': 'w', - 'formatter': 'detailed' - }, - 'errors': { - 'class': 'logging.FileHandler', - 'filename': 'mplog-errors.log', - 'mode': 'w', - 'formatter': 'detailed', - 'level': 'ERROR' - } - }, - 'loggers': { - 'foo': { - 'handlers': ['foofile'] - } - }, - 'root': { - 'handlers': ['console', 'file', 'errors'], - 'level': 'DEBUG' - } - } - # Log some initial events, just to show that logging in the parent works - # normally. - logging.config.dictConfig(config_initial) - logger = logging.getLogger('setup') - logger.info('About to create workers ...') - workers = [] - for i in range(5): - wp = Process(target=worker_process, name='worker %d' % (i + 1), - args=(config_worker,)) - workers.append(wp) - wp.start() - logger.info('Started worker: %s', wp.name) - logger.info('About to create listener ...') - stop_event = Event() - lp = Process(target=listener_process, name='listener', - args=(q, stop_event, config_listener)) - lp.start() - logger.info('Started listener') - # We now hang around for the workers to finish their work. - for wp in workers: - wp.join() - # Workers all done, listening can now stop. - # Logging in the parent still works normally. - logger.info('Telling listener to stop ...') - stop_event.set() - lp.join() - logger.info('All done.') - - if __name__ == '__main__': - main() - - Inserting a BOM into messages sent to a SysLogHandler ----------------------------------------------------- -:rfc:`5424` requires that a +`RFC 5424 <https://tools.ietf.org/html/rfc5424>`_ requires that a Unicode message be sent to a syslog daemon as a set of bytes which have the following structure: an optional pure-ASCII component, followed by a UTF-8 Byte -Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the -:rfc:`relevant section of the specification <5424#section-6>`.) +Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant +section of the specification <https://tools.ietf.org/html/rfc5424#section-6>`_.) -In Python 3.1, code was added to +In Python 2.6 and 2.7, code was added to :class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but unfortunately, it was implemented incorrectly, with the BOM appearing at the beginning of the message and hence not allowing any pure-ASCII component to appear before it. As this behaviour is broken, the incorrect BOM insertion code is being removed -from Python 3.2.4 and later. However, it is not being replaced, and if you -want to produce :rfc:`5424`-compliant messages which include a BOM, an optional +from Python 2.7.4 and later. However, it is not being replaced, and if you +want to produce RFC 5424-compliant messages which include a BOM, an optional pure-ASCII sequence before it and arbitrary Unicode after it, encoded using UTF-8, then you need to do the following: @@ -1708,10 +790,10 @@ UTF-8, then you need to do the following: :class:`~logging.handlers.SysLogHandler` instance, with a format string such as:: - 'ASCII section\ufeffUnicode section' + u'ASCII section\ufeffUnicode section' - The Unicode code point U+FEFF, when encoded using UTF-8, will be - encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``. + The Unicode code point ``u'\ufeff'``, when encoded using UTF-8, will be + encoded as a UTF-8 BOM -- the byte-string ``'\xef\xbb\xbf'``. #. Replace the ASCII section with whatever placeholders you like, but make sure that the data that appears in there after substitution is always ASCII (that @@ -1721,10 +803,11 @@ UTF-8, then you need to do the following: which appears there after substitution contains characters outside the ASCII range, that's fine -- it will be encoded using UTF-8. -The formatted message *will* be encoded using UTF-8 encoding by -``SysLogHandler``. If you follow the above rules, you should be able to produce -:rfc:`5424`-compliant messages. If you don't, logging may not complain, but your -messages will not be RFC 5424-compliant, and your syslog daemon may complain. +If the formatted message is Unicode, it *will* be encoded using UTF-8 encoding +by ``SysLogHandler``. If you follow the above rules, you should be able to +produce RFC 5424-compliant messages. If you don't, logging may not complain, +but your messages will not be RFC 5424-compliant, and your syslog daemon may +complain. Implementing structured logging @@ -1741,8 +824,8 @@ which uses JSON to serialise the event in a machine-parseable manner:: import json import logging - class StructuredMessage: - def __init__(self, message, /, **kwargs): + class StructuredMessage(object): + def __init__(self, message, **kwargs): self.message = message self.kwargs = kwargs @@ -1754,9 +837,7 @@ which uses JSON to serialise the event in a machine-parseable manner:: logging.basicConfig(level=logging.INFO, format='%(message)s') logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456)) -If the above script is run, it prints: - -.. code-block:: none +If the above script is run, it prints:: message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"} @@ -1785,8 +866,8 @@ as in the following complete example:: return o.encode('unicode_escape').decode('ascii') return super(Encoder, self).default(o) - class StructuredMessage: - def __init__(self, message, /, **kwargs): + class StructuredMessage(object): + def __init__(self, message, **kwargs): self.message = message self.kwargs = kwargs @@ -1798,14 +879,12 @@ as in the following complete example:: def main(): logging.basicConfig(level=logging.INFO, format='%(message)s') - logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603')) + logging.info(_('message 1', set_value=set([1, 2, 3]), snowman='\u2603')) if __name__ == '__main__': main() -When the above script is run, it prints: - -.. code-block:: none +When the above script is run, it prints:: message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]} @@ -1823,15 +902,20 @@ Customizing handlers with :func:`dictConfig` There are times when you want to customize logging handlers in particular ways, and if you use :func:`dictConfig` you may be able to do this without subclassing. As an example, consider that you may want to set the ownership of a -log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file +log file. On POSIX, this is easily done using :func:`os.chown`, but the file handlers in the stdlib don't offer built-in support. You can customize handler creation using a plain function such as:: def owned_file_handler(filename, mode='a', encoding=None, owner=None): if owner: + import os, pwd, grp + # convert user and group names to uid and gid + uid = pwd.getpwnam(owner[0]).pw_uid + gid = grp.getgrnam(owner[1]).gr_gid + owner = (uid, gid) if not os.path.exists(filename): open(filename, 'a').close() - shutil.chown(filename, *owner) + os.chown(filename, *owner) return logging.FileHandler(filename, mode, encoding) You can then specify, in a logging configuration passed to :func:`dictConfig`, @@ -1953,130 +1037,8 @@ Of course, the approach could also be extended to types of handler other than a or a different type of handler altogether. -.. currentmodule:: logging - -.. _formatting-styles: - -Using particular formatting styles throughout your application --------------------------------------------------------------- - -In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword -parameter which, while defaulting to ``%`` for backward compatibility, allowed -the specification of ``{`` or ``$`` to support the formatting approaches -supported by :meth:`str.format` and :class:`string.Template`. Note that this -governs the formatting of logging messages for final output to logs, and is -completely orthogonal to how an individual logging message is constructed. - -Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take -positional parameters for the actual logging message itself, with keyword -parameters used only for determining options for how to handle the logging call -(e.g. the ``exc_info`` keyword parameter to indicate that traceback information -should be logged, or the ``extra`` keyword parameter to indicate additional -contextual information to be added to the log). So you cannot directly make -logging calls using :meth:`str.format` or :class:`string.Template` syntax, -because internally the logging package uses %-formatting to merge the format -string and the variable arguments. There would no changing this while preserving -backward compatibility, since all logging calls which are out there in existing -code will be using %-format strings. - -There have been suggestions to associate format styles with specific loggers, -but that approach also runs into backward compatibility problems because any -existing code could be using a given logger name and using %-formatting. - -For logging to work interoperably between any third-party libraries and your -code, decisions about formatting need to be made at the level of the -individual logging call. This opens up a couple of ways in which alternative -formatting styles can be accommodated. - - -Using LogRecord factories -^^^^^^^^^^^^^^^^^^^^^^^^^ - -In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned -above, the logging package gained the ability to allow users to set their own -:class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function. -You can use this to set your own subclass of :class:`LogRecord`, which does the -Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base -class implementation of this method is where the ``msg % args`` formatting -happens, and where you can substitute your alternate formatting; however, you -should be careful to support all formatting styles and allow %-formatting as -the default, to ensure interoperability with other code. Care should also be -taken to call ``str(self.msg)``, just as the base implementation does. - -Refer to the reference documentation on :func:`setLogRecordFactory` and -:class:`LogRecord` for more information. - - -Using custom message objects -^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -There is another, perhaps simpler way that you can use {}- and $- formatting to -construct your individual log messages. You may recall (from -:ref:`arbitrary-object-messages`) that when logging you can use an arbitrary -object as a message format string, and that the logging package will call -:func:`str` on that object to get the actual format string. Consider the -following two classes:: - - class BraceMessage: - def __init__(self, fmt, /, *args, **kwargs): - self.fmt = fmt - self.args = args - self.kwargs = kwargs - - def __str__(self): - return self.fmt.format(*self.args, **self.kwargs) - - class DollarMessage: - def __init__(self, fmt, /, **kwargs): - self.fmt = fmt - self.kwargs = kwargs - - def __str__(self): - from string import Template - return Template(self.fmt).substitute(**self.kwargs) - -Either of these can be used in place of a format string, to allow {}- or -$-formatting to be used to build the actual "message" part which appears in the -formatted log output in place of “%(message)s” or “{message}” or “$message”. -If you find it a little unwieldy to use the class names whenever you want to log -something, you can make it more palatable if you use an alias such as ``M`` or -``_`` for the message (or perhaps ``__``, if you are using ``_`` for -localization). - -Examples of this approach are given below. Firstly, formatting with -:meth:`str.format`:: - - >>> __ = BraceMessage - >>> print(__('Message with {0} {1}', 2, 'placeholders')) - Message with 2 placeholders - >>> class Point: pass - ... - >>> p = Point() - >>> p.x = 0.5 - >>> p.y = 0.5 - >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p)) - Message with coordinates: (0.50, 0.50) - -Secondly, formatting with :class:`string.Template`:: - - >>> __ = DollarMessage - >>> print(__('Message with $num $what', num=2, what='placeholders')) - Message with 2 placeholders - >>> - -One thing to note is that you pay no significant performance penalty with this -approach: the actual formatting happens not when you make the logging call, but -when (and if) the logged message is actually about to be output to a log by a -handler. So the only slightly unusual thing which might trip you up is that the -parentheses go around the format string and the arguments, not just the format -string. That’s because the __ notation is just syntax sugar for a constructor -call to one of the ``XXXMessage`` classes shown above. - - .. _filters-dictconfig: -.. currentmodule:: logging.config - Configuring filters with :func:`dictConfig` ------------------------------------------- @@ -2135,9 +1097,7 @@ most obvious, but you can provide any callable which returns a This example shows how you can pass configuration data to the callable which constructs the instance, in the form of keyword parameters. When run, the above -script will print: - -.. code-block:: none +script will print:: changed: hello @@ -2176,7 +1136,7 @@ class, as shown in the following example:: Format an exception so that it prints on a single line. """ result = super(OneLineExceptionFormatter, self).formatException(exc_info) - return repr(result) # or format into one line however you want to + return repr(result) # or format into one line however you want to def format(self, record): s = super(OneLineExceptionFormatter, self).format(record) @@ -2204,9 +1164,7 @@ class, as shown in the following example:: if __name__ == '__main__': main() -When run, this produces a file with exactly two lines: - -.. code-block:: none +When run, this produces a file with exactly two lines:: 28/01/2015 07:21:23|INFO|Sample message| 28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n File "logtest7.py", line 30, in main\n x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'| @@ -2268,7 +1226,6 @@ The above approach can, of course, be adapted to other TTS systems and even other systems altogether which can process messages via external programs run from a command line. - .. _buffered-logging: Buffering logging messages and outputting them conditionally @@ -2301,9 +1258,9 @@ The script just arranges to decorate ``foo`` with a decorator which will do the conditional logging that's required. The decorator takes a logger as a parameter and attaches a memory handler for the duration of the call to the decorated function. The decorator can be additionally parameterised using a target handler, -a level at which flushing should occur, and a capacity for the buffer (number of -records buffered). These default to a :class:`~logging.StreamHandler` which -writes to ``sys.stderr``, ``logging.ERROR`` and ``100`` respectively. +a level at which flushing should occur, and a capacity for the buffer. These +default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``, +``logging.ERROR`` and ``100`` respectively. Here's the script:: @@ -2368,9 +1325,7 @@ Here's the script:: write_line('Calling decorated foo with True') assert decorated_foo(True) -When this script is run, the following output should be observed: - -.. code-block:: none +When this script is run, the following output should be observed:: Calling undecorated foo with False about to log at DEBUG ... @@ -2466,9 +1421,7 @@ the following complete example:: logging.config.dictConfig(LOGGING) logging.warning('The local time is %s', time.asctime()) -When this script is run, it should print something like: - -.. code-block:: none +When this script is run, it should print something like:: 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015 @@ -2492,7 +1445,7 @@ scope of the context manager:: import logging import sys - class LoggingContext: + class LoggingContext(object): def __init__(self, logger, level=None, handler=None, close=True): self.logger = logger self.level = level @@ -2583,399 +1536,3 @@ In this case, the message #5 printed to ``stdout`` doesn't appear, as expected. Of course, the approach described here can be generalised, for example to attach logging filters temporarily. Note that the above code works in Python 2 as well as Python 3. - - -.. _starter-template: - -A CLI application starter template ----------------------------------- - -Here's an example which shows how you can: - -* Use a logging level based on command-line arguments -* Dispatch to multiple subcommands in separate files, all logging at the same - level in a consistent way -* Make use of simple, minimal configuration - -Suppose we have a command-line application whose job is to stop, start or -restart some services. This could be organised for the purposes of illustration -as a file ``app.py`` that is the main script for the application, with individual -commands implemented in ``start.py``, ``stop.py`` and ``restart.py``. Suppose -further that we want to control the verbosity of the application via a -command-line argument, defaulting to ``logging.INFO``. Here's one way that -``app.py`` could be written:: - - import argparse - import importlib - import logging - import os - import sys - - def main(args=None): - scriptname = os.path.basename(__file__) - parser = argparse.ArgumentParser(scriptname) - levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL') - parser.add_argument('--log-level', default='INFO', choices=levels) - subparsers = parser.add_subparsers(dest='command', - help='Available commands:') - start_cmd = subparsers.add_parser('start', help='Start a service') - start_cmd.add_argument('name', metavar='NAME', - help='Name of service to start') - stop_cmd = subparsers.add_parser('stop', - help='Stop one or more services') - stop_cmd.add_argument('names', metavar='NAME', nargs='+', - help='Name of service to stop') - restart_cmd = subparsers.add_parser('restart', - help='Restart one or more services') - restart_cmd.add_argument('names', metavar='NAME', nargs='+', - help='Name of service to restart') - options = parser.parse_args() - # the code to dispatch commands could all be in this file. For the purposes - # of illustration only, we implement each command in a separate module. - try: - mod = importlib.import_module(options.command) - cmd = getattr(mod, 'command') - except (ImportError, AttributeError): - print('Unable to find the code for command \'%s\'' % options.command) - return 1 - # Could get fancy here and load configuration from file or dictionary - logging.basicConfig(level=options.log_level, - format='%(levelname)s %(name)s %(message)s') - cmd(options) - - if __name__ == '__main__': - sys.exit(main()) - -And the ``start``, ``stop`` and ``restart`` commands can be implemented in -separate modules, like so for starting:: - - # start.py - import logging - - logger = logging.getLogger(__name__) - - def command(options): - logger.debug('About to start %s', options.name) - # actually do the command processing here ... - logger.info('Started the \'%s\' service.', options.name) - -and thus for stopping:: - - # stop.py - import logging - - logger = logging.getLogger(__name__) - - def command(options): - n = len(options.names) - if n == 1: - plural = '' - services = '\'%s\'' % options.names[0] - else: - plural = 's' - services = ', '.join('\'%s\'' % name for name in options.names) - i = services.rfind(', ') - services = services[:i] + ' and ' + services[i + 2:] - logger.debug('About to stop %s', services) - # actually do the command processing here ... - logger.info('Stopped the %s service%s.', services, plural) - -and similarly for restarting:: - - # restart.py - import logging - - logger = logging.getLogger(__name__) - - def command(options): - n = len(options.names) - if n == 1: - plural = '' - services = '\'%s\'' % options.names[0] - else: - plural = 's' - services = ', '.join('\'%s\'' % name for name in options.names) - i = services.rfind(', ') - services = services[:i] + ' and ' + services[i + 2:] - logger.debug('About to restart %s', services) - # actually do the command processing here ... - logger.info('Restarted the %s service%s.', services, plural) - -If we run this application with the default log level, we get output like this: - -.. code-block:: shell-session - - $ python app.py start foo - INFO start Started the 'foo' service. - - $ python app.py stop foo bar - INFO stop Stopped the 'foo' and 'bar' services. - - $ python app.py restart foo bar baz - INFO restart Restarted the 'foo', 'bar' and 'baz' services. - -The first word is the logging level, and the second word is the module or -package name of the place where the event was logged. - -If we change the logging level, then we can change the information sent to the -log. For example, if we want more information: - -.. code-block:: shell-session - - $ python app.py --log-level DEBUG start foo - DEBUG start About to start foo - INFO start Started the 'foo' service. - - $ python app.py --log-level DEBUG stop foo bar - DEBUG stop About to stop 'foo' and 'bar' - INFO stop Stopped the 'foo' and 'bar' services. - - $ python app.py --log-level DEBUG restart foo bar baz - DEBUG restart About to restart 'foo', 'bar' and 'baz' - INFO restart Restarted the 'foo', 'bar' and 'baz' services. - -And if we want less: - -.. code-block:: shell-session - - $ python app.py --log-level WARNING start foo - $ python app.py --log-level WARNING stop foo bar - $ python app.py --log-level WARNING restart foo bar baz - -In this case, the commands don't print anything to the console, since nothing -at ``WARNING`` level or above is logged by them. - -.. _qt-gui: - -A Qt GUI for logging --------------------- - -A question that comes up from time to time is about how to log to a GUI -application. The `Qt <https://www.qt.io/>`_ framework is a popular -cross-platform UI framework with Python bindings using `PySide2 -<https://pypi.org/project/PySide2/>`_ or `PyQt5 -<https://pypi.org/project/PyQt5/>`_ libraries. - -The following example shows how to log to a Qt GUI. This introduces a simple -``QtHandler`` class which takes a callable, which should be a slot in the main -thread that does GUI updates. A worker thread is also created to show how you -can log to the GUI from both the UI itself (via a button for manual logging) -as well as a worker thread doing work in the background (here, just logging -messages at random levels with random short delays in between). - -The worker thread is implemented using Qt's ``QThread`` class rather than the -:mod:`threading` module, as there are circumstances where one has to use -``QThread``, which offers better integration with other ``Qt`` components. - -The code should work with recent releases of either ``PySide2`` or ``PyQt5``. -You should be able to adapt the approach to earlier versions of Qt. Please -refer to the comments in the code snippet for more detailed information. - -.. code-block:: python3 - - import datetime - import logging - import random - import sys - import time - - # Deal with minor differences between PySide2 and PyQt5 - try: - from PySide2 import QtCore, QtGui, QtWidgets - Signal = QtCore.Signal - Slot = QtCore.Slot - except ImportError: - from PyQt5 import QtCore, QtGui, QtWidgets - Signal = QtCore.pyqtSignal - Slot = QtCore.pyqtSlot - - - logger = logging.getLogger(__name__) - - - # - # Signals need to be contained in a QObject or subclass in order to be correctly - # initialized. - # - class Signaller(QtCore.QObject): - signal = Signal(str, logging.LogRecord) - - # - # Output to a Qt GUI is only supposed to happen on the main thread. So, this - # handler is designed to take a slot function which is set up to run in the main - # thread. In this example, the function takes a string argument which is a - # formatted log message, and the log record which generated it. The formatted - # string is just a convenience - you could format a string for output any way - # you like in the slot function itself. - # - # You specify the slot function to do whatever GUI updates you want. The handler - # doesn't know or care about specific UI elements. - # - class QtHandler(logging.Handler): - def __init__(self, slotfunc, *args, **kwargs): - super(QtHandler, self).__init__(*args, **kwargs) - self.signaller = Signaller() - self.signaller.signal.connect(slotfunc) - - def emit(self, record): - s = self.format(record) - self.signaller.signal.emit(s, record) - - # - # This example uses QThreads, which means that the threads at the Python level - # are named something like "Dummy-1". The function below gets the Qt name of the - # current thread. - # - def ctname(): - return QtCore.QThread.currentThread().objectName() - - - # - # Used to generate random levels for logging. - # - LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, - logging.CRITICAL) - - # - # This worker class represents work that is done in a thread separate to the - # main thread. The way the thread is kicked off to do work is via a button press - # that connects to a slot in the worker. - # - # Because the default threadName value in the LogRecord isn't much use, we add - # a qThreadName which contains the QThread name as computed above, and pass that - # value in an "extra" dictionary which is used to update the LogRecord with the - # QThread name. - # - # This example worker just outputs messages sequentially, interspersed with - # random delays of the order of a few seconds. - # - class Worker(QtCore.QObject): - @Slot() - def start(self): - extra = {'qThreadName': ctname() } - logger.debug('Started work', extra=extra) - i = 1 - # Let the thread run until interrupted. This allows reasonably clean - # thread termination. - while not QtCore.QThread.currentThread().isInterruptionRequested(): - delay = 0.5 + random.random() * 2 - time.sleep(delay) - level = random.choice(LEVELS) - logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra) - i += 1 - - # - # Implement a simple UI for this cookbook example. This contains: - # - # * A read-only text edit window which holds formatted log messages - # * A button to start work and log stuff in a separate thread - # * A button to log something from the main thread - # * A button to clear the log window - # - class Window(QtWidgets.QWidget): - - COLORS = { - logging.DEBUG: 'black', - logging.INFO: 'blue', - logging.WARNING: 'orange', - logging.ERROR: 'red', - logging.CRITICAL: 'purple', - } - - def __init__(self, app): - super(Window, self).__init__() - self.app = app - self.textedit = te = QtWidgets.QPlainTextEdit(self) - # Set whatever the default monospace font is for the platform - f = QtGui.QFont('nosuchfont') - f.setStyleHint(f.Monospace) - te.setFont(f) - te.setReadOnly(True) - PB = QtWidgets.QPushButton - self.work_button = PB('Start background work', self) - self.log_button = PB('Log a message at a random level', self) - self.clear_button = PB('Clear log window', self) - self.handler = h = QtHandler(self.update_status) - # Remember to use qThreadName rather than threadName in the format string. - fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s' - formatter = logging.Formatter(fs) - h.setFormatter(formatter) - logger.addHandler(h) - # Set up to terminate the QThread when we exit - app.aboutToQuit.connect(self.force_quit) - - # Lay out all the widgets - layout = QtWidgets.QVBoxLayout(self) - layout.addWidget(te) - layout.addWidget(self.work_button) - layout.addWidget(self.log_button) - layout.addWidget(self.clear_button) - self.setFixedSize(900, 400) - - # Connect the non-worker slots and signals - self.log_button.clicked.connect(self.manual_update) - self.clear_button.clicked.connect(self.clear_display) - - # Start a new worker thread and connect the slots for the worker - self.start_thread() - self.work_button.clicked.connect(self.worker.start) - # Once started, the button should be disabled - self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False)) - - def start_thread(self): - self.worker = Worker() - self.worker_thread = QtCore.QThread() - self.worker.setObjectName('Worker') - self.worker_thread.setObjectName('WorkerThread') # for qThreadName - self.worker.moveToThread(self.worker_thread) - # This will start an event loop in the worker thread - self.worker_thread.start() - - def kill_thread(self): - # Just tell the worker to stop, then tell it to quit and wait for that - # to happen - self.worker_thread.requestInterruption() - if self.worker_thread.isRunning(): - self.worker_thread.quit() - self.worker_thread.wait() - else: - print('worker has already exited.') - - def force_quit(self): - # For use when the window is closed - if self.worker_thread.isRunning(): - self.kill_thread() - - # The functions below update the UI and run in the main thread because - # that's where the slots are set up - - @Slot(str, logging.LogRecord) - def update_status(self, status, record): - color = self.COLORS.get(record.levelno, 'black') - s = '<pre><font color="%s">%s</font></pre>' % (color, status) - self.textedit.appendHtml(s) - - @Slot() - def manual_update(self): - # This function uses the formatted message passed in, but also uses - # information from the record to format the message in an appropriate - # color according to its severity (level). - level = random.choice(LEVELS) - extra = {'qThreadName': ctname() } - logger.log(level, 'Manually logged!', extra=extra) - - @Slot() - def clear_display(self): - self.textedit.clear() - - - def main(): - QtCore.QThread.currentThread().setObjectName('MainThread') - logging.getLogger().setLevel(logging.DEBUG) - app = QtWidgets.QApplication(sys.argv) - example = Window(app) - example.show() - sys.exit(app.exec_()) - - if __name__=='__main__': - main() |