Debian Codegraph @

Doc/howto/logging-cookbook.rst

raw
1 .. _logging-cookbook:
2
3 ================
4 Logging Cookbook
5 ================
6
7 :Author: Vinay Sajip <vinay_sajip at red-dove dot com>
8
9 This page contains a number of recipes related to logging, which have been found
10 useful in the past. For links to tutorial and reference information, please see
11 :ref:`cookbook-ref-links`.
12
13 .. currentmodule:: logging
14
15 Using logging in multiple modules
16 ---------------------------------
17
18 Multiple calls to ``logging.getLogger('someLogger')`` return a reference to the
19 same logger object. This is true not only within the same module, but also
20 across modules as long as it is in the same Python interpreter process. It is
21 true for references to the same object; additionally, application code can
22 define and configure a parent logger in one module and create (but not
23 configure) a child logger in a separate module, and all logger calls to the
24 child will pass up to the parent. Here is a main module::
25
26 import logging
27 import auxiliary_module
28
29 # create logger with 'spam_application'
30 logger = logging.getLogger('spam_application')
31 logger.setLevel(logging.DEBUG)
32 # create file handler which logs even debug messages
33 fh = logging.FileHandler('spam.log')
34 fh.setLevel(logging.DEBUG)
35 # create console handler with a higher log level
36 ch = logging.StreamHandler()
37 ch.setLevel(logging.ERROR)
38 # create formatter and add it to the handlers
39 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
40 fh.setFormatter(formatter)
41 ch.setFormatter(formatter)
42 # add the handlers to the logger
43 logger.addHandler(fh)
44 logger.addHandler(ch)
45
46 logger.info('creating an instance of auxiliary_module.Auxiliary')
47 a = auxiliary_module.Auxiliary()
48 logger.info('created an instance of auxiliary_module.Auxiliary')
49 logger.info('calling auxiliary_module.Auxiliary.do_something')
50 a.do_something()
51 logger.info('finished auxiliary_module.Auxiliary.do_something')
52 logger.info('calling auxiliary_module.some_function()')
53 auxiliary_module.some_function()
54 logger.info('done with auxiliary_module.some_function()')
55
56 Here is the auxiliary module::
57
58 import logging
59
60 # create logger
61 module_logger = logging.getLogger('spam_application.auxiliary')
62
63 class Auxiliary:
64 def __init__(self):
65 self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
66 self.logger.info('creating an instance of Auxiliary')
67
68 def do_something(self):
69 self.logger.info('doing something')
70 a = 1 + 1
71 self.logger.info('done doing something')
72
73 def some_function():
74 module_logger.info('received a call to "some_function"')
75
76 The output looks like this:
77
78 .. code-block:: none
79
80 2005-03-23 23:47:11,663 - spam_application - INFO -
81 creating an instance of auxiliary_module.Auxiliary
82 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
83 creating an instance of Auxiliary
84 2005-03-23 23:47:11,665 - spam_application - INFO -
85 created an instance of auxiliary_module.Auxiliary
86 2005-03-23 23:47:11,668 - spam_application - INFO -
87 calling auxiliary_module.Auxiliary.do_something
88 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
89 doing something
90 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
91 done doing something
92 2005-03-23 23:47:11,670 - spam_application - INFO -
93 finished auxiliary_module.Auxiliary.do_something
94 2005-03-23 23:47:11,671 - spam_application - INFO -
95 calling auxiliary_module.some_function()
96 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
97 received a call to 'some_function'
98 2005-03-23 23:47:11,673 - spam_application - INFO -
99 done with auxiliary_module.some_function()
100
101 Logging from multiple threads
102 -----------------------------
103
104 Logging from multiple threads requires no special effort. The following example
105 shows logging from the main (initial) thread and another thread::
106
107 import logging
108 import threading
109 import time
110
111 def worker(arg):
112 while not arg['stop']:
113 logging.debug('Hi from myfunc')
114 time.sleep(0.5)
115
116 def main():
117 logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
118 info = {'stop': False}
119 thread = threading.Thread(target=worker, args=(info,))
120 thread.start()
121 while True:
122 try:
123 logging.debug('Hello from main')
124 time.sleep(0.75)
125 except KeyboardInterrupt:
126 info['stop'] = True
127 break
128 thread.join()
129
130 if __name__ == '__main__':
131 main()
132
133 When run, the script should print something like the following:
134
135 .. code-block:: none
136
137 0 Thread-1 Hi from myfunc
138 3 MainThread Hello from main
139 505 Thread-1 Hi from myfunc
140 755 MainThread Hello from main
141 1007 Thread-1 Hi from myfunc
142 1507 MainThread Hello from main
143 1508 Thread-1 Hi from myfunc
144 2010 Thread-1 Hi from myfunc
145 2258 MainThread Hello from main
146 2512 Thread-1 Hi from myfunc
147 3009 MainThread Hello from main
148 3013 Thread-1 Hi from myfunc
149 3515 Thread-1 Hi from myfunc
150 3761 MainThread Hello from main
151 4017 Thread-1 Hi from myfunc
152 4513 MainThread Hello from main
153 4518 Thread-1 Hi from myfunc
154
155 This shows the logging output interspersed as one might expect. This approach
156 works for more threads than shown here, of course.
157
158 Multiple handlers and formatters
159 --------------------------------
160
161 Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has no
162 minimum or maximum quota for the number of handlers you may add. Sometimes it
163 will be beneficial for an application to log all messages of all severities to a
164 text file while simultaneously logging errors or above to the console. To set
165 this up, simply configure the appropriate handlers. The logging calls in the
166 application code will remain unchanged. Here is a slight modification to the
167 previous simple module-based configuration example::
168
169 import logging
170
171 logger = logging.getLogger('simple_example')
172 logger.setLevel(logging.DEBUG)
173 # create file handler which logs even debug messages
174 fh = logging.FileHandler('spam.log')
175 fh.setLevel(logging.DEBUG)
176 # create console handler with a higher log level
177 ch = logging.StreamHandler()
178 ch.setLevel(logging.ERROR)
179 # create formatter and add it to the handlers
180 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
181 ch.setFormatter(formatter)
182 fh.setFormatter(formatter)
183 # add the handlers to logger
184 logger.addHandler(ch)
185 logger.addHandler(fh)
186
187 # 'application' code
188 logger.debug('debug message')
189 logger.info('info message')
190 logger.warning('warn message')
191 logger.error('error message')
192 logger.critical('critical message')
193
194 Notice that the 'application' code does not care about multiple handlers. All
195 that changed was the addition and configuration of a new handler named *fh*.
196
197 The ability to create new handlers with higher- or lower-severity filters can be
198 very helpful when writing and testing an application. Instead of using many
199 ``print`` statements for debugging, use ``logger.debug``: Unlike the print
200 statements, which you will have to delete or comment out later, the logger.debug
201 statements can remain intact in the source code and remain dormant until you
202 need them again. At that time, the only change that needs to happen is to
203 modify the severity level of the logger and/or handler to debug.
204
205 .. _multiple-destinations:
206
207 Logging to multiple destinations
208 --------------------------------
209
210 Let's say you want to log to console and file with different message formats and
211 in differing circumstances. Say you want to log messages with levels of DEBUG
212 and higher to file, and those messages at level INFO and higher to the console.
213 Let's also assume that the file should contain timestamps, but the console
214 messages should not. Here's how you can achieve this::
215
216 import logging
217
218 # set up logging to file - see previous section for more details
219 logging.basicConfig(level=logging.DEBUG,
220 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
221 datefmt='%m-%d %H:%M',
222 filename='/tmp/myapp.log',
223 filemode='w')
224 # define a Handler which writes INFO messages or higher to the sys.stderr
225 console = logging.StreamHandler()
226 console.setLevel(logging.INFO)
227 # set a format which is simpler for console use
228 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
229 # tell the handler to use this format
230 console.setFormatter(formatter)
231 # add the handler to the root logger
232 logging.getLogger().addHandler(console)
233
234 # Now, we can log to the root logger, or any other logger. First the root...
235 logging.info('Jackdaws love my big sphinx of quartz.')
236
237 # Now, define a couple of other loggers which might represent areas in your
238 # application:
239
240 logger1 = logging.getLogger('myapp.area1')
241 logger2 = logging.getLogger('myapp.area2')
242
243 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
244 logger1.info('How quickly daft jumping zebras vex.')
245 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
246 logger2.error('The five boxing wizards jump quickly.')
247
248 When you run this, on the console you will see
249
250 .. code-block:: none
251
252 root : INFO Jackdaws love my big sphinx of quartz.
253 myapp.area1 : INFO How quickly daft jumping zebras vex.
254 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
255 myapp.area2 : ERROR The five boxing wizards jump quickly.
256
257 and in the file you will see something like
258
259 .. code-block:: none
260
261 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
262 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
263 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
264 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
265 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
266
267 As you can see, the DEBUG message only shows up in the file. The other messages
268 are sent to both destinations.
269
270 This example uses console and file handlers, but you can use any number and
271 combination of handlers you choose.
272
273 Note that the above choice of log filename ``/tmp/myapp.log`` implies use of a
274 standard location for temporary files on POSIX systems. On Windows, you may need to
275 choose a different directory name for the log - just ensure that the directory exists
276 and that you have the permissions to create and update files in it.
277
278
279 .. _custom-level-handling:
280
281 Custom handling of levels
282 -------------------------
283
284 Sometimes, you might want to do something slightly different from the standard
285 handling of levels in handlers, where all levels above a threshold get
286 processed by a handler. To do this, you need to use filters. Let's look at a
287 scenario where you want to arrange things as follows:
288
289 * Send messages of severity ``INFO`` and ``WARNING`` to ``sys.stdout``
290 * Send messages of severity ``ERROR`` and above to ``sys.stderr``
291 * Send messages of severity ``DEBUG`` and above to file ``app.log``
292
293 Suppose you configure logging with the following JSON:
294
295 .. code-block:: json
296
297 {
298 "version": 1,
299 "disable_existing_loggers": false,
300 "formatters": {
301 "simple": {
302 "format": "%(levelname)-8s - %(message)s"
303 }
304 },
305 "handlers": {
306 "stdout": {
307 "class": "logging.StreamHandler",
308 "level": "INFO",
309 "formatter": "simple",
310 "stream": "ext://sys.stdout"
311 },
312 "stderr": {
313 "class": "logging.StreamHandler",
314 "level": "ERROR",
315 "formatter": "simple",
316 "stream": "ext://sys.stderr"
317 },
318 "file": {
319 "class": "logging.FileHandler",
320 "formatter": "simple",
321 "filename": "app.log",
322 "mode": "w"
323 }
324 },
325 "root": {
326 "level": "DEBUG",
327 "handlers": [
328 "stderr",
329 "stdout",
330 "file"
331 ]
332 }
333 }
334
335 This configuration does *almost* what we want, except that ``sys.stdout`` would show messages
336 of severity ``ERROR`` and only events of this severity and higher will be tracked
337 as well as ``INFO`` and ``WARNING`` messages. To prevent this, we can set up a filter which
338 excludes those messages and add it to the relevant handler. This can be configured by
339 adding a ``filters`` section parallel to ``formatters`` and ``handlers``:
340
341 .. code-block:: json
342
343 {
344 "filters": {
345 "warnings_and_below": {
346 "()" : "__main__.filter_maker",
347 "level": "WARNING"
348 }
349 }
350 }
351
352 and changing the section on the ``stdout`` handler to add it:
353
354 .. code-block:: json
355
356 {
357 "stdout": {
358 "class": "logging.StreamHandler",
359 "level": "INFO",
360 "formatter": "simple",
361 "stream": "ext://sys.stdout",
362 "filters": ["warnings_and_below"]
363 }
364 }
365
366 A filter is just a function, so we can define the ``filter_maker`` (a factory
367 function) as follows:
368
369 .. code-block:: python
370
371 def filter_maker(level):
372 level = getattr(logging, level)
373
374 def filter(record):
375 return record.levelno <= level
376
377 return filter
378
379 This converts the string argument passed in to a numeric level, and returns a
380 function which only returns ``True`` if the level of the passed in record is
381 at or below the specified level. Note that in this example I have defined the
382 ``filter_maker`` in a test script ``main.py`` that I run from the command line,
383 so its module will be ``__main__`` - hence the ``__main__.filter_maker`` in the
384 filter configuration. You will need to change that if you define it in a
385 different module.
386
387 With the filter added, we can run ``main.py``, which in full is:
388
389 .. code-block:: python
390
391 import json
392 import logging
393 import logging.config
394
395 CONFIG = '''
396 {
397 "version": 1,
398 "disable_existing_loggers": false,
399 "formatters": {
400 "simple": {
401 "format": "%(levelname)-8s - %(message)s"
402 }
403 },
404 "filters": {
405 "warnings_and_below": {
406 "()" : "__main__.filter_maker",
407 "level": "WARNING"
408 }
409 },
410 "handlers": {
411 "stdout": {
412 "class": "logging.StreamHandler",
413 "level": "INFO",
414 "formatter": "simple",
415 "stream": "ext://sys.stdout",
416 "filters": ["warnings_and_below"]
417 },
418 "stderr": {
419 "class": "logging.StreamHandler",
420 "level": "ERROR",
421 "formatter": "simple",
422 "stream": "ext://sys.stderr"
423 },
424 "file": {
425 "class": "logging.FileHandler",
426 "formatter": "simple",
427 "filename": "app.log",
428 "mode": "w"
429 }
430 },
431 "root": {
432 "level": "DEBUG",
433 "handlers": [
434 "stderr",
435 "stdout",
436 "file"
437 ]
438 }
439 }
440 '''
441
442 def filter_maker(level):
443 level = getattr(logging, level)
444
445 def filter(record):
446 return record.levelno <= level
447
448 return filter
449
450 logging.config.dictConfig(json.loads(CONFIG))
451 logging.debug('A DEBUG message')
452 logging.info('An INFO message')
453 logging.warning('A WARNING message')
454 logging.error('An ERROR message')
455 logging.critical('A CRITICAL message')
456
457 And after running it like this:
458
459 .. code-block:: shell
460
461 python main.py 2>stderr.log >stdout.log
462
463 We can see the results are as expected:
464
465 .. code-block:: shell
466
467 $ more *.log
468 ::::::::::::::
469 app.log
470 ::::::::::::::
471 DEBUG - A DEBUG message
472 INFO - An INFO message
473 WARNING - A WARNING message
474 ERROR - An ERROR message
475 CRITICAL - A CRITICAL message
476 ::::::::::::::
477 stderr.log
478 ::::::::::::::
479 ERROR - An ERROR message
480 CRITICAL - A CRITICAL message
481 ::::::::::::::
482 stdout.log
483 ::::::::::::::
484 INFO - An INFO message
485 WARNING - A WARNING message
486
487
488 Configuration server example
489 ----------------------------
490
491 Here is an example of a module using the logging configuration server::
492
493 import logging
494 import logging.config
495 import time
496 import os
497
498 # read initial config file
499 logging.config.fileConfig('logging.conf')
500
501 # create and start listener on port 9999
502 t = logging.config.listen(9999)
503 t.start()
504
505 logger = logging.getLogger('simpleExample')
506
507 try:
508 # loop through logging calls to see the difference
509 # new configurations make, until Ctrl+C is pressed
510 while True:
511 logger.debug('debug message')
512 logger.info('info message')
513 logger.warning('warn message')
514 logger.error('error message')
515 logger.critical('critical message')
516 time.sleep(5)
517 except KeyboardInterrupt:
518 # cleanup
519 logging.config.stopListening()
520 t.join()
521
522 And here is a script that takes a filename and sends that file to the server,
523 properly preceded with the binary-encoded length, as the new logging
524 configuration::
525
526 #!/usr/bin/env python
527 import socket, sys, struct
528
529 with open(sys.argv[1], 'rb') as f:
530 data_to_send = f.read()
531
532 HOST = 'localhost'
533 PORT = 9999
534 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
535 print('connecting...')
536 s.connect((HOST, PORT))
537 print('sending config...')
538 s.send(struct.pack('>L', len(data_to_send)))
539 s.send(data_to_send)
540 s.close()
541 print('complete')
542
543
544 .. _blocking-handlers:
545
546 Dealing with handlers that block
547 --------------------------------
548
549 .. currentmodule:: logging.handlers
550
551 Sometimes you have to get your logging handlers to do their work without
552 blocking the thread you're logging from. This is common in web applications,
553 though of course it also occurs in other scenarios.
554
555 A common culprit which demonstrates sluggish behaviour is the
556 :class:`SMTPHandler`: sending emails can take a long time, for a
557 number of reasons outside the developer's control (for example, a poorly
558 performing mail or network infrastructure). But almost any network-based
559 handler can block: Even a :class:`SocketHandler` operation may do a
560 DNS query under the hood which is too slow (and this query can be deep in the
561 socket library code, below the Python layer, and outside your control).
562
563 One solution is to use a two-part approach. For the first part, attach only a
564 :class:`QueueHandler` to those loggers which are accessed from
565 performance-critical threads. They simply write to their queue, which can be
566 sized to a large enough capacity or initialized with no upper bound to their
567 size. The write to the queue will typically be accepted quickly, though you
568 will probably need to catch the :exc:`queue.Full` exception as a precaution
569 in your code. If you are a library developer who has performance-critical
570 threads in their code, be sure to document this (together with a suggestion to
571 attach only ``QueueHandlers`` to your loggers) for the benefit of other
572 developers who will use your code.
573
574 The second part of the solution is :class:`QueueListener`, which has been
575 designed as the counterpart to :class:`QueueHandler`. A
576 :class:`QueueListener` is very simple: it's passed a queue and some handlers,
577 and it fires up an internal thread which listens to its queue for LogRecords
578 sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
579 matter). The ``LogRecords`` are removed from the queue and passed to the
580 handlers for processing.
581
582 The advantage of having a separate :class:`QueueListener` class is that you
583 can use the same instance to service multiple ``QueueHandlers``. This is more
584 resource-friendly than, say, having threaded versions of the existing handler
585 classes, which would eat up one thread per handler for no particular benefit.
586
587 An example of using these two classes follows (imports omitted)::
588
589 que = queue.Queue(-1) # no limit on size
590 queue_handler = QueueHandler(que)
591 handler = logging.StreamHandler()
592 listener = QueueListener(que, handler)
593 root = logging.getLogger()
594 root.addHandler(queue_handler)
595 formatter = logging.Formatter('%(threadName)s: %(message)s')
596 handler.setFormatter(formatter)
597 listener.start()
598 # The log output will display the thread which generated
599 # the event (the main thread) rather than the internal
600 # thread which monitors the internal queue. This is what
601 # you want to happen.
602 root.warning('Look out!')
603 listener.stop()
604
605 which, when run, will produce:
606
607 .. code-block:: none
608
609 MainThread: Look out!
610
611 .. note:: Although the earlier discussion wasn't specifically talking about
612 async code, but rather about slow logging handlers, it should be noted that
613 when logging from async code, network and even file handlers could lead to
614 problems (blocking the event loop) because some logging is done from
615 :mod:`asyncio` internals. It might be best, if any async code is used in an
616 application, to use the above approach for logging, so that any blocking code
617 runs only in the ``QueueListener`` thread.
618
619 .. versionchanged:: 3.5
620 Prior to Python 3.5, the :class:`QueueListener` always passed every message
621 received from the queue to every handler it was initialized with. (This was
622 because it was assumed that level filtering was all done on the other side,
623 where the queue is filled.) From 3.5 onwards, this behaviour can be changed
624 by passing a keyword argument ``respect_handler_level=True`` to the
625 listener's constructor. When this is done, the listener compares the level
626 of each message with the handler's level, and only passes a message to a
627 handler if it's appropriate to do so.
628
629 .. _network-logging:
630
631 Sending and receiving logging events across a network
632 -----------------------------------------------------
633
634 Let's say you want to send logging events across a network, and handle them at
635 the receiving end. A simple way of doing this is attaching a
636 :class:`SocketHandler` instance to the root logger at the sending end::
637
638 import logging, logging.handlers
639
640 rootLogger = logging.getLogger()
641 rootLogger.setLevel(logging.DEBUG)
642 socketHandler = logging.handlers.SocketHandler('localhost',
643 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
644 # don't bother with a formatter, since a socket handler sends the event as
645 # an unformatted pickle
646 rootLogger.addHandler(socketHandler)
647
648 # Now, we can log to the root logger, or any other logger. First the root...
649 logging.info('Jackdaws love my big sphinx of quartz.')
650
651 # Now, define a couple of other loggers which might represent areas in your
652 # application:
653
654 logger1 = logging.getLogger('myapp.area1')
655 logger2 = logging.getLogger('myapp.area2')
656
657 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
658 logger1.info('How quickly daft jumping zebras vex.')
659 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
660 logger2.error('The five boxing wizards jump quickly.')
661
662 At the receiving end, you can set up a receiver using the :mod:`socketserver`
663 module. Here is a basic working example::
664
665 import pickle
666 import logging
667 import logging.handlers
668 import socketserver
669 import struct
670
671
672 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
673 """Handler for a streaming logging request.
674
675 This basically logs the record using whatever logging policy is
676 configured locally.
677 """
678
679 def handle(self):
680 """
681 Handle multiple requests - each expected to be a 4-byte length,
682 followed by the LogRecord in pickle format. Logs the record
683 according to whatever policy is configured locally.
684 """
685 while True:
686 chunk = self.connection.recv(4)
687 if len(chunk) < 4:
688 break
689 slen = struct.unpack('>L', chunk)[0]
690 chunk = self.connection.recv(slen)
691 while len(chunk) < slen:
692 chunk = chunk + self.connection.recv(slen - len(chunk))
693 obj = self.unPickle(chunk)
694 record = logging.makeLogRecord(obj)
695 self.handleLogRecord(record)
696
697 def unPickle(self, data):
698 return pickle.loads(data)
699
700 def handleLogRecord(self, record):
701 # if a name is specified, we use the named logger rather than the one
702 # implied by the record.
703 if self.server.logname is not None:
704 name = self.server.logname
705 else:
706 name = record.name
707 logger = logging.getLogger(name)
708 # N.B. EVERY record gets logged. This is because Logger.handle
709 # is normally called AFTER logger-level filtering. If you want
710 # to do filtering, do it at the client end to save wasting
711 # cycles and network bandwidth!
712 logger.handle(record)
713
714 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
715 """
716 Simple TCP socket-based logging receiver suitable for testing.
717 """
718
719 allow_reuse_address = True
720
721 def __init__(self, host='localhost',
722 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
723 handler=LogRecordStreamHandler):
724 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
725 self.abort = 0
726 self.timeout = 1
727 self.logname = None
728
729 def serve_until_stopped(self):
730 import select
731 abort = 0
732 while not abort:
733 rd, wr, ex = select.select([self.socket.fileno()],
734 [], [],
735 self.timeout)
736 if rd:
737 self.handle_request()
738 abort = self.abort
739
740 def main():
741 logging.basicConfig(
742 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
743 tcpserver = LogRecordSocketReceiver()
744 print('About to start TCP server...')
745 tcpserver.serve_until_stopped()
746
747 if __name__ == '__main__':
748 main()
749
750 First run the server, and then the client. On the client side, nothing is
751 printed on the console; on the server side, you should see something like:
752
753 .. code-block:: none
754
755 About to start TCP server...
756 59 root INFO Jackdaws love my big sphinx of quartz.
757 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
758 69 myapp.area1 INFO How quickly daft jumping zebras vex.
759 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
760 69 myapp.area2 ERROR The five boxing wizards jump quickly.
761
762 Note that there are some security issues with pickle in some scenarios. If
763 these affect you, you can use an alternative serialization scheme by overriding
764 the :meth:`~SocketHandler.makePickle` method and implementing your
765 alternative there, as well as adapting the above script to use your alternative
766 serialization.
767
768
769 Running a logging socket listener in production
770 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
771
772 .. _socket-listener-gist: https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b
773
774 To run a logging listener in production, you may need to use a
775 process-management tool such as `Supervisor <http://supervisord.org/>`_.
776 `Here is a Gist <socket-listener-gist_>`__
777 which provides the bare-bones files to run the above functionality using
778 Supervisor. It consists of the following files:
779
780 +-------------------------+----------------------------------------------------+
781 | File | Purpose |
782 +=========================+====================================================+
783 | :file:`prepare.sh` | A Bash script to prepare the environment for |
784 | | testing |
785 +-------------------------+----------------------------------------------------+
786 | :file:`supervisor.conf` | The Supervisor configuration file, which has |
787 | | entries for the listener and a multi-process web |
788 | | application |
789 +-------------------------+----------------------------------------------------+
790 | :file:`ensure_app.sh` | A Bash script to ensure that Supervisor is running |
791 | | with the above configuration |
792 +-------------------------+----------------------------------------------------+
793 | :file:`log_listener.py` | The socket listener program which receives log |
794 | | events and records them to a file |
795 +-------------------------+----------------------------------------------------+
796 | :file:`main.py` | A simple web application which performs logging |
797 | | via a socket connected to the listener |
798 +-------------------------+----------------------------------------------------+
799 | :file:`webapp.json` | A JSON configuration file for the web application |
800 +-------------------------+----------------------------------------------------+
801 | :file:`client.py` | A Python script to exercise the web application |
802 +-------------------------+----------------------------------------------------+
803
804 The web application uses `Gunicorn <https://gunicorn.org/>`_, which is a
805 popular web application server that starts multiple worker processes to handle
806 requests. This example setup shows how the workers can write to the same log file
807 without conflicting with one another --- they all go through the socket listener.
808
809 To test these files, do the following in a POSIX environment:
810
811 #. Download `the Gist <socket-listener-gist_>`__
812 as a ZIP archive using the :guilabel:`Download ZIP` button.
813
814 #. Unzip the above files from the archive into a scratch directory.
815
816 #. In the scratch directory, run ``bash prepare.sh`` to get things ready.
817 This creates a :file:`run` subdirectory to contain Supervisor-related and
818 log files, and a :file:`venv` subdirectory to contain a virtual environment
819 into which ``bottle``, ``gunicorn`` and ``supervisor`` are installed.
820
821 #. Run ``bash ensure_app.sh`` to ensure that Supervisor is running with
822 the above configuration.
823
824 #. Run ``venv/bin/python client.py`` to exercise the web application,
825 which will lead to records being written to the log.
826
827 #. Inspect the log files in the :file:`run` subdirectory. You should see the
828 most recent log lines in files matching the pattern :file:`app.log*`. They
829 won't be in any particular order, since they have been handled concurrently
830 by different worker processes in a non-deterministic way.
831
832 #. You can shut down the listener and the web application by running
833 ``venv/bin/supervisorctl -c supervisor.conf shutdown``.
834
835 You may need to tweak the configuration files in the unlikely event that the
836 configured ports clash with something else in your test environment.
837
838 The default configuration uses a TCP socket on port 9020. You can use a Unix
839 Domain socket instead of a TCP socket by doing the following:
840
841 #. In :file:`listener.json`, add a ``socket`` key with the path to the domain
842 socket you want to use. If this key is present, the listener listens on the
843 corresponding domain socket and not on a TCP socket (the ``port`` key is
844 ignored).
845
846 #. In :file:`webapp.json`, change the socket handler configuration dictionary
847 so that the ``host`` value is the path to the domain socket, and set the
848 ``port`` value to ``null``.
849
850
851 .. currentmodule:: logging
852
853 .. _context-info:
854
855 Adding contextual information to your logging output
856 ----------------------------------------------------
857
858 Sometimes you want logging output to contain contextual information in
859 addition to the parameters passed to the logging call. For example, in a
860 networked application, it may be desirable to log client-specific information
861 in the log (e.g. remote client's username, or IP address). Although you could
862 use the *extra* parameter to achieve this, it's not always convenient to pass
863 the information in this way. While it might be tempting to create
864 :class:`Logger` instances on a per-connection basis, this is not a good idea
865 because these instances are not garbage collected. While this is not a problem
866 in practice, when the number of :class:`Logger` instances is dependent on the
867 level of granularity you want to use in logging an application, it could
868 be hard to manage if the number of :class:`Logger` instances becomes
869 effectively unbounded.
870
871
872 Using LoggerAdapters to impart contextual information
873 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
874
875 An easy way in which you can pass contextual information to be output along
876 with logging event information is to use the :class:`LoggerAdapter` class.
877 This class is designed to look like a :class:`Logger`, so that you can call
878 :meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
879 :meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
880 same signatures as their counterparts in :class:`Logger`, so you can use the
881 two types of instances interchangeably.
882
883 When you create an instance of :class:`LoggerAdapter`, you pass it a
884 :class:`Logger` instance and a dict-like object which contains your contextual
885 information. When you call one of the logging methods on an instance of
886 :class:`LoggerAdapter`, it delegates the call to the underlying instance of
887 :class:`Logger` passed to its constructor, and arranges to pass the contextual
888 information in the delegated call. Here's a snippet from the code of
889 :class:`LoggerAdapter`::
890
891 def debug(self, msg, /, *args, **kwargs):
892 """
893 Delegate a debug call to the underlying logger, after adding
894 contextual information from this adapter instance.
895 """
896 msg, kwargs = self.process(msg, kwargs)
897 self.logger.debug(msg, *args, **kwargs)
898
899 The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the
900 contextual information is added to the logging output. It's passed the message
901 and keyword arguments of the logging call, and it passes back (potentially)
902 modified versions of these to use in the call to the underlying logger. The
903 default implementation of this method leaves the message alone, but inserts
904 an 'extra' key in the keyword argument whose value is the dict-like object
905 passed to the constructor. Of course, if you had passed an 'extra' keyword
906 argument in the call to the adapter, it will be silently overwritten.
907
908 The advantage of using 'extra' is that the values in the dict-like object are
909 merged into the :class:`LogRecord` instance's __dict__, allowing you to use
910 customized strings with your :class:`Formatter` instances which know about
911 the keys of the dict-like object. If you need a different method, e.g. if you
912 want to prepend or append the contextual information to the message string,
913 you just need to subclass :class:`LoggerAdapter` and override
914 :meth:`~LoggerAdapter.process` to do what you need. Here is a simple example::
915
916 class CustomAdapter(logging.LoggerAdapter):
917 """
918 This example adapter expects the passed in dict-like object to have a
919 'connid' key, whose value in brackets is prepended to the log message.
920 """
921 def process(self, msg, kwargs):
922 return '[%s] %s' % (self.extra['connid'], msg), kwargs
923
924 which you can use like this::
925
926 logger = logging.getLogger(__name__)
927 adapter = CustomAdapter(logger, {'connid': some_conn_id})
928
929 Then any events that you log to the adapter will have the value of
930 ``some_conn_id`` prepended to the log messages.
931
932 Using objects other than dicts to pass contextual information
933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
934
935 You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could
936 pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so
937 that it looks like a dict to logging. This would be useful if you want to
938 generate values dynamically (whereas the values in a dict would be constant).
939
940
941 .. _filters-contextual:
942
943 Using Filters to impart contextual information
944 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
945
946 You can also add contextual information to log output using a user-defined
947 :class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
948 passed to them, including adding additional attributes which can then be output
949 using a suitable format string, or if needed a custom :class:`Formatter`.
950
951 For example in a web application, the request being processed (or at least,
952 the interesting parts of it) can be stored in a threadlocal
953 (:class:`threading.local`) variable, and then accessed from a ``Filter`` to
954 add, say, information from the request - say, the remote IP address and remote
955 user's username - to the ``LogRecord``, using the attribute names 'ip' and
956 'user' as in the ``LoggerAdapter`` example above. In that case, the same format
957 string can be used to get similar output to that shown above. Here's an example
958 script::
959
960 import logging
961 from random import choice
962
963 class ContextFilter(logging.Filter):
964 """
965 This is a filter which injects contextual information into the log.
966
967 Rather than use actual contextual information, we just use random
968 data in this demo.
969 """
970
971 USERS = ['jim', 'fred', 'sheila']
972 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
973
974 def filter(self, record):
975
976 record.ip = choice(ContextFilter.IPS)
977 record.user = choice(ContextFilter.USERS)
978 return True
979
980 if __name__ == '__main__':
981 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
982 logging.basicConfig(level=logging.DEBUG,
983 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
984 a1 = logging.getLogger('a.b.c')
985 a2 = logging.getLogger('d.e.f')
986
987 f = ContextFilter()
988 a1.addFilter(f)
989 a2.addFilter(f)
990 a1.debug('A debug message')
991 a1.info('An info message with %s', 'some parameters')
992 for x in range(10):
993 lvl = choice(levels)
994 lvlname = logging.getLevelName(lvl)
995 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
996
997 which, when run, produces something like:
998
999 .. code-block:: none
1000
1001 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1002 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1003 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1004 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters
1005 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters
1006 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters
1007 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
1008 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1009 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters
1010 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
1011 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters
1012 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters
1013
1014 Use of ``contextvars``
1015 ----------------------
1016
1017 Since Python 3.7, the :mod:`contextvars` module has provided context-local storage
1018 which works for both :mod:`threading` and :mod:`asyncio` processing needs. This type
1019 of storage may thus be generally preferable to thread-locals. The following example
1020 shows how, in a multi-threaded environment, logs can populated with contextual
1021 information such as, for example, request attributes handled by web applications.
1022
1023 For the purposes of illustration, say that you have different web applications, each
1024 independent of the other but running in the same Python process and using a library
1025 common to them. How can each of these applications have their own log, where all
1026 logging messages from the library (and other request processing code) are directed to
1027 the appropriate application's log file, while including in the log additional
1028 contextual information such as client IP, HTTP request method and client username?
1029
1030 Let's assume that the library can be simulated by the following code:
1031
1032 .. code-block:: python
1033
1034 # webapplib.py
1035 import logging
1036 import time
1037
1038 logger = logging.getLogger(__name__)
1039
1040 def useful():
1041 # Just a representative event logged from the library
1042 logger.debug('Hello from webapplib!')
1043 # Just sleep for a bit so other threads get to run
1044 time.sleep(0.01)
1045
1046 We can simulate the multiple web applications by means of two simple classes,
1047 ``Request`` and ``WebApp``. These simulate how real threaded web applications work -
1048 each request is handled by a thread:
1049
1050 .. code-block:: python
1051
1052 # main.py
1053 import argparse
1054 from contextvars import ContextVar
1055 import logging
1056 import os
1057 from random import choice
1058 import threading
1059 import webapplib
1060
1061 logger = logging.getLogger(__name__)
1062 root = logging.getLogger()
1063 root.setLevel(logging.DEBUG)
1064
1065 class Request:
1066 """
1067 A simple dummy request class which just holds dummy HTTP request method,
1068 client IP address and client username
1069 """
1070 def __init__(self, method, ip, user):
1071 self.method = method
1072 self.ip = ip
1073 self.user = user
1074
1075 # A dummy set of requests which will be used in the simulation - we'll just pick
1076 # from this list randomly. Note that all GET requests are from 192.168.2.XXX
1077 # addresses, whereas POST requests are from 192.16.3.XXX addresses. Three users
1078 # are represented in the sample requests.
1079
1080 REQUESTS = [
1081 Request('GET', '192.168.2.20', 'jim'),
1082 Request('POST', '192.168.3.20', 'fred'),
1083 Request('GET', '192.168.2.21', 'sheila'),
1084 Request('POST', '192.168.3.21', 'jim'),
1085 Request('GET', '192.168.2.22', 'fred'),
1086 Request('POST', '192.168.3.22', 'sheila'),
1087 ]
1088
1089 # Note that the format string includes references to request context information
1090 # such as HTTP method, client IP and username
1091
1092 formatter = logging.Formatter('%(threadName)-11s %(appName)s %(name)-9s %(user)-6s %(ip)s %(method)-4s %(message)s')
1093
1094 # Create our context variables. These will be filled at the start of request
1095 # processing, and used in the logging that happens during that processing
1096
1097 ctx_request = ContextVar('request')
1098 ctx_appname = ContextVar('appname')
1099
1100 class InjectingFilter(logging.Filter):
1101 """
1102 A filter which injects context-specific information into logs and ensures
1103 that only information for a specific webapp is included in its log
1104 """
1105 def __init__(self, app):
1106 self.app = app
1107
1108 def filter(self, record):
1109 request = ctx_request.get()
1110 record.method = request.method
1111 record.ip = request.ip
1112 record.user = request.user
1113 record.appName = appName = ctx_appname.get()
1114 return appName == self.app.name
1115
1116 class WebApp:
1117 """
1118 A dummy web application class which has its own handler and filter for a
1119 webapp-specific log.
1120 """
1121 def __init__(self, name):
1122 self.name = name
1123 handler = logging.FileHandler(name + '.log', 'w')
1124 f = InjectingFilter(self)
1125 handler.setFormatter(formatter)
1126 handler.addFilter(f)
1127 root.addHandler(handler)
1128 self.num_requests = 0
1129
1130 def process_request(self, request):
1131 """
1132 This is the dummy method for processing a request. It's called on a
1133 different thread for every request. We store the context information into
1134 the context vars before doing anything else.
1135 """
1136 ctx_request.set(request)
1137 ctx_appname.set(self.name)
1138 self.num_requests += 1
1139 logger.debug('Request processing started')
1140 webapplib.useful()
1141 logger.debug('Request processing finished')
1142
1143 def main():
1144 fn = os.path.splitext(os.path.basename(__file__))[0]
1145 adhf = argparse.ArgumentDefaultsHelpFormatter
1146 ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn,
1147 description='Simulate a couple of web '
1148 'applications handling some '
1149 'requests, showing how request '
1150 'context can be used to '
1151 'populate logs')
1152 aa = ap.add_argument
1153 aa('--count', '-c', type=int, default=100, help='How many requests to simulate')
1154 options = ap.parse_args()
1155
1156 # Create the dummy webapps and put them in a list which we can use to select
1157 # from randomly
1158 app1 = WebApp('app1')
1159 app2 = WebApp('app2')
1160 apps = [app1, app2]
1161 threads = []
1162 # Add a common handler which will capture all events
1163 handler = logging.FileHandler('app.log', 'w')
1164 handler.setFormatter(formatter)
1165 root.addHandler(handler)
1166
1167 # Generate calls to process requests
1168 for i in range(options.count):
1169 try:
1170 # Pick an app at random and a request for it to process
1171 app = choice(apps)
1172 request = choice(REQUESTS)
1173 # Process the request in its own thread
1174 t = threading.Thread(target=app.process_request, args=(request,))
1175 threads.append(t)
1176 t.start()
1177 except KeyboardInterrupt:
1178 break
1179
1180 # Wait for the threads to terminate
1181 for t in threads:
1182 t.join()
1183
1184 for app in apps:
1185 print('%s processed %s requests' % (app.name, app.num_requests))
1186
1187 if __name__ == '__main__':
1188 main()
1189
1190 If you run the above, you should find that roughly half the requests go
1191 into :file:`app1.log` and the rest into :file:`app2.log`, and the all the requests are
1192 logged to :file:`app.log`. Each webapp-specific log will contain only log entries for
1193 only that webapp, and the request information will be displayed consistently in the
1194 log (i.e. the information in each dummy request will always appear together in a log
1195 line). This is illustrated by the following shell output:
1196
1197 .. code-block:: shell
1198
1199 ~/logging-contextual-webapp$ python main.py
1200 app1 processed 51 requests
1201 app2 processed 49 requests
1202 ~/logging-contextual-webapp$ wc -l *.log
1203 153 app1.log
1204 147 app2.log
1205 300 app.log
1206 600 total
1207 ~/logging-contextual-webapp$ head -3 app1.log
1208 Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request processing started
1209 Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello from webapplib!
1210 Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request processing started
1211 ~/logging-contextual-webapp$ head -3 app2.log
1212 Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request processing started
1213 Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello from webapplib!
1214 Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request processing started
1215 ~/logging-contextual-webapp$ head app.log
1216 Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request processing started
1217 Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello from webapplib!
1218 Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request processing started
1219 Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request processing started
1220 Thread-2 (process_request) app2 webapplib jim 192.168.2.20 GET Hello from webapplib!
1221 Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello from webapplib!
1222 Thread-4 (process_request) app2 __main__ fred 192.168.2.22 GET Request processing started
1223 Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request processing started
1224 Thread-4 (process_request) app2 webapplib fred 192.168.2.22 GET Hello from webapplib!
1225 Thread-6 (process_request) app1 __main__ jim 192.168.3.21 POST Request processing started
1226 ~/logging-contextual-webapp$ grep app1 app1.log | wc -l
1227 153
1228 ~/logging-contextual-webapp$ grep app2 app2.log | wc -l
1229 147
1230 ~/logging-contextual-webapp$ grep app1 app.log | wc -l
1231 153
1232 ~/logging-contextual-webapp$ grep app2 app.log | wc -l
1233 147
1234
1235
1236 Imparting contextual information in handlers
1237 --------------------------------------------
1238
1239 Each :class:`~Handler` has its own chain of filters.
1240 If you want to add contextual information to a :class:`LogRecord` without leaking
1241 it to other handlers, you can use a filter that returns
1242 a new :class:`~LogRecord` instead of modifying it in-place, as shown in the following script::
1243
1244 import copy
1245 import logging
1246
1247 def filter(record: logging.LogRecord):
1248 record = copy.copy(record)
1249 record.user = 'jim'
1250 return record
1251
1252 if __name__ == '__main__':
1253 logger = logging.getLogger()
1254 logger.setLevel(logging.INFO)
1255 handler = logging.StreamHandler()
1256 formatter = logging.Formatter('%(message)s from %(user)-8s')
1257 handler.setFormatter(formatter)
1258 handler.addFilter(filter)
1259 logger.addHandler(handler)
1260
1261 logger.info('A log message')
1262
1263 .. _multiple-processes:
1264
1265 Logging to a single file from multiple processes
1266 ------------------------------------------------
1267
1268 Although logging is thread-safe, and logging to a single file from multiple
1269 threads in a single process *is* supported, logging to a single file from
1270 *multiple processes* is *not* supported, because there is no standard way to
1271 serialize access to a single file across multiple processes in Python. If you
1272 need to log to a single file from multiple processes, one way of doing this is
1273 to have all the processes log to a :class:`~handlers.SocketHandler`, and have a
1274 separate process which implements a socket server which reads from the socket
1275 and logs to file. (If you prefer, you can dedicate one thread in one of the
1276 existing processes to perform this function.)
1277 :ref:`This section <network-logging>` documents this approach in more detail and
1278 includes a working socket receiver which can be used as a starting point for you
1279 to adapt in your own applications.
1280
1281 You could also write your own handler which uses the :class:`~multiprocessing.Lock`
1282 class from the :mod:`multiprocessing` module to serialize access to the
1283 file from your processes. The stdlib :class:`FileHandler` and subclasses do
1284 not make use of :mod:`multiprocessing`.
1285
1286 .. currentmodule:: logging.handlers
1287
1288 Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1289 all logging events to one of the processes in your multi-process application.
1290 The following example script demonstrates how you can do this; in the example
1291 a separate listener process listens for events sent by other processes and logs
1292 them according to its own logging configuration. Although the example only
1293 demonstrates one way of doing it (for example, you may want to use a listener
1294 thread rather than a separate listener process -- the implementation would be
1295 analogous) it does allow for completely different logging configurations for
1296 the listener and the other processes in your application, and can be used as
1297 the basis for code meeting your own specific requirements::
1298
1299 # You'll need these imports in your own code
1300 import logging
1301 import logging.handlers
1302 import multiprocessing
1303
1304 # Next two import lines for this demo only
1305 from random import choice, random
1306 import time
1307
1308 #
1309 # Because you'll want to define the logging configurations for listener and workers, the
1310 # listener and worker process functions take a configurer parameter which is a callable
1311 # for configuring logging for that process. These functions are also passed the queue,
1312 # which they use for communication.
1313 #
1314 # In practice, you can configure the listener however you want, but note that in this
1315 # simple example, the listener does not apply level or filter logic to received records.
1316 # In practice, you would probably want to do this logic in the worker processes, to avoid
1317 # sending events which would be filtered out between processes.
1318 #
1319 # The size of the rotated files is made small so you can see the results easily.
1320 def listener_configurer():
1321 root = logging.getLogger()
1322 h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
1323 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1324 h.setFormatter(f)
1325 root.addHandler(h)
1326
1327 # This is the listener process top-level loop: wait for logging events
1328 # (LogRecords)on the queue and handle them, quit when you get a None for a
1329 # LogRecord.
1330 def listener_process(queue, configurer):
1331 configurer()
1332 while True:
1333 try:
1334 record = queue.get()
1335 if record is None: # We send this as a sentinel to tell the listener to quit.
1336 break
1337 logger = logging.getLogger(record.name)
1338 logger.handle(record) # No level or filter logic applied - just do it!
1339 except Exception:
1340 import sys, traceback
1341 print('Whoops! Problem:', file=sys.stderr)
1342 traceback.print_exc(file=sys.stderr)
1343
1344 # Arrays used for random selections in this demo
1345
1346 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1347 logging.ERROR, logging.CRITICAL]
1348
1349 LOGGERS = ['a.b.c', 'd.e.f']
1350
1351 MESSAGES = [
1352 'Random message #1',
1353 'Random message #2',
1354 'Random message #3',
1355 ]
1356
1357 # The worker configuration is done at the start of the worker process run.
1358 # Note that on Windows you can't rely on fork semantics, so each process
1359 # will run the logging configuration code when it starts.
1360 def worker_configurer(queue):
1361 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1362 root = logging.getLogger()
1363 root.addHandler(h)
1364 # send all messages, for demo; no other level or filter logic applied.
1365 root.setLevel(logging.DEBUG)
1366
1367 # This is the worker process top-level loop, which just logs ten events with
1368 # random intervening delays before terminating.
1369 # The print messages are just so you know it's doing something!
1370 def worker_process(queue, configurer):
1371 configurer(queue)
1372 name = multiprocessing.current_process().name
1373 print('Worker started: %s' % name)
1374 for i in range(10):
1375 time.sleep(random())
1376 logger = logging.getLogger(choice(LOGGERS))
1377 level = choice(LEVELS)
1378 message = choice(MESSAGES)
1379 logger.log(level, message)
1380 print('Worker finished: %s' % name)
1381
1382 # Here's where the demo gets orchestrated. Create the queue, create and start
1383 # the listener, create ten workers and start them, wait for them to finish,
1384 # then send a None to the queue to tell the listener to finish.
1385 def main():
1386 queue = multiprocessing.Queue(-1)
1387 listener = multiprocessing.Process(target=listener_process,
1388 args=(queue, listener_configurer))
1389 listener.start()
1390 workers = []
1391 for i in range(10):
1392 worker = multiprocessing.Process(target=worker_process,
1393 args=(queue, worker_configurer))
1394 workers.append(worker)
1395 worker.start()
1396 for w in workers:
1397 w.join()
1398 queue.put_nowait(None)
1399 listener.join()
1400
1401 if __name__ == '__main__':
1402 main()
1403
1404 A variant of the above script keeps the logging in the main process, in a
1405 separate thread::
1406
1407 import logging
1408 import logging.config
1409 import logging.handlers
1410 from multiprocessing import Process, Queue
1411 import random
1412 import threading
1413 import time
1414
1415 def logger_thread(q):
1416 while True:
1417 record = q.get()
1418 if record is None:
1419 break
1420 logger = logging.getLogger(record.name)
1421 logger.handle(record)
1422
1423
1424 def worker_process(q):
1425 qh = logging.handlers.QueueHandler(q)
1426 root = logging.getLogger()
1427 root.setLevel(logging.DEBUG)
1428 root.addHandler(qh)
1429 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
1430 logging.CRITICAL]
1431 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
1432 'spam', 'spam.ham', 'spam.ham.eggs']
1433 for i in range(100):
1434 lvl = random.choice(levels)
1435 logger = logging.getLogger(random.choice(loggers))
1436 logger.log(lvl, 'Message no. %d', i)
1437
1438 if __name__ == '__main__':
1439 q = Queue()
1440 d = {
1441 'version': 1,
1442 'formatters': {
1443 'detailed': {
1444 'class': 'logging.Formatter',
1445 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1446 }
1447 },
1448 'handlers': {
1449 'console': {
1450 'class': 'logging.StreamHandler',
1451 'level': 'INFO',
1452 },
1453 'file': {
1454 'class': 'logging.FileHandler',
1455 'filename': 'mplog.log',
1456 'mode': 'w',
1457 'formatter': 'detailed',
1458 },
1459 'foofile': {
1460 'class': 'logging.FileHandler',
1461 'filename': 'mplog-foo.log',
1462 'mode': 'w',
1463 'formatter': 'detailed',
1464 },
1465 'errors': {
1466 'class': 'logging.FileHandler',
1467 'filename': 'mplog-errors.log',
1468 'mode': 'w',
1469 'level': 'ERROR',
1470 'formatter': 'detailed',
1471 },
1472 },
1473 'loggers': {
1474 'foo': {
1475 'handlers': ['foofile']
1476 }
1477 },
1478 'root': {
1479 'level': 'DEBUG',
1480 'handlers': ['console', 'file', 'errors']
1481 },
1482 }
1483 workers = []
1484 for i in range(5):
1485 wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
1486 workers.append(wp)
1487 wp.start()
1488 logging.config.dictConfig(d)
1489 lp = threading.Thread(target=logger_thread, args=(q,))
1490 lp.start()
1491 # At this point, the main process could do some useful work of its own
1492 # Once it's done that, it can wait for the workers to terminate...
1493 for wp in workers:
1494 wp.join()
1495 # And now tell the logging thread to finish up, too
1496 q.put(None)
1497 lp.join()
1498
1499 This variant shows how you can e.g. apply configuration for particular loggers
1500 - e.g. the ``foo`` logger has a special handler which stores all events in the
1501 ``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging
1502 machinery in the main process (even though the logging events are generated in
1503 the worker processes) to direct the messages to the appropriate destinations.
1504
1505 Using concurrent.futures.ProcessPoolExecutor
1506 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1507
1508 If you want to use :class:`concurrent.futures.ProcessPoolExecutor` to start
1509 your worker processes, you need to create the queue slightly differently.
1510 Instead of
1511
1512 .. code-block:: python
1513
1514 queue = multiprocessing.Queue(-1)
1515
1516 you should use
1517
1518 .. code-block:: python
1519
1520 queue = multiprocessing.Manager().Queue(-1) # also works with the examples above
1521
1522 and you can then replace the worker creation from this::
1523
1524 workers = []
1525 for i in range(10):
1526 worker = multiprocessing.Process(target=worker_process,
1527 args=(queue, worker_configurer))
1528 workers.append(worker)
1529 worker.start()
1530 for w in workers:
1531 w.join()
1532
1533 to this (remembering to first import :mod:`concurrent.futures`)::
1534
1535 with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
1536 for i in range(10):
1537 executor.submit(worker_process, queue, worker_configurer)
1538
1539 Deploying Web applications using Gunicorn and uWSGI
1540 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1541
1542 When deploying Web applications using `Gunicorn <https://gunicorn.org/>`_ or `uWSGI
1543 <https://uwsgi-docs.readthedocs.io/en/latest/>`_ (or similar), multiple worker
1544 processes are created to handle client requests. In such environments, avoid creating
1545 file-based handlers directly in your web application. Instead, use a
1546 :class:`SocketHandler` to log from the web application to a listener in a separate
1547 process. This can be set up using a process management tool such as Supervisor - see
1548 `Running a logging socket listener in production`_ for more details.
1549
1550
1551 Using file rotation
1552 -------------------
1553
1554 .. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1555 .. (see <https://pymotw.com/3/logging/>)
1556
1557 Sometimes you want to let a log file grow to a certain size, then open a new
1558 file and log to that. You may want to keep a certain number of these files, and
1559 when that many files have been created, rotate the files so that the number of
1560 files and the size of the files both remain bounded. For this usage pattern, the
1561 logging package provides a :class:`RotatingFileHandler`::
1562
1563 import glob
1564 import logging
1565 import logging.handlers
1566
1567 LOG_FILENAME = 'logging_rotatingfile_example.out'
1568
1569 # Set up a specific logger with our desired output level
1570 my_logger = logging.getLogger('MyLogger')
1571 my_logger.setLevel(logging.DEBUG)
1572
1573 # Add the log message handler to the logger
1574 handler = logging.handlers.RotatingFileHandler(
1575 LOG_FILENAME, maxBytes=20, backupCount=5)
1576
1577 my_logger.addHandler(handler)
1578
1579 # Log some messages
1580 for i in range(20):
1581 my_logger.debug('i = %d' % i)
1582
1583 # See what files are created
1584 logfiles = glob.glob('%s*' % LOG_FILENAME)
1585
1586 for filename in logfiles:
1587 print(filename)
1588
1589 The result should be 6 separate files, each with part of the log history for the
1590 application:
1591
1592 .. code-block:: none
1593
1594 logging_rotatingfile_example.out
1595 logging_rotatingfile_example.out.1
1596 logging_rotatingfile_example.out.2
1597 logging_rotatingfile_example.out.3
1598 logging_rotatingfile_example.out.4
1599 logging_rotatingfile_example.out.5
1600
1601 The most current file is always :file:`logging_rotatingfile_example.out`,
1602 and each time it reaches the size limit it is renamed with the suffix
1603 ``.1``. Each of the existing backup files is renamed to increment the suffix
1604 (``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1605
1606 Obviously this example sets the log length much too small as an extreme
1607 example. You would want to set *maxBytes* to an appropriate value.
1608
1609 .. currentmodule:: logging
1610
1611 .. _format-styles:
1612
1613 Use of alternative formatting styles
1614 ------------------------------------
1615
1616 When logging was added to the Python standard library, the only way of
1617 formatting messages with variable content was to use the %-formatting
1618 method. Since then, Python has gained two new formatting approaches:
1619 :class:`string.Template` (added in Python 2.4) and :meth:`str.format`
1620 (added in Python 2.6).
1621
1622 Logging (as of 3.2) provides improved support for these two additional
1623 formatting styles. The :class:`Formatter` class been enhanced to take an
1624 additional, optional keyword parameter named ``style``. This defaults to
1625 ``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond
1626 to the other two formatting styles. Backwards compatibility is maintained by
1627 default (as you would expect), but by explicitly specifying a style parameter,
1628 you get the ability to specify format strings which work with
1629 :meth:`str.format` or :class:`string.Template`. Here's an example console
1630 session to show the possibilities:
1631
1632 .. code-block:: pycon
1633
1634 >>> import logging
1635 >>> root = logging.getLogger()
1636 >>> root.setLevel(logging.DEBUG)
1637 >>> handler = logging.StreamHandler()
1638 >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
1639 ... style='{')
1640 >>> handler.setFormatter(bf)
1641 >>> root.addHandler(handler)
1642 >>> logger = logging.getLogger('foo.bar')
1643 >>> logger.debug('This is a DEBUG message')
1644 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message
1645 >>> logger.critical('This is a CRITICAL message')
1646 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
1647 >>> df = logging.Formatter('$asctime $name ${levelname} $message',
1648 ... style='$')
1649 >>> handler.setFormatter(df)
1650 >>> logger.debug('This is a DEBUG message')
1651 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
1652 >>> logger.critical('This is a CRITICAL message')
1653 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
1654 >>>
1655
1656 Note that the formatting of logging messages for final output to logs is
1657 completely independent of how an individual logging message is constructed.
1658 That can still use %-formatting, as shown here::
1659
1660 >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
1661 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
1662 >>>
1663
1664 Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take
1665 positional parameters for the actual logging message itself, with keyword
1666 parameters used only for determining options for how to handle the actual
1667 logging call (e.g. the ``exc_info`` keyword parameter to indicate that
1668 traceback information should be logged, or the ``extra`` keyword parameter
1669 to indicate additional contextual information to be added to the log). So
1670 you cannot directly make logging calls using :meth:`str.format` or
1671 :class:`string.Template` syntax, because internally the logging package
1672 uses %-formatting to merge the format string and the variable arguments.
1673 There would be no changing this while preserving backward compatibility, since
1674 all logging calls which are out there in existing code will be using %-format
1675 strings.
1676
1677 There is, however, a way that you can use {}- and $- formatting to construct
1678 your individual log messages. Recall that for a message you can use an
1679 arbitrary object as a message format string, and that the logging package will
1680 call ``str()`` on that object to get the actual format string. Consider the
1681 following two classes::
1682
1683 class BraceMessage:
1684 def __init__(self, fmt, /, *args, **kwargs):
1685 self.fmt = fmt
1686 self.args = args
1687 self.kwargs = kwargs
1688
1689 def __str__(self):
1690 return self.fmt.format(*self.args, **self.kwargs)
1691
1692 class DollarMessage:
1693 def __init__(self, fmt, /, **kwargs):
1694 self.fmt = fmt
1695 self.kwargs = kwargs
1696
1697 def __str__(self):
1698 from string import Template
1699 return Template(self.fmt).substitute(**self.kwargs)
1700
1701 Either of these can be used in place of a format string, to allow {}- or
1702 $-formatting to be used to build the actual "message" part which appears in the
1703 formatted log output in place of "%(message)s" or "{message}" or "$message".
1704 It's a little unwieldy to use the class names whenever you want to log
1705 something, but it's quite palatable if you use an alias such as __ (double
1706 underscore --- not to be confused with _, the single underscore used as a
1707 synonym/alias for :func:`gettext.gettext` or its brethren).
1708
1709 The above classes are not included in Python, though they're easy enough to
1710 copy and paste into your own code. They can be used as follows (assuming that
1711 they're declared in a module called ``wherever``):
1712
1713 .. code-block:: pycon
1714
1715 >>> from wherever import BraceMessage as __
1716 >>> print(__('Message with {0} {name}', 2, name='placeholders'))
1717 Message with 2 placeholders
1718 >>> class Point: pass
1719 ...
1720 >>> p = Point()
1721 >>> p.x = 0.5
1722 >>> p.y = 0.5
1723 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
1724 ... point=p))
1725 Message with coordinates: (0.50, 0.50)
1726 >>> from wherever import DollarMessage as __
1727 >>> print(__('Message with $num $what', num=2, what='placeholders'))
1728 Message with 2 placeholders
1729 >>>
1730
1731 While the above examples use ``print()`` to show how the formatting works, you
1732 would of course use ``logger.debug()`` or similar to actually log using this
1733 approach.
1734
1735 One thing to note is that you pay no significant performance penalty with this
1736 approach: the actual formatting happens not when you make the logging call, but
1737 when (and if) the logged message is actually about to be output to a log by a
1738 handler. So the only slightly unusual thing which might trip you up is that the
1739 parentheses go around the format string and the arguments, not just the format
1740 string. That's because the __ notation is just syntax sugar for a constructor
1741 call to one of the :samp:`{XXX}Message` classes.
1742
1743 If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect
1744 to the above, as in the following example::
1745
1746 import logging
1747
1748 class Message:
1749 def __init__(self, fmt, args):
1750 self.fmt = fmt
1751 self.args = args
1752
1753 def __str__(self):
1754 return self.fmt.format(*self.args)
1755
1756 class StyleAdapter(logging.LoggerAdapter):
1757 def log(self, level, msg, /, *args, stacklevel=1, **kwargs):
1758 if self.isEnabledFor(level):
1759 msg, kwargs = self.process(msg, kwargs)
1760 self.logger.log(level, Message(msg, args), **kwargs,
1761 stacklevel=stacklevel+1)
1762
1763 logger = StyleAdapter(logging.getLogger(__name__))
1764
1765 def main():
1766 logger.debug('Hello, {}', 'world!')
1767
1768 if __name__ == '__main__':
1769 logging.basicConfig(level=logging.DEBUG)
1770 main()
1771
1772 The above script should log the message ``Hello, world!`` when run with
1773 Python 3.8 or later.
1774
1775
1776 .. currentmodule:: logging
1777
1778 .. _custom-logrecord:
1779
1780 Customizing ``LogRecord``
1781 -------------------------
1782
1783 Every logging event is represented by a :class:`LogRecord` instance.
1784 When an event is logged and not filtered out by a logger's level, a
1785 :class:`LogRecord` is created, populated with information about the event and
1786 then passed to the handlers for that logger (and its ancestors, up to and
1787 including the logger where further propagation up the hierarchy is disabled).
1788 Before Python 3.2, there were only two places where this creation was done:
1789
1790 * :meth:`Logger.makeRecord`, which is called in the normal process of
1791 logging an event. This invoked :class:`LogRecord` directly to create an
1792 instance.
1793 * :func:`makeLogRecord`, which is called with a dictionary containing
1794 attributes to be added to the LogRecord. This is typically invoked when a
1795 suitable dictionary has been received over the network (e.g. in pickle form
1796 via a :class:`~handlers.SocketHandler`, or in JSON form via an
1797 :class:`~handlers.HTTPHandler`).
1798
1799 This has usually meant that if you need to do anything special with a
1800 :class:`LogRecord`, you've had to do one of the following.
1801
1802 * Create your own :class:`Logger` subclass, which overrides
1803 :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass`
1804 before any loggers that you care about are instantiated.
1805 * Add a :class:`Filter` to a logger or handler, which does the
1806 necessary special manipulation you need when its
1807 :meth:`~Filter.filter` method is called.
1808
1809 The first approach would be a little unwieldy in the scenario where (say)
1810 several different libraries wanted to do different things. Each would attempt
1811 to set its own :class:`Logger` subclass, and the one which did this last would
1812 win.
1813
1814 The second approach works reasonably well for many cases, but does not allow
1815 you to e.g. use a specialized subclass of :class:`LogRecord`. Library
1816 developers can set a suitable filter on their loggers, but they would have to
1817 remember to do this every time they introduced a new logger (which they would
1818 do simply by adding new packages or modules and doing ::
1819
1820 logger = logging.getLogger(__name__)
1821
1822 at module level). It's probably one too many things to think about. Developers
1823 could also add the filter to a :class:`~logging.NullHandler` attached to their
1824 top-level logger, but this would not be invoked if an application developer
1825 attached a handler to a lower-level library logger --- so output from that
1826 handler would not reflect the intentions of the library developer.
1827
1828 In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a
1829 factory, which you can specify. The factory is just a callable you can set with
1830 :func:`~logging.setLogRecordFactory`, and interrogate with
1831 :func:`~logging.getLogRecordFactory`. The factory is invoked with the same
1832 signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord`
1833 is the default setting for the factory.
1834
1835 This approach allows a custom factory to control all aspects of LogRecord
1836 creation. For example, you could return a subclass, or just add some additional
1837 attributes to the record once created, using a pattern similar to this::
1838
1839 old_factory = logging.getLogRecordFactory()
1840
1841 def record_factory(*args, **kwargs):
1842 record = old_factory(*args, **kwargs)
1843 record.custom_attribute = 0xdecafbad
1844 return record
1845
1846 logging.setLogRecordFactory(record_factory)
1847
1848 This pattern allows different libraries to chain factories together, and as
1849 long as they don't overwrite each other's attributes or unintentionally
1850 overwrite the attributes provided as standard, there should be no surprises.
1851 However, it should be borne in mind that each link in the chain adds run-time
1852 overhead to all logging operations, and the technique should only be used when
1853 the use of a :class:`Filter` does not provide the desired result.
1854
1855 .. currentmodule:: logging.handlers
1856
1857 .. _zeromq-handlers:
1858
1859 Subclassing QueueHandler and QueueListener- a ZeroMQ example
1860 ------------------------------------------------------------
1861
1862 Subclass ``QueueHandler``
1863 ^^^^^^^^^^^^^^^^^^^^^^^^^
1864
1865 You can use a :class:`QueueHandler` subclass to send messages to other kinds
1866 of queues, for example a ZeroMQ 'publish' socket. In the example below,the
1867 socket is created separately and passed to the handler (as its 'queue')::
1868
1869 import zmq # using pyzmq, the Python binding for ZeroMQ
1870 import json # for serializing records portably
1871
1872 ctx = zmq.Context()
1873 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
1874 sock.bind('tcp://*:5556') # or wherever
1875
1876 class ZeroMQSocketHandler(QueueHandler):
1877 def enqueue(self, record):
1878 self.queue.send_json(record.__dict__)
1879
1880
1881 handler = ZeroMQSocketHandler(sock)
1882
1883
1884 Of course there are other ways of organizing this, for example passing in the
1885 data needed by the handler to create the socket::
1886
1887 class ZeroMQSocketHandler(QueueHandler):
1888 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
1889 self.ctx = ctx or zmq.Context()
1890 socket = zmq.Socket(self.ctx, socktype)
1891 socket.bind(uri)
1892 super().__init__(socket)
1893
1894 def enqueue(self, record):
1895 self.queue.send_json(record.__dict__)
1896
1897 def close(self):
1898 self.queue.close()
1899
1900
1901 Subclass ``QueueListener``
1902 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1903
1904 You can also subclass :class:`QueueListener` to get messages from other kinds
1905 of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
1906
1907 class ZeroMQSocketListener(QueueListener):
1908 def __init__(self, uri, /, *handlers, **kwargs):
1909 self.ctx = kwargs.get('ctx') or zmq.Context()
1910 socket = zmq.Socket(self.ctx, zmq.SUB)
1911 socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to everything
1912 socket.connect(uri)
1913 super().__init__(socket, *handlers, **kwargs)
1914
1915 def dequeue(self):
1916 msg = self.queue.recv_json()
1917 return logging.makeLogRecord(msg)
1918
1919 .. _pynng-handlers:
1920
1921 Subclassing QueueHandler and QueueListener- a ``pynng`` example
1922 ---------------------------------------------------------------
1923
1924 In a similar way to the above section, we can implement a listener and handler
1925 using :pypi:`pynng`, which is a Python binding to
1926 `NNG <https://nng.nanomsg.org/>`_, billed as a spiritual successor to ZeroMQ.
1927 The following snippets illustrate -- you can test them in an environment which has
1928 ``pynng`` installed. Just for variety, we present the listener first.
1929
1930
1931 Subclass ``QueueListener``
1932 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1933
1934 .. code-block:: python
1935
1936 # listener.py
1937 import json
1938 import logging
1939 import logging.handlers
1940
1941 import pynng
1942
1943 DEFAULT_ADDR = "tcp://localhost:13232"
1944
1945 interrupted = False
1946
1947 class NNGSocketListener(logging.handlers.QueueListener):
1948
1949 def __init__(self, uri, /, *handlers, **kwargs):
1950 # Have a timeout for interruptability, and open a
1951 # subscriber socket
1952 socket = pynng.Sub0(listen=uri, recv_timeout=500)
1953 # The b'' subscription matches all topics
1954 topics = kwargs.pop('topics', None) or b''
1955 socket.subscribe(topics)
1956 # We treat the socket as a queue
1957 super().__init__(socket, *handlers, **kwargs)
1958
1959 def dequeue(self, block):
1960 data = None
1961 # Keep looping while not interrupted and no data received over the
1962 # socket
1963 while not interrupted:
1964 try:
1965 data = self.queue.recv(block=block)
1966 break
1967 except pynng.Timeout:
1968 pass
1969 except pynng.Closed: # sometimes happens when you hit Ctrl-C
1970 break
1971 if data is None:
1972 return None
1973 # Get the logging event sent from a publisher
1974 event = json.loads(data.decode('utf-8'))
1975 return logging.makeLogRecord(event)
1976
1977 def enqueue_sentinel(self):
1978 # Not used in this implementation, as the socket isn't really a
1979 # queue
1980 pass
1981
1982 logging.getLogger('pynng').propagate = False
1983 listener = NNGSocketListener(DEFAULT_ADDR, logging.StreamHandler(), topics=b'')
1984 listener.start()
1985 print('Press Ctrl-C to stop.')
1986 try:
1987 while True:
1988 pass
1989 except KeyboardInterrupt:
1990 interrupted = True
1991 finally:
1992 listener.stop()
1993
1994
1995 Subclass ``QueueHandler``
1996 ^^^^^^^^^^^^^^^^^^^^^^^^^
1997
1998 .. currentmodule:: logging
1999
2000 .. code-block:: python
2001
2002 # sender.py
2003 import json
2004 import logging
2005 import logging.handlers
2006 import time
2007 import random
2008
2009 import pynng
2010
2011 DEFAULT_ADDR = "tcp://localhost:13232"
2012
2013 class NNGSocketHandler(logging.handlers.QueueHandler):
2014
2015 def __init__(self, uri):
2016 socket = pynng.Pub0(dial=uri, send_timeout=500)
2017 super().__init__(socket)
2018
2019 def enqueue(self, record):
2020 # Send the record as UTF-8 encoded JSON
2021 d = dict(record.__dict__)
2022 data = json.dumps(d)
2023 self.queue.send(data.encode('utf-8'))
2024
2025 def close(self):
2026 self.queue.close()
2027
2028 logging.getLogger('pynng').propagate = False
2029 handler = NNGSocketHandler(DEFAULT_ADDR)
2030 # Make sure the process ID is in the output
2031 logging.basicConfig(level=logging.DEBUG,
2032 handlers=[logging.StreamHandler(), handler],
2033 format='%(levelname)-8s %(name)10s %(process)6s %(message)s')
2034 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
2035 logging.CRITICAL)
2036 logger_names = ('myapp', 'myapp.lib1', 'myapp.lib2')
2037 msgno = 1
2038 while True:
2039 # Just randomly select some loggers and levels and log away
2040 level = random.choice(levels)
2041 logger = logging.getLogger(random.choice(logger_names))
2042 logger.log(level, 'Message no. %5d' % msgno)
2043 msgno += 1
2044 delay = random.random() * 2 + 0.5
2045 time.sleep(delay)
2046
2047 You can run the above two snippets in separate command shells. If we run the
2048 listener in one shell and run the sender in two separate shells, we should see
2049 something like the following. In the first sender shell:
2050
2051 .. code-block:: console
2052
2053 $ python sender.py
2054 DEBUG myapp 613 Message no. 1
2055 WARNING myapp.lib2 613 Message no. 2
2056 CRITICAL myapp.lib2 613 Message no. 3
2057 WARNING myapp.lib2 613 Message no. 4
2058 CRITICAL myapp.lib1 613 Message no. 5
2059 DEBUG myapp 613 Message no. 6
2060 CRITICAL myapp.lib1 613 Message no. 7
2061 INFO myapp.lib1 613 Message no. 8
2062 (and so on)
2063
2064 In the second sender shell:
2065
2066 .. code-block:: console
2067
2068 $ python sender.py
2069 INFO myapp.lib2 657 Message no. 1
2070 CRITICAL myapp.lib2 657 Message no. 2
2071 CRITICAL myapp 657 Message no. 3
2072 CRITICAL myapp.lib1 657 Message no. 4
2073 INFO myapp.lib1 657 Message no. 5
2074 WARNING myapp.lib2 657 Message no. 6
2075 CRITICAL myapp 657 Message no. 7
2076 DEBUG myapp.lib1 657 Message no. 8
2077 (and so on)
2078
2079 In the listener shell:
2080
2081 .. code-block:: console
2082
2083 $ python listener.py
2084 Press Ctrl-C to stop.
2085 DEBUG myapp 613 Message no. 1
2086 WARNING myapp.lib2 613 Message no. 2
2087 INFO myapp.lib2 657 Message no. 1
2088 CRITICAL myapp.lib2 613 Message no. 3
2089 CRITICAL myapp.lib2 657 Message no. 2
2090 CRITICAL myapp 657 Message no. 3
2091 WARNING myapp.lib2 613 Message no. 4
2092 CRITICAL myapp.lib1 613 Message no. 5
2093 CRITICAL myapp.lib1 657 Message no. 4
2094 INFO myapp.lib1 657 Message no. 5
2095 DEBUG myapp 613 Message no. 6
2096 WARNING myapp.lib2 657 Message no. 6
2097 CRITICAL myapp 657 Message no. 7
2098 CRITICAL myapp.lib1 613 Message no. 7
2099 INFO myapp.lib1 613 Message no. 8
2100 DEBUG myapp.lib1 657 Message no. 8
2101 (and so on)
2102
2103 As you can see, the logging from the two sender processes is interleaved in the
2104 listener's output.
2105
2106
2107 An example dictionary-based configuration
2108 -----------------------------------------
2109
2110 Below is an example of a logging configuration dictionary - it's taken from
2111 the `documentation on the Django project <https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging>`_.
2112 This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::
2113
2114 LOGGING = {
2115 'version': 1,
2116 'disable_existing_loggers': False,
2117 'formatters': {
2118 'verbose': {
2119 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
2120 'style': '{',
2121 },
2122 'simple': {
2123 'format': '{levelname} {message}',
2124 'style': '{',
2125 },
2126 },
2127 'filters': {
2128 'special': {
2129 '()': 'project.logging.SpecialFilter',
2130 'foo': 'bar',
2131 },
2132 },
2133 'handlers': {
2134 'console': {
2135 'level': 'INFO',
2136 'class': 'logging.StreamHandler',
2137 'formatter': 'simple',
2138 },
2139 'mail_admins': {
2140 'level': 'ERROR',
2141 'class': 'django.utils.log.AdminEmailHandler',
2142 'filters': ['special']
2143 }
2144 },
2145 'loggers': {
2146 'django': {
2147 'handlers': ['console'],
2148 'propagate': True,
2149 },
2150 'django.request': {
2151 'handlers': ['mail_admins'],
2152 'level': 'ERROR',
2153 'propagate': False,
2154 },
2155 'myproject.custom': {
2156 'handlers': ['console', 'mail_admins'],
2157 'level': 'INFO',
2158 'filters': ['special']
2159 }
2160 }
2161 }
2162
2163 For more information about this configuration, you can see the `relevant
2164 section <https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging>`_
2165 of the Django documentation.
2166
2167 .. _cookbook-rotator-namer:
2168
2169 Using a rotator and namer to customize log rotation processing
2170 --------------------------------------------------------------
2171
2172 An example of how you can define a namer and rotator is given in the following
2173 runnable script, which shows gzip compression of the log file::
2174
2175 import gzip
2176 import logging
2177 import logging.handlers
2178 import os
2179 import shutil
2180
2181 def namer(name):
2182 return name + ".gz"
2183
2184 def rotator(source, dest):
2185 with open(source, 'rb') as f_in:
2186 with gzip.open(dest, 'wb') as f_out:
2187 shutil.copyfileobj(f_in, f_out)
2188 os.remove(source)
2189
2190
2191 rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, backupCount=5)
2192 rh.rotator = rotator
2193 rh.namer = namer
2194
2195 root = logging.getLogger()
2196 root.setLevel(logging.INFO)
2197 root.addHandler(rh)
2198 f = logging.Formatter('%(asctime)s %(message)s')
2199 rh.setFormatter(f)
2200 for i in range(1000):
2201 root.info(f'Message no. {i + 1}')
2202
2203 After running this, you will see six new files, five of which are compressed:
2204
2205 .. code-block:: shell-session
2206
2207 $ ls rotated.log*
2208 rotated.log rotated.log.2.gz rotated.log.4.gz
2209 rotated.log.1.gz rotated.log.3.gz rotated.log.5.gz
2210 $ zcat rotated.log.1.gz
2211 2023-01-20 02:28:17,767 Message no. 996
2212 2023-01-20 02:28:17,767 Message no. 997
2213 2023-01-20 02:28:17,767 Message no. 998
2214
2215 A more elaborate multiprocessing example
2216 ----------------------------------------
2217
2218 The following working example shows how logging can be used with multiprocessing
2219 using configuration files. The configurations are fairly simple, but serve to
2220 illustrate how more complex ones could be implemented in a real multiprocessing
2221 scenario.
2222
2223 In the example, the main process spawns a listener process and some worker
2224 processes. Each of the main process, the listener and the workers have three
2225 separate configurations (the workers all share the same configuration). We can
2226 see logging in the main process, how the workers log to a QueueHandler and how
2227 the listener implements a QueueListener and a more complex logging
2228 configuration, and arranges to dispatch events received via the queue to the
2229 handlers specified in the configuration. Note that these configurations are
2230 purely illustrative, but you should be able to adapt this example to your own
2231 scenario.
2232
2233 Here's the script - the docstrings and the comments hopefully explain how it
2234 works::
2235
2236 import logging
2237 import logging.config
2238 import logging.handlers
2239 from multiprocessing import Process, Queue, Event, current_process
2240 import os
2241 import random
2242 import time
2243
2244 class MyHandler:
2245 """
2246 A simple handler for logging events. It runs in the listener process and
2247 dispatches events to loggers based on the name in the received record,
2248 which then get dispatched, by the logging system, to the handlers
2249 configured for those loggers.
2250 """
2251
2252 def handle(self, record):
2253 if record.name == "root":
2254 logger = logging.getLogger()
2255 else:
2256 logger = logging.getLogger(record.name)
2257
2258 if logger.isEnabledFor(record.levelno):
2259 # The process name is transformed just to show that it's the listener
2260 # doing the logging to files and console
2261 record.processName = '%s (for %s)' % (current_process().name, record.processName)
2262 logger.handle(record)
2263
2264 def listener_process(q, stop_event, config):
2265 """
2266 This could be done in the main process, but is just done in a separate
2267 process for illustrative purposes.
2268
2269 This initialises logging according to the specified configuration,
2270 starts the listener and waits for the main process to signal completion
2271 via the event. The listener is then stopped, and the process exits.
2272 """
2273 logging.config.dictConfig(config)
2274 listener = logging.handlers.QueueListener(q, MyHandler())
2275 listener.start()
2276 if os.name == 'posix':
2277 # On POSIX, the setup logger will have been configured in the
2278 # parent process, but should have been disabled following the
2279 # dictConfig call.
2280 # On Windows, since fork isn't used, the setup logger won't
2281 # exist in the child, so it would be created and the message
2282 # would appear - hence the "if posix" clause.
2283 logger = logging.getLogger('setup')
2284 logger.critical('Should not appear, because of disabled logger ...')
2285 stop_event.wait()
2286 listener.stop()
2287
2288 def worker_process(config):
2289 """
2290 A number of these are spawned for the purpose of illustration. In
2291 practice, they could be a heterogeneous bunch of processes rather than
2292 ones which are identical to each other.
2293
2294 This initialises logging according to the specified configuration,
2295 and logs a hundred messages with random levels to randomly selected
2296 loggers.
2297
2298 A small sleep is added to allow other processes a chance to run. This
2299 is not strictly needed, but it mixes the output from the different
2300 processes a bit more than if it's left out.
2301 """
2302 logging.config.dictConfig(config)
2303 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
2304 logging.CRITICAL]
2305 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
2306 'spam', 'spam.ham', 'spam.ham.eggs']
2307 if os.name == 'posix':
2308 # On POSIX, the setup logger will have been configured in the
2309 # parent process, but should have been disabled following the
2310 # dictConfig call.
2311 # On Windows, since fork isn't used, the setup logger won't
2312 # exist in the child, so it would be created and the message
2313 # would appear - hence the "if posix" clause.
2314 logger = logging.getLogger('setup')
2315 logger.critical('Should not appear, because of disabled logger ...')
2316 for i in range(100):
2317 lvl = random.choice(levels)
2318 logger = logging.getLogger(random.choice(loggers))
2319 logger.log(lvl, 'Message no. %d', i)
2320 time.sleep(0.01)
2321
2322 def main():
2323 q = Queue()
2324 # The main process gets a simple configuration which prints to the console.
2325 config_initial = {
2326 'version': 1,
2327 'handlers': {
2328 'console': {
2329 'class': 'logging.StreamHandler',
2330 'level': 'INFO'
2331 }
2332 },
2333 'root': {
2334 'handlers': ['console'],
2335 'level': 'DEBUG'
2336 }
2337 }
2338 # The worker process configuration is just a QueueHandler attached to the
2339 # root logger, which allows all messages to be sent to the queue.
2340 # We disable existing loggers to disable the "setup" logger used in the
2341 # parent process. This is needed on POSIX because the logger will
2342 # be there in the child following a fork().
2343 config_worker = {
2344 'version': 1,
2345 'disable_existing_loggers': True,
2346 'handlers': {
2347 'queue': {
2348 'class': 'logging.handlers.QueueHandler',
2349 'queue': q
2350 }
2351 },
2352 'root': {
2353 'handlers': ['queue'],
2354 'level': 'DEBUG'
2355 }
2356 }
2357 # The listener process configuration shows that the full flexibility of
2358 # logging configuration is available to dispatch events to handlers however
2359 # you want.
2360 # We disable existing loggers to disable the "setup" logger used in the
2361 # parent process. This is needed on POSIX because the logger will
2362 # be there in the child following a fork().
2363 config_listener = {
2364 'version': 1,
2365 'disable_existing_loggers': True,
2366 'formatters': {
2367 'detailed': {
2368 'class': 'logging.Formatter',
2369 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
2370 },
2371 'simple': {
2372 'class': 'logging.Formatter',
2373 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
2374 }
2375 },
2376 'handlers': {
2377 'console': {
2378 'class': 'logging.StreamHandler',
2379 'formatter': 'simple',
2380 'level': 'INFO'
2381 },
2382 'file': {
2383 'class': 'logging.FileHandler',
2384 'filename': 'mplog.log',
2385 'mode': 'w',
2386 'formatter': 'detailed'
2387 },
2388 'foofile': {
2389 'class': 'logging.FileHandler',
2390 'filename': 'mplog-foo.log',
2391 'mode': 'w',
2392 'formatter': 'detailed'
2393 },
2394 'errors': {
2395 'class': 'logging.FileHandler',
2396 'filename': 'mplog-errors.log',
2397 'mode': 'w',
2398 'formatter': 'detailed',
2399 'level': 'ERROR'
2400 }
2401 },
2402 'loggers': {
2403 'foo': {
2404 'handlers': ['foofile']
2405 }
2406 },
2407 'root': {
2408 'handlers': ['console', 'file', 'errors'],
2409 'level': 'DEBUG'
2410 }
2411 }
2412 # Log some initial events, just to show that logging in the parent works
2413 # normally.
2414 logging.config.dictConfig(config_initial)
2415 logger = logging.getLogger('setup')
2416 logger.info('About to create workers ...')
2417 workers = []
2418 for i in range(5):
2419 wp = Process(target=worker_process, name='worker %d' % (i + 1),
2420 args=(config_worker,))
2421 workers.append(wp)
2422 wp.start()
2423 logger.info('Started worker: %s', wp.name)
2424 logger.info('About to create listener ...')
2425 stop_event = Event()
2426 lp = Process(target=listener_process, name='listener',
2427 args=(q, stop_event, config_listener))
2428 lp.start()
2429 logger.info('Started listener')
2430 # We now hang around for the workers to finish their work.
2431 for wp in workers:
2432 wp.join()
2433 # Workers all done, listening can now stop.
2434 # Logging in the parent still works normally.
2435 logger.info('Telling listener to stop ...')
2436 stop_event.set()
2437 lp.join()
2438 logger.info('All done.')
2439
2440 if __name__ == '__main__':
2441 main()
2442
2443
2444 Inserting a BOM into messages sent to a SysLogHandler
2445 -----------------------------------------------------
2446
2447 :rfc:`5424` requires that a
2448 Unicode message be sent to a syslog daemon as a set of bytes which have the
2449 following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
2450 Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the
2451 :rfc:`relevant section of the specification <5424#section-6>`.)
2452
2453 In Python 3.1, code was added to
2454 :class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
2455 unfortunately, it was implemented incorrectly, with the BOM appearing at the
2456 beginning of the message and hence not allowing any pure-ASCII component to
2457 appear before it.
2458
2459 As this behaviour is broken, the incorrect BOM insertion code is being removed
2460 from Python 3.2.4 and later. However, it is not being replaced, and if you
2461 want to produce :rfc:`5424`-compliant messages which include a BOM, an optional
2462 pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
2463 UTF-8, then you need to do the following:
2464
2465 #. Attach a :class:`~logging.Formatter` instance to your
2466 :class:`~logging.handlers.SysLogHandler` instance, with a format string
2467 such as::
2468
2469 'ASCII section\ufeffUnicode section'
2470
2471 The Unicode code point U+FEFF, when encoded using UTF-8, will be
2472 encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``.
2473
2474 #. Replace the ASCII section with whatever placeholders you like, but make sure
2475 that the data that appears in there after substitution is always ASCII (that
2476 way, it will remain unchanged after UTF-8 encoding).
2477
2478 #. Replace the Unicode section with whatever placeholders you like; if the data
2479 which appears there after substitution contains characters outside the ASCII
2480 range, that's fine -- it will be encoded using UTF-8.
2481
2482 The formatted message *will* be encoded using UTF-8 encoding by
2483 ``SysLogHandler``. If you follow the above rules, you should be able to produce
2484 :rfc:`5424`-compliant messages. If you don't, logging may not complain, but your
2485 messages will not be RFC 5424-compliant, and your syslog daemon may complain.
2486
2487
2488 Implementing structured logging
2489 -------------------------------
2490
2491 Although most logging messages are intended for reading by humans, and thus not
2492 readily machine-parseable, there might be circumstances where you want to output
2493 messages in a structured format which *is* capable of being parsed by a program
2494 (without needing complex regular expressions to parse the log message). This is
2495 straightforward to achieve using the logging package. There are a number of
2496 ways in which this could be achieved, but the following is a simple approach
2497 which uses JSON to serialise the event in a machine-parseable manner::
2498
2499 import json
2500 import logging
2501
2502 class StructuredMessage:
2503 def __init__(self, message, /, **kwargs):
2504 self.message = message
2505 self.kwargs = kwargs
2506
2507 def __str__(self):
2508 return '%s >>> %s' % (self.message, json.dumps(self.kwargs))
2509
2510 _ = StructuredMessage # optional, to improve readability
2511
2512 logging.basicConfig(level=logging.INFO, format='%(message)s')
2513 logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
2514
2515 If the above script is run, it prints:
2516
2517 .. code-block:: none
2518
2519 message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}
2520
2521 Note that the order of items might be different according to the version of
2522 Python used.
2523
2524 If you need more specialised processing, you can use a custom JSON encoder,
2525 as in the following complete example::
2526
2527 import json
2528 import logging
2529
2530
2531 class Encoder(json.JSONEncoder):
2532 def default(self, o):
2533 if isinstance(o, set):
2534 return tuple(o)
2535 elif isinstance(o, str):
2536 return o.encode('unicode_escape').decode('ascii')
2537 return super().default(o)
2538
2539 class StructuredMessage:
2540 def __init__(self, message, /, **kwargs):
2541 self.message = message
2542 self.kwargs = kwargs
2543
2544 def __str__(self):
2545 s = Encoder().encode(self.kwargs)
2546 return '%s >>> %s' % (self.message, s)
2547
2548 _ = StructuredMessage # optional, to improve readability
2549
2550 def main():
2551 logging.basicConfig(level=logging.INFO, format='%(message)s')
2552 logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))
2553
2554 if __name__ == '__main__':
2555 main()
2556
2557 When the above script is run, it prints:
2558
2559 .. code-block:: none
2560
2561 message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}
2562
2563 Note that the order of items might be different according to the version of
2564 Python used.
2565
2566
2567 .. _custom-handlers:
2568
2569 .. currentmodule:: logging.config
2570
2571 Customizing handlers with :func:`dictConfig`
2572 --------------------------------------------
2573
2574 There are times when you want to customize logging handlers in particular ways,
2575 and if you use :func:`dictConfig` you may be able to do this without
2576 subclassing. As an example, consider that you may want to set the ownership of a
2577 log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file
2578 handlers in the stdlib don't offer built-in support. You can customize handler
2579 creation using a plain function such as::
2580
2581 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
2582 if owner:
2583 if not os.path.exists(filename):
2584 open(filename, 'a').close()
2585 shutil.chown(filename, *owner)
2586 return logging.FileHandler(filename, mode, encoding)
2587
2588 You can then specify, in a logging configuration passed to :func:`dictConfig`,
2589 that a logging handler be created by calling this function::
2590
2591 LOGGING = {
2592 'version': 1,
2593 'disable_existing_loggers': False,
2594 'formatters': {
2595 'default': {
2596 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
2597 },
2598 },
2599 'handlers': {
2600 'file':{
2601 # The values below are popped from this dictionary and
2602 # used to create the handler, set the handler's level and
2603 # its formatter.
2604 '()': owned_file_handler,
2605 'level':'DEBUG',
2606 'formatter': 'default',
2607 # The values below are passed to the handler creator callable
2608 # as keyword arguments.
2609 'owner': ['pulse', 'pulse'],
2610 'filename': 'chowntest.log',
2611 'mode': 'w',
2612 'encoding': 'utf-8',
2613 },
2614 },
2615 'root': {
2616 'handlers': ['file'],
2617 'level': 'DEBUG',
2618 },
2619 }
2620
2621 In this example I am setting the ownership using the ``pulse`` user and group,
2622 just for the purposes of illustration. Putting it together into a working
2623 script, ``chowntest.py``::
2624
2625 import logging, logging.config, os, shutil
2626
2627 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
2628 if owner:
2629 if not os.path.exists(filename):
2630 open(filename, 'a').close()
2631 shutil.chown(filename, *owner)
2632 return logging.FileHandler(filename, mode, encoding)
2633
2634 LOGGING = {
2635 'version': 1,
2636 'disable_existing_loggers': False,
2637 'formatters': {
2638 'default': {
2639 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
2640 },
2641 },
2642 'handlers': {
2643 'file':{
2644 # The values below are popped from this dictionary and
2645 # used to create the handler, set the handler's level and
2646 # its formatter.
2647 '()': owned_file_handler,
2648 'level':'DEBUG',
2649 'formatter': 'default',
2650 # The values below are passed to the handler creator callable
2651 # as keyword arguments.
2652 'owner': ['pulse', 'pulse'],
2653 'filename': 'chowntest.log',
2654 'mode': 'w',
2655 'encoding': 'utf-8',
2656 },
2657 },
2658 'root': {
2659 'handlers': ['file'],
2660 'level': 'DEBUG',
2661 },
2662 }
2663
2664 logging.config.dictConfig(LOGGING)
2665 logger = logging.getLogger('mylogger')
2666 logger.debug('A debug message')
2667
2668 To run this, you will probably need to run as ``root``:
2669
2670 .. code-block:: shell-session
2671
2672 $ sudo python3.3 chowntest.py
2673 $ cat chowntest.log
2674 2013-11-05 09:34:51,128 DEBUG mylogger A debug message
2675 $ ls -l chowntest.log
2676 -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
2677
2678 Note that this example uses Python 3.3 because that's where :func:`shutil.chown`
2679 makes an appearance. This approach should work with any Python version that
2680 supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3
2681 versions, you would need to implement the actual ownership change using e.g.
2682 :func:`os.chown`.
2683
2684 In practice, the handler-creating function may be in a utility module somewhere
2685 in your project. Instead of the line in the configuration::
2686
2687 '()': owned_file_handler,
2688
2689 you could use e.g.::
2690
2691 '()': 'ext://project.util.owned_file_handler',
2692
2693 where ``project.util`` can be replaced with the actual name of the package
2694 where the function resides. In the above working script, using
2695 ``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable
2696 is resolved by :func:`dictConfig` from the ``ext://`` specification.
2697
2698 This example hopefully also points the way to how you could implement other
2699 types of file change - e.g. setting specific POSIX permission bits - in the
2700 same way, using :func:`os.chmod`.
2701
2702 Of course, the approach could also be extended to types of handler other than a
2703 :class:`~logging.FileHandler` - for example, one of the rotating file handlers,
2704 or a different type of handler altogether.
2705
2706
2707 .. currentmodule:: logging
2708
2709 .. _formatting-styles:
2710
2711 Using particular formatting styles throughout your application
2712 --------------------------------------------------------------
2713
2714 In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword
2715 parameter which, while defaulting to ``%`` for backward compatibility, allowed
2716 the specification of ``{`` or ``$`` to support the formatting approaches
2717 supported by :meth:`str.format` and :class:`string.Template`. Note that this
2718 governs the formatting of logging messages for final output to logs, and is
2719 completely orthogonal to how an individual logging message is constructed.
2720
2721 Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take
2722 positional parameters for the actual logging message itself, with keyword
2723 parameters used only for determining options for how to handle the logging call
2724 (e.g. the ``exc_info`` keyword parameter to indicate that traceback information
2725 should be logged, or the ``extra`` keyword parameter to indicate additional
2726 contextual information to be added to the log). So you cannot directly make
2727 logging calls using :meth:`str.format` or :class:`string.Template` syntax,
2728 because internally the logging package uses %-formatting to merge the format
2729 string and the variable arguments. There would be no changing this while preserving
2730 backward compatibility, since all logging calls which are out there in existing
2731 code will be using %-format strings.
2732
2733 There have been suggestions to associate format styles with specific loggers,
2734 but that approach also runs into backward compatibility problems because any
2735 existing code could be using a given logger name and using %-formatting.
2736
2737 For logging to work interoperably between any third-party libraries and your
2738 code, decisions about formatting need to be made at the level of the
2739 individual logging call. This opens up a couple of ways in which alternative
2740 formatting styles can be accommodated.
2741
2742
2743 Using LogRecord factories
2744 ^^^^^^^^^^^^^^^^^^^^^^^^^
2745
2746 In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned
2747 above, the logging package gained the ability to allow users to set their own
2748 :class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function.
2749 You can use this to set your own subclass of :class:`LogRecord`, which does the
2750 Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base
2751 class implementation of this method is where the ``msg % args`` formatting
2752 happens, and where you can substitute your alternate formatting; however, you
2753 should be careful to support all formatting styles and allow %-formatting as
2754 the default, to ensure interoperability with other code. Care should also be
2755 taken to call ``str(self.msg)``, just as the base implementation does.
2756
2757 Refer to the reference documentation on :func:`setLogRecordFactory` and
2758 :class:`LogRecord` for more information.
2759
2760
2761 Using custom message objects
2762 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2763
2764 There is another, perhaps simpler way that you can use {}- and $- formatting to
2765 construct your individual log messages. You may recall (from
2766 :ref:`arbitrary-object-messages`) that when logging you can use an arbitrary
2767 object as a message format string, and that the logging package will call
2768 :func:`str` on that object to get the actual format string. Consider the
2769 following two classes::
2770
2771 class BraceMessage:
2772 def __init__(self, fmt, /, *args, **kwargs):
2773 self.fmt = fmt
2774 self.args = args
2775 self.kwargs = kwargs
2776
2777 def __str__(self):
2778 return self.fmt.format(*self.args, **self.kwargs)
2779
2780 class DollarMessage:
2781 def __init__(self, fmt, /, **kwargs):
2782 self.fmt = fmt
2783 self.kwargs = kwargs
2784
2785 def __str__(self):
2786 from string import Template
2787 return Template(self.fmt).substitute(**self.kwargs)
2788
2789 Either of these can be used in place of a format string, to allow {}- or
2790 $-formatting to be used to build the actual "message" part which appears in the
2791 formatted log output in place of “%(message)s” or “{message}” or “$message”.
2792 If you find it a little unwieldy to use the class names whenever you want to log
2793 something, you can make it more palatable if you use an alias such as ``M`` or
2794 ``_`` for the message (or perhaps ``__``, if you are using ``_`` for
2795 localization).
2796
2797 Examples of this approach are given below. Firstly, formatting with
2798 :meth:`str.format`::
2799
2800 >>> __ = BraceMessage
2801 >>> print(__('Message with {0} {1}', 2, 'placeholders'))
2802 Message with 2 placeholders
2803 >>> class Point: pass
2804 ...
2805 >>> p = Point()
2806 >>> p.x = 0.5
2807 >>> p.y = 0.5
2808 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
2809 Message with coordinates: (0.50, 0.50)
2810
2811 Secondly, formatting with :class:`string.Template`::
2812
2813 >>> __ = DollarMessage
2814 >>> print(__('Message with $num $what', num=2, what='placeholders'))
2815 Message with 2 placeholders
2816 >>>
2817
2818 One thing to note is that you pay no significant performance penalty with this
2819 approach: the actual formatting happens not when you make the logging call, but
2820 when (and if) the logged message is actually about to be output to a log by a
2821 handler. So the only slightly unusual thing which might trip you up is that the
2822 parentheses go around the format string and the arguments, not just the format
2823 string. That’s because the __ notation is just syntax sugar for a constructor
2824 call to one of the :samp:`{XXX}Message` classes shown above.
2825
2826
2827 .. _filters-dictconfig:
2828
2829 .. currentmodule:: logging.config
2830
2831 Configuring filters with :func:`dictConfig`
2832 -------------------------------------------
2833
2834 You *can* configure filters using :func:`~logging.config.dictConfig`, though it
2835 might not be obvious at first glance how to do it (hence this recipe). Since
2836 :class:`~logging.Filter` is the only filter class included in the standard
2837 library, and it is unlikely to cater to many requirements (it's only there as a
2838 base class), you will typically need to define your own :class:`~logging.Filter`
2839 subclass with an overridden :meth:`~logging.Filter.filter` method. To do this,
2840 specify the ``()`` key in the configuration dictionary for the filter,
2841 specifying a callable which will be used to create the filter (a class is the
2842 most obvious, but you can provide any callable which returns a
2843 :class:`~logging.Filter` instance). Here is a complete example::
2844
2845 import logging
2846 import logging.config
2847 import sys
2848
2849 class MyFilter(logging.Filter):
2850 def __init__(self, param=None):
2851 self.param = param
2852
2853 def filter(self, record):
2854 if self.param is None:
2855 allow = True
2856 else:
2857 allow = self.param not in record.msg
2858 if allow:
2859 record.msg = 'changed: ' + record.msg
2860 return allow
2861
2862 LOGGING = {
2863 'version': 1,
2864 'filters': {
2865 'myfilter': {
2866 '()': MyFilter,
2867 'param': 'noshow',
2868 }
2869 },
2870 'handlers': {
2871 'console': {
2872 'class': 'logging.StreamHandler',
2873 'filters': ['myfilter']
2874 }
2875 },
2876 'root': {
2877 'level': 'DEBUG',
2878 'handlers': ['console']
2879 },
2880 }
2881
2882 if __name__ == '__main__':
2883 logging.config.dictConfig(LOGGING)
2884 logging.debug('hello')
2885 logging.debug('hello - noshow')
2886
2887 This example shows how you can pass configuration data to the callable which
2888 constructs the instance, in the form of keyword parameters. When run, the above
2889 script will print:
2890
2891 .. code-block:: none
2892
2893 changed: hello
2894
2895 which shows that the filter is working as configured.
2896
2897 A couple of extra points to note:
2898
2899 * If you can't refer to the callable directly in the configuration (e.g. if it
2900 lives in a different module, and you can't import it directly where the
2901 configuration dictionary is), you can use the form ``ext://...`` as described
2902 in :ref:`logging-config-dict-externalobj`. For example, you could have used
2903 the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above
2904 example.
2905
2906 * As well as for filters, this technique can also be used to configure custom
2907 handlers and formatters. See :ref:`logging-config-dict-userdef` for more
2908 information on how logging supports using user-defined objects in its
2909 configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
2910
2911
2912 .. _custom-format-exception:
2913
2914 Customized exception formatting
2915 -------------------------------
2916
2917 There might be times when you want to do customized exception formatting - for
2918 argument's sake, let's say you want exactly one line per logged event, even
2919 when exception information is present. You can do this with a custom formatter
2920 class, as shown in the following example::
2921
2922 import logging
2923
2924 class OneLineExceptionFormatter(logging.Formatter):
2925 def formatException(self, exc_info):
2926 """
2927 Format an exception so that it prints on a single line.
2928 """
2929 result = super().formatException(exc_info)
2930 return repr(result) # or format into one line however you want to
2931
2932 def format(self, record):
2933 s = super().format(record)
2934 if record.exc_text:
2935 s = s.replace('\n', '') + '|'
2936 return s
2937
2938 def configure_logging():
2939 fh = logging.FileHandler('output.txt', 'w')
2940 f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
2941 '%d/%m/%Y %H:%M:%S')
2942 fh.setFormatter(f)
2943 root = logging.getLogger()
2944 root.setLevel(logging.DEBUG)
2945 root.addHandler(fh)
2946
2947 def main():
2948 configure_logging()
2949 logging.info('Sample message')
2950 try:
2951 x = 1 / 0
2952 except ZeroDivisionError as e:
2953 logging.exception('ZeroDivisionError: %s', e)
2954
2955 if __name__ == '__main__':
2956 main()
2957
2958 When run, this produces a file with exactly two lines:
2959
2960 .. code-block:: none
2961
2962 28/01/2015 07:21:23|INFO|Sample message|
2963 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'|
2964
2965 While the above treatment is simplistic, it points the way to how exception
2966 information can be formatted to your liking. The :mod:`traceback` module may be
2967 helpful for more specialized needs.
2968
2969 .. _spoken-messages:
2970
2971 Speaking logging messages
2972 -------------------------
2973
2974 There might be situations when it is desirable to have logging messages rendered
2975 in an audible rather than a visible format. This is easy to do if you have
2976 text-to-speech (TTS) functionality available in your system, even if it doesn't have
2977 a Python binding. Most TTS systems have a command line program you can run, and
2978 this can be invoked from a handler using :mod:`subprocess`. It's assumed here
2979 that TTS command line programs won't expect to interact with users or take a
2980 long time to complete, and that the frequency of logged messages will be not so
2981 high as to swamp the user with messages, and that it's acceptable to have the
2982 messages spoken one at a time rather than concurrently, The example implementation
2983 below waits for one message to be spoken before the next is processed, and this
2984 might cause other handlers to be kept waiting. Here is a short example showing
2985 the approach, which assumes that the ``espeak`` TTS package is available::
2986
2987 import logging
2988 import subprocess
2989 import sys
2990
2991 class TTSHandler(logging.Handler):
2992 def emit(self, record):
2993 msg = self.format(record)
2994 # Speak slowly in a female English voice
2995 cmd = ['espeak', '-s150', '-ven+f3', msg]
2996 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
2997 stderr=subprocess.STDOUT)
2998 # wait for the program to finish
2999 p.communicate()
3000
3001 def configure_logging():
3002 h = TTSHandler()
3003 root = logging.getLogger()
3004 root.addHandler(h)
3005 # the default formatter just returns the message
3006 root.setLevel(logging.DEBUG)
3007
3008 def main():
3009 logging.info('Hello')
3010 logging.debug('Goodbye')
3011
3012 if __name__ == '__main__':
3013 configure_logging()
3014 sys.exit(main())
3015
3016 When run, this script should say "Hello" and then "Goodbye" in a female voice.
3017
3018 The above approach can, of course, be adapted to other TTS systems and even
3019 other systems altogether which can process messages via external programs run
3020 from a command line.
3021
3022
3023 .. _buffered-logging:
3024
3025 Buffering logging messages and outputting them conditionally
3026 ------------------------------------------------------------
3027
3028 There might be situations where you want to log messages in a temporary area
3029 and only output them if a certain condition occurs. For example, you may want to
3030 start logging debug events in a function, and if the function completes without
3031 errors, you don't want to clutter the log with the collected debug information,
3032 but if there is an error, you want all the debug information to be output as well
3033 as the error.
3034
3035 Here is an example which shows how you could do this using a decorator for your
3036 functions where you want logging to behave this way. It makes use of the
3037 :class:`logging.handlers.MemoryHandler`, which allows buffering of logged events
3038 until some condition occurs, at which point the buffered events are ``flushed``
3039 - passed to another handler (the ``target`` handler) for processing. By default,
3040 the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose
3041 level is greater than or equal to a specified threshold is seen. You can use this
3042 recipe with a more specialised subclass of ``MemoryHandler`` if you want custom
3043 flushing behavior.
3044
3045 The example script has a simple function, ``foo``, which just cycles through
3046 all the logging levels, writing to ``sys.stderr`` to say what level it's about
3047 to log at, and then actually logging a message at that level. You can pass a
3048 parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
3049 otherwise, it only logs at DEBUG, INFO and WARNING levels.
3050
3051 The script just arranges to decorate ``foo`` with a decorator which will do the
3052 conditional logging that's required. The decorator takes a logger as a parameter
3053 and attaches a memory handler for the duration of the call to the decorated
3054 function. The decorator can be additionally parameterised using a target handler,
3055 a level at which flushing should occur, and a capacity for the buffer (number of
3056 records buffered). These default to a :class:`~logging.StreamHandler` which
3057 writes to ``sys.stderr``, ``logging.ERROR`` and ``100`` respectively.
3058
3059 Here's the script::
3060
3061 import logging
3062 from logging.handlers import MemoryHandler
3063 import sys
3064
3065 logger = logging.getLogger(__name__)
3066 logger.addHandler(logging.NullHandler())
3067
3068 def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
3069 if target_handler is None:
3070 target_handler = logging.StreamHandler()
3071 if flush_level is None:
3072 flush_level = logging.ERROR
3073 if capacity is None:
3074 capacity = 100
3075 handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)
3076
3077 def decorator(fn):
3078 def wrapper(*args, **kwargs):
3079 logger.addHandler(handler)
3080 try:
3081 return fn(*args, **kwargs)
3082 except Exception:
3083 logger.exception('call failed')
3084 raise
3085 finally:
3086 super(MemoryHandler, handler).flush()
3087 logger.removeHandler(handler)
3088 return wrapper
3089
3090 return decorator
3091
3092 def write_line(s):
3093 sys.stderr.write('%s\n' % s)
3094
3095 def foo(fail=False):
3096 write_line('about to log at DEBUG ...')
3097 logger.debug('Actually logged at DEBUG')
3098 write_line('about to log at INFO ...')
3099 logger.info('Actually logged at INFO')
3100 write_line('about to log at WARNING ...')
3101 logger.warning('Actually logged at WARNING')
3102 if fail:
3103 write_line('about to log at ERROR ...')
3104 logger.error('Actually logged at ERROR')
3105 write_line('about to log at CRITICAL ...')
3106 logger.critical('Actually logged at CRITICAL')
3107 return fail
3108
3109 decorated_foo = log_if_errors(logger)(foo)
3110
3111 if __name__ == '__main__':
3112 logger.setLevel(logging.DEBUG)
3113 write_line('Calling undecorated foo with False')
3114 assert not foo(False)
3115 write_line('Calling undecorated foo with True')
3116 assert foo(True)
3117 write_line('Calling decorated foo with False')
3118 assert not decorated_foo(False)
3119 write_line('Calling decorated foo with True')
3120 assert decorated_foo(True)
3121
3122 When this script is run, the following output should be observed:
3123
3124 .. code-block:: none
3125
3126 Calling undecorated foo with False
3127 about to log at DEBUG ...
3128 about to log at INFO ...
3129 about to log at WARNING ...
3130 Calling undecorated foo with True
3131 about to log at DEBUG ...
3132 about to log at INFO ...
3133 about to log at WARNING ...
3134 about to log at ERROR ...
3135 about to log at CRITICAL ...
3136 Calling decorated foo with False
3137 about to log at DEBUG ...
3138 about to log at INFO ...
3139 about to log at WARNING ...
3140 Calling decorated foo with True
3141 about to log at DEBUG ...
3142 about to log at INFO ...
3143 about to log at WARNING ...
3144 about to log at ERROR ...
3145 Actually logged at DEBUG
3146 Actually logged at INFO
3147 Actually logged at WARNING
3148 Actually logged at ERROR
3149 about to log at CRITICAL ...
3150 Actually logged at CRITICAL
3151
3152 As you can see, actual logging output only occurs when an event is logged whose
3153 severity is ERROR or greater, but in that case, any previous events at lower
3154 severities are also logged.
3155
3156 You can of course use the conventional means of decoration::
3157
3158 @log_if_errors(logger)
3159 def foo(fail=False):
3160 ...
3161
3162
3163 .. _buffered-smtp:
3164
3165 Sending logging messages to email, with buffering
3166 -------------------------------------------------
3167
3168 To illustrate how you can send log messages via email, so that a set number of
3169 messages are sent per email, you can subclass
3170 :class:`~logging.handlers.BufferingHandler`. In the following example, which you can
3171 adapt to suit your specific needs, a simple test harness is provided which allows you
3172 to run the script with command line arguments specifying what you typically need to
3173 send things via SMTP. (Run the downloaded script with the ``-h`` argument to see the
3174 required and optional arguments.)
3175
3176 .. code-block:: python
3177
3178 import logging
3179 import logging.handlers
3180 import smtplib
3181
3182 class BufferingSMTPHandler(logging.handlers.BufferingHandler):
3183 def __init__(self, mailhost, port, username, password, fromaddr, toaddrs,
3184 subject, capacity):
3185 logging.handlers.BufferingHandler.__init__(self, capacity)
3186 self.mailhost = mailhost
3187 self.mailport = port
3188 self.username = username
3189 self.password = password
3190 self.fromaddr = fromaddr
3191 if isinstance(toaddrs, str):
3192 toaddrs = [toaddrs]
3193 self.toaddrs = toaddrs
3194 self.subject = subject
3195 self.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))
3196
3197 def flush(self):
3198 if len(self.buffer) > 0:
3199 try:
3200 smtp = smtplib.SMTP(self.mailhost, self.mailport)
3201 smtp.starttls()
3202 smtp.login(self.username, self.password)
3203 msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (self.fromaddr, ','.join(self.toaddrs), self.subject)
3204 for record in self.buffer:
3205 s = self.format(record)
3206 msg = msg + s + "\r\n"
3207 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
3208 smtp.quit()
3209 except Exception:
3210 if logging.raiseExceptions:
3211 raise
3212 self.buffer = []
3213
3214 if __name__ == '__main__':
3215 import argparse
3216
3217 ap = argparse.ArgumentParser()
3218 aa = ap.add_argument
3219 aa('host', metavar='HOST', help='SMTP server')
3220 aa('--port', '-p', type=int, default=587, help='SMTP port')
3221 aa('user', metavar='USER', help='SMTP username')
3222 aa('password', metavar='PASSWORD', help='SMTP password')
3223 aa('to', metavar='TO', help='Addressee for emails')
3224 aa('sender', metavar='SENDER', help='Sender email address')
3225 aa('--subject', '-s',
3226 default='Test Logging email from Python logging module (buffering)',
3227 help='Subject of email')
3228 options = ap.parse_args()
3229 logger = logging.getLogger()
3230 logger.setLevel(logging.DEBUG)
3231 h = BufferingSMTPHandler(options.host, options.port, options.user,
3232 options.password, options.sender,
3233 options.to, options.subject, 10)
3234 logger.addHandler(h)
3235 for i in range(102):
3236 logger.info("Info index = %d", i)
3237 h.flush()
3238 h.close()
3239
3240 If you run this script and your SMTP server is correctly set up, you should find that
3241 it sends eleven emails to the addressee you specify. The first ten emails will each
3242 have ten log messages, and the eleventh will have two messages. That makes up 102
3243 messages as specified in the script.
3244
3245 .. _utc-formatting:
3246
3247 Formatting times using UTC (GMT) via configuration
3248 --------------------------------------------------
3249
3250 Sometimes you want to format times using UTC, which can be done using a class
3251 such as ``UTCFormatter``, shown below::
3252
3253 import logging
3254 import time
3255
3256 class UTCFormatter(logging.Formatter):
3257 converter = time.gmtime
3258
3259 and you can then use the ``UTCFormatter`` in your code instead of
3260 :class:`~logging.Formatter`. If you want to do that via configuration, you can
3261 use the :func:`~logging.config.dictConfig` API with an approach illustrated by
3262 the following complete example::
3263
3264 import logging
3265 import logging.config
3266 import time
3267
3268 class UTCFormatter(logging.Formatter):
3269 converter = time.gmtime
3270
3271 LOGGING = {
3272 'version': 1,
3273 'disable_existing_loggers': False,
3274 'formatters': {
3275 'utc': {
3276 '()': UTCFormatter,
3277 'format': '%(asctime)s %(message)s',
3278 },
3279 'local': {
3280 'format': '%(asctime)s %(message)s',
3281 }
3282 },
3283 'handlers': {
3284 'console1': {
3285 'class': 'logging.StreamHandler',
3286 'formatter': 'utc',
3287 },
3288 'console2': {
3289 'class': 'logging.StreamHandler',
3290 'formatter': 'local',
3291 },
3292 },
3293 'root': {
3294 'handlers': ['console1', 'console2'],
3295 }
3296 }
3297
3298 if __name__ == '__main__':
3299 logging.config.dictConfig(LOGGING)
3300 logging.warning('The local time is %s', time.asctime())
3301
3302 When this script is run, it should print something like:
3303
3304 .. code-block:: none
3305
3306 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
3307 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
3308
3309 showing how the time is formatted both as local time and UTC, one for each
3310 handler.
3311
3312
3313 .. _context-manager:
3314
3315 Using a context manager for selective logging
3316 ---------------------------------------------
3317
3318 There are times when it would be useful to temporarily change the logging
3319 configuration and revert it back after doing something. For this, a context
3320 manager is the most obvious way of saving and restoring the logging context.
3321 Here is a simple example of such a context manager, which allows you to
3322 optionally change the logging level and add a logging handler purely in the
3323 scope of the context manager::
3324
3325 import logging
3326 import sys
3327
3328 class LoggingContext:
3329 def __init__(self, logger, level=None, handler=None, close=True):
3330 self.logger = logger
3331 self.level = level
3332 self.handler = handler
3333 self.close = close
3334
3335 def __enter__(self):
3336 if self.level is not None:
3337 self.old_level = self.logger.level
3338 self.logger.setLevel(self.level)
3339 if self.handler:
3340 self.logger.addHandler(self.handler)
3341
3342 def __exit__(self, et, ev, tb):
3343 if self.level is not None:
3344 self.logger.setLevel(self.old_level)
3345 if self.handler:
3346 self.logger.removeHandler(self.handler)
3347 if self.handler and self.close:
3348 self.handler.close()
3349 # implicit return of None => don't swallow exceptions
3350
3351 If you specify a level value, the logger's level is set to that value in the
3352 scope of the with block covered by the context manager. If you specify a
3353 handler, it is added to the logger on entry to the block and removed on exit
3354 from the block. You can also ask the manager to close the handler for you on
3355 block exit - you could do this if you don't need the handler any more.
3356
3357 To illustrate how it works, we can add the following block of code to the
3358 above::
3359
3360 if __name__ == '__main__':
3361 logger = logging.getLogger('foo')
3362 logger.addHandler(logging.StreamHandler())
3363 logger.setLevel(logging.INFO)
3364 logger.info('1. This should appear just once on stderr.')
3365 logger.debug('2. This should not appear.')
3366 with LoggingContext(logger, level=logging.DEBUG):
3367 logger.debug('3. This should appear once on stderr.')
3368 logger.debug('4. This should not appear.')
3369 h = logging.StreamHandler(sys.stdout)
3370 with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
3371 logger.debug('5. This should appear twice - once on stderr and once on stdout.')
3372 logger.info('6. This should appear just once on stderr.')
3373 logger.debug('7. This should not appear.')
3374
3375 We initially set the logger's level to ``INFO``, so message #1 appears and
3376 message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the
3377 following ``with`` block, and so message #3 appears. After the block exits, the
3378 logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the
3379 next ``with`` block, we set the level to ``DEBUG`` again but also add a handler
3380 writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once
3381 via ``stderr`` and once via ``stdout``). After the ``with`` statement's
3382 completion, the status is as it was before so message #6 appears (like message
3383 #1) whereas message #7 doesn't (just like message #2).
3384
3385 If we run the resulting script, the result is as follows:
3386
3387 .. code-block:: shell-session
3388
3389 $ python logctx.py
3390 1. This should appear just once on stderr.
3391 3. This should appear once on stderr.
3392 5. This should appear twice - once on stderr and once on stdout.
3393 5. This should appear twice - once on stderr and once on stdout.
3394 6. This should appear just once on stderr.
3395
3396 If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
3397 which is the only message written to ``stdout``:
3398
3399 .. code-block:: shell-session
3400
3401 $ python logctx.py 2>/dev/null
3402 5. This should appear twice - once on stderr and once on stdout.
3403
3404 Once again, but piping ``stdout`` to ``/dev/null``, we get:
3405
3406 .. code-block:: shell-session
3407
3408 $ python logctx.py >/dev/null
3409 1. This should appear just once on stderr.
3410 3. This should appear once on stderr.
3411 5. This should appear twice - once on stderr and once on stdout.
3412 6. This should appear just once on stderr.
3413
3414 In this case, the message #5 printed to ``stdout`` doesn't appear, as expected.
3415
3416 Of course, the approach described here can be generalised, for example to attach
3417 logging filters temporarily. Note that the above code works in Python 2 as well
3418 as Python 3.
3419
3420
3421 .. _starter-template:
3422
3423 A CLI application starter template
3424 ----------------------------------
3425
3426 Here's an example which shows how you can:
3427
3428 * Use a logging level based on command-line arguments
3429 * Dispatch to multiple subcommands in separate files, all logging at the same
3430 level in a consistent way
3431 * Make use of simple, minimal configuration
3432
3433 Suppose we have a command-line application whose job is to stop, start or
3434 restart some services. This could be organised for the purposes of illustration
3435 as a file ``app.py`` that is the main script for the application, with individual
3436 commands implemented in ``start.py``, ``stop.py`` and ``restart.py``. Suppose
3437 further that we want to control the verbosity of the application via a
3438 command-line argument, defaulting to ``logging.INFO``. Here's one way that
3439 ``app.py`` could be written::
3440
3441 import argparse
3442 import importlib
3443 import logging
3444 import os
3445 import sys
3446
3447 def main(args=None):
3448 scriptname = os.path.basename(__file__)
3449 parser = argparse.ArgumentParser(scriptname)
3450 levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
3451 parser.add_argument('--log-level', default='INFO', choices=levels)
3452 subparsers = parser.add_subparsers(dest='command',
3453 help='Available commands:')
3454 start_cmd = subparsers.add_parser('start', help='Start a service')
3455 start_cmd.add_argument('name', metavar='NAME',
3456 help='Name of service to start')
3457 stop_cmd = subparsers.add_parser('stop',
3458 help='Stop one or more services')
3459 stop_cmd.add_argument('names', metavar='NAME', nargs='+',
3460 help='Name of service to stop')
3461 restart_cmd = subparsers.add_parser('restart',
3462 help='Restart one or more services')
3463 restart_cmd.add_argument('names', metavar='NAME', nargs='+',
3464 help='Name of service to restart')
3465 options = parser.parse_args()
3466 # the code to dispatch commands could all be in this file. For the purposes
3467 # of illustration only, we implement each command in a separate module.
3468 try:
3469 mod = importlib.import_module(options.command)
3470 cmd = getattr(mod, 'command')
3471 except (ImportError, AttributeError):
3472 print('Unable to find the code for command \'%s\'' % options.command)
3473 return 1
3474 # Could get fancy here and load configuration from file or dictionary
3475 logging.basicConfig(level=options.log_level,
3476 format='%(levelname)s %(name)s %(message)s')
3477 cmd(options)
3478
3479 if __name__ == '__main__':
3480 sys.exit(main())
3481
3482 And the ``start``, ``stop`` and ``restart`` commands can be implemented in
3483 separate modules, like so for starting::
3484
3485 # start.py
3486 import logging
3487
3488 logger = logging.getLogger(__name__)
3489
3490 def command(options):
3491 logger.debug('About to start %s', options.name)
3492 # actually do the command processing here ...
3493 logger.info('Started the \'%s\' service.', options.name)
3494
3495 and thus for stopping::
3496
3497 # stop.py
3498 import logging
3499
3500 logger = logging.getLogger(__name__)
3501
3502 def command(options):
3503 n = len(options.names)
3504 if n == 1:
3505 plural = ''
3506 services = '\'%s\'' % options.names[0]
3507 else:
3508 plural = 's'
3509 services = ', '.join('\'%s\'' % name for name in options.names)
3510 i = services.rfind(', ')
3511 services = services[:i] + ' and ' + services[i + 2:]
3512 logger.debug('About to stop %s', services)
3513 # actually do the command processing here ...
3514 logger.info('Stopped the %s service%s.', services, plural)
3515
3516 and similarly for restarting::
3517
3518 # restart.py
3519 import logging
3520
3521 logger = logging.getLogger(__name__)
3522
3523 def command(options):
3524 n = len(options.names)
3525 if n == 1:
3526 plural = ''
3527 services = '\'%s\'' % options.names[0]
3528 else:
3529 plural = 's'
3530 services = ', '.join('\'%s\'' % name for name in options.names)
3531 i = services.rfind(', ')
3532 services = services[:i] + ' and ' + services[i + 2:]
3533 logger.debug('About to restart %s', services)
3534 # actually do the command processing here ...
3535 logger.info('Restarted the %s service%s.', services, plural)
3536
3537 If we run this application with the default log level, we get output like this:
3538
3539 .. code-block:: shell-session
3540
3541 $ python app.py start foo
3542 INFO start Started the 'foo' service.
3543
3544 $ python app.py stop foo bar
3545 INFO stop Stopped the 'foo' and 'bar' services.
3546
3547 $ python app.py restart foo bar baz
3548 INFO restart Restarted the 'foo', 'bar' and 'baz' services.
3549
3550 The first word is the logging level, and the second word is the module or
3551 package name of the place where the event was logged.
3552
3553 If we change the logging level, then we can change the information sent to the
3554 log. For example, if we want more information:
3555
3556 .. code-block:: shell-session
3557
3558 $ python app.py --log-level DEBUG start foo
3559 DEBUG start About to start foo
3560 INFO start Started the 'foo' service.
3561
3562 $ python app.py --log-level DEBUG stop foo bar
3563 DEBUG stop About to stop 'foo' and 'bar'
3564 INFO stop Stopped the 'foo' and 'bar' services.
3565
3566 $ python app.py --log-level DEBUG restart foo bar baz
3567 DEBUG restart About to restart 'foo', 'bar' and 'baz'
3568 INFO restart Restarted the 'foo', 'bar' and 'baz' services.
3569
3570 And if we want less:
3571
3572 .. code-block:: shell-session
3573
3574 $ python app.py --log-level WARNING start foo
3575 $ python app.py --log-level WARNING stop foo bar
3576 $ python app.py --log-level WARNING restart foo bar baz
3577
3578 In this case, the commands don't print anything to the console, since nothing
3579 at ``WARNING`` level or above is logged by them.
3580
3581 .. _qt-gui:
3582
3583 A Qt GUI for logging
3584 --------------------
3585
3586 A question that comes up from time to time is about how to log to a GUI
3587 application. The `Qt <https://www.qt.io/>`_ framework is a popular
3588 cross-platform UI framework with Python bindings using :pypi:`PySide2`
3589 or :pypi:`PyQt5` libraries.
3590
3591 The following example shows how to log to a Qt GUI. This introduces a simple
3592 ``QtHandler`` class which takes a callable, which should be a slot in the main
3593 thread that does GUI updates. A worker thread is also created to show how you
3594 can log to the GUI from both the UI itself (via a button for manual logging)
3595 as well as a worker thread doing work in the background (here, just logging
3596 messages at random levels with random short delays in between).
3597
3598 The worker thread is implemented using Qt's ``QThread`` class rather than the
3599 :mod:`threading` module, as there are circumstances where one has to use
3600 ``QThread``, which offers better integration with other ``Qt`` components.
3601
3602 The code should work with recent releases of any of ``PySide6``, ``PyQt6``,
3603 ``PySide2`` or ``PyQt5``. You should be able to adapt the approach to earlier
3604 versions of Qt. Please refer to the comments in the code snippet for more
3605 detailed information.
3606
3607 .. code-block:: python3
3608
3609 import datetime
3610 import logging
3611 import random
3612 import sys
3613 import time
3614
3615 # Deal with minor differences between different Qt packages
3616 try:
3617 from PySide6 import QtCore, QtGui, QtWidgets
3618 Signal = QtCore.Signal
3619 Slot = QtCore.Slot
3620 except ImportError:
3621 try:
3622 from PyQt6 import QtCore, QtGui, QtWidgets
3623 Signal = QtCore.pyqtSignal
3624 Slot = QtCore.pyqtSlot
3625 except ImportError:
3626 try:
3627 from PySide2 import QtCore, QtGui, QtWidgets
3628 Signal = QtCore.Signal
3629 Slot = QtCore.Slot
3630 except ImportError:
3631 from PyQt5 import QtCore, QtGui, QtWidgets
3632 Signal = QtCore.pyqtSignal
3633 Slot = QtCore.pyqtSlot
3634
3635 logger = logging.getLogger(__name__)
3636
3637
3638 #
3639 # Signals need to be contained in a QObject or subclass in order to be correctly
3640 # initialized.
3641 #
3642 class Signaller(QtCore.QObject):
3643 signal = Signal(str, logging.LogRecord)
3644
3645 #
3646 # Output to a Qt GUI is only supposed to happen on the main thread. So, this
3647 # handler is designed to take a slot function which is set up to run in the main
3648 # thread. In this example, the function takes a string argument which is a
3649 # formatted log message, and the log record which generated it. The formatted
3650 # string is just a convenience - you could format a string for output any way
3651 # you like in the slot function itself.
3652 #
3653 # You specify the slot function to do whatever GUI updates you want. The handler
3654 # doesn't know or care about specific UI elements.
3655 #
3656 class QtHandler(logging.Handler):
3657 def __init__(self, slotfunc, *args, **kwargs):
3658 super().__init__(*args, **kwargs)
3659 self.signaller = Signaller()
3660 self.signaller.signal.connect(slotfunc)
3661
3662 def emit(self, record):
3663 s = self.format(record)
3664 self.signaller.signal.emit(s, record)
3665
3666 #
3667 # This example uses QThreads, which means that the threads at the Python level
3668 # are named something like "Dummy-1". The function below gets the Qt name of the
3669 # current thread.
3670 #
3671 def ctname():
3672 return QtCore.QThread.currentThread().objectName()
3673
3674
3675 #
3676 # Used to generate random levels for logging.
3677 #
3678 LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
3679 logging.CRITICAL)
3680
3681 #
3682 # This worker class represents work that is done in a thread separate to the
3683 # main thread. The way the thread is kicked off to do work is via a button press
3684 # that connects to a slot in the worker.
3685 #
3686 # Because the default threadName value in the LogRecord isn't much use, we add
3687 # a qThreadName which contains the QThread name as computed above, and pass that
3688 # value in an "extra" dictionary which is used to update the LogRecord with the
3689 # QThread name.
3690 #
3691 # This example worker just outputs messages sequentially, interspersed with
3692 # random delays of the order of a few seconds.
3693 #
3694 class Worker(QtCore.QObject):
3695 @Slot()
3696 def start(self):
3697 extra = {'qThreadName': ctname() }
3698 logger.debug('Started work', extra=extra)
3699 i = 1
3700 # Let the thread run until interrupted. This allows reasonably clean
3701 # thread termination.
3702 while not QtCore.QThread.currentThread().isInterruptionRequested():
3703 delay = 0.5 + random.random() * 2
3704 time.sleep(delay)
3705 try:
3706 if random.random() < 0.1:
3707 raise ValueError('Exception raised: %d' % i)
3708 else:
3709 level = random.choice(LEVELS)
3710 logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra)
3711 except ValueError as e:
3712 logger.exception('Failed: %s', e, extra=extra)
3713 i += 1
3714
3715 #
3716 # Implement a simple UI for this cookbook example. This contains:
3717 #
3718 # * A read-only text edit window which holds formatted log messages
3719 # * A button to start work and log stuff in a separate thread
3720 # * A button to log something from the main thread
3721 # * A button to clear the log window
3722 #
3723 class Window(QtWidgets.QWidget):
3724
3725 COLORS = {
3726 logging.DEBUG: 'black',
3727 logging.INFO: 'blue',
3728 logging.WARNING: 'orange',
3729 logging.ERROR: 'red',
3730 logging.CRITICAL: 'purple',
3731 }
3732
3733 def __init__(self, app):
3734 super().__init__()
3735 self.app = app
3736 self.textedit = te = QtWidgets.QPlainTextEdit(self)
3737 # Set whatever the default monospace font is for the platform
3738 f = QtGui.QFont('nosuchfont')
3739 if hasattr(f, 'Monospace'):
3740 f.setStyleHint(f.Monospace)
3741 else:
3742 f.setStyleHint(f.StyleHint.Monospace) # for Qt6
3743 te.setFont(f)
3744 te.setReadOnly(True)
3745 PB = QtWidgets.QPushButton
3746 self.work_button = PB('Start background work', self)
3747 self.log_button = PB('Log a message at a random level', self)
3748 self.clear_button = PB('Clear log window', self)
3749 self.handler = h = QtHandler(self.update_status)
3750 # Remember to use qThreadName rather than threadName in the format string.
3751 fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'
3752 formatter = logging.Formatter(fs)
3753 h.setFormatter(formatter)
3754 logger.addHandler(h)
3755 # Set up to terminate the QThread when we exit
3756 app.aboutToQuit.connect(self.force_quit)
3757
3758 # Lay out all the widgets
3759 layout = QtWidgets.QVBoxLayout(self)
3760 layout.addWidget(te)
3761 layout.addWidget(self.work_button)
3762 layout.addWidget(self.log_button)
3763 layout.addWidget(self.clear_button)
3764 self.setFixedSize(900, 400)
3765
3766 # Connect the non-worker slots and signals
3767 self.log_button.clicked.connect(self.manual_update)
3768 self.clear_button.clicked.connect(self.clear_display)
3769
3770 # Start a new worker thread and connect the slots for the worker
3771 self.start_thread()
3772 self.work_button.clicked.connect(self.worker.start)
3773 # Once started, the button should be disabled
3774 self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False))
3775
3776 def start_thread(self):
3777 self.worker = Worker()
3778 self.worker_thread = QtCore.QThread()
3779 self.worker.setObjectName('Worker')
3780 self.worker_thread.setObjectName('WorkerThread') # for qThreadName
3781 self.worker.moveToThread(self.worker_thread)
3782 # This will start an event loop in the worker thread
3783 self.worker_thread.start()
3784
3785 def kill_thread(self):
3786 # Just tell the worker to stop, then tell it to quit and wait for that
3787 # to happen
3788 self.worker_thread.requestInterruption()
3789 if self.worker_thread.isRunning():
3790 self.worker_thread.quit()
3791 self.worker_thread.wait()
3792 else:
3793 print('worker has already exited.')
3794
3795 def force_quit(self):
3796 # For use when the window is closed
3797 if self.worker_thread.isRunning():
3798 self.kill_thread()
3799
3800 # The functions below update the UI and run in the main thread because
3801 # that's where the slots are set up
3802
3803 @Slot(str, logging.LogRecord)
3804 def update_status(self, status, record):
3805 color = self.COLORS.get(record.levelno, 'black')
3806 s = '<pre><font color="%s">%s</font></pre>' % (color, status)
3807 self.textedit.appendHtml(s)
3808
3809 @Slot()
3810 def manual_update(self):
3811 # This function uses the formatted message passed in, but also uses
3812 # information from the record to format the message in an appropriate
3813 # color according to its severity (level).
3814 level = random.choice(LEVELS)
3815 extra = {'qThreadName': ctname() }
3816 logger.log(level, 'Manually logged!', extra=extra)
3817
3818 @Slot()
3819 def clear_display(self):
3820 self.textedit.clear()
3821
3822
3823 def main():
3824 QtCore.QThread.currentThread().setObjectName('MainThread')
3825 logging.getLogger().setLevel(logging.DEBUG)
3826 app = QtWidgets.QApplication(sys.argv)
3827 example = Window(app)
3828 example.show()
3829 if hasattr(app, 'exec'):
3830 rc = app.exec()
3831 else:
3832 rc = app.exec_()
3833 sys.exit(rc)
3834
3835 if __name__=='__main__':
3836 main()
3837
3838 Logging to syslog with RFC5424 support
3839 --------------------------------------
3840
3841 Although :rfc:`5424` dates from 2009, most syslog servers are configured by default to
3842 use the older :rfc:`3164`, which hails from 2001. When ``logging`` was added to Python
3843 in 2003, it supported the earlier (and only existing) protocol at the time. Since
3844 RFC5424 came out, as there has not been widespread deployment of it in syslog
3845 servers, the :class:`~logging.handlers.SysLogHandler` functionality has not been
3846 updated.
3847
3848 RFC 5424 contains some useful features such as support for structured data, and if you
3849 need to be able to log to a syslog server with support for it, you can do so with a
3850 subclassed handler which looks something like this::
3851
3852 import datetime
3853 import logging.handlers
3854 import re
3855 import socket
3856 import time
3857
3858 class SysLogHandler5424(logging.handlers.SysLogHandler):
3859
3860 tz_offset = re.compile(r'([+-]\d{2})(\d{2})$')
3861 escaped = re.compile(r'([\]"\\])')
3862
3863 def __init__(self, *args, **kwargs):
3864 self.msgid = kwargs.pop('msgid', None)
3865 self.appname = kwargs.pop('appname', None)
3866 super().__init__(*args, **kwargs)
3867
3868 def format(self, record):
3869 version = 1
3870 asctime = datetime.datetime.fromtimestamp(record.created).isoformat()
3871 m = self.tz_offset.match(time.strftime('%z'))
3872 has_offset = False
3873 if m and time.timezone:
3874 hrs, mins = m.groups()
3875 if int(hrs) or int(mins):
3876 has_offset = True
3877 if not has_offset:
3878 asctime += 'Z'
3879 else:
3880 asctime += f'{hrs}:{mins}'
3881 try:
3882 hostname = socket.gethostname()
3883 except Exception:
3884 hostname = '-'
3885 appname = self.appname or '-'
3886 procid = record.process
3887 msgid = '-'
3888 msg = super().format(record)
3889 sdata = '-'
3890 if hasattr(record, 'structured_data'):
3891 sd = record.structured_data
3892 # This should be a dict where the keys are SD-ID and the value is a
3893 # dict mapping PARAM-NAME to PARAM-VALUE (refer to the RFC for what these
3894 # mean)
3895 # There's no error checking here - it's purely for illustration, and you
3896 # can adapt this code for use in production environments
3897 parts = []
3898
3899 def replacer(m):
3900 g = m.groups()
3901 return '\\' + g[0]
3902
3903 for sdid, dv in sd.items():
3904 part = f'[{sdid}'
3905 for k, v in dv.items():
3906 s = str(v)
3907 s = self.escaped.sub(replacer, s)
3908 part += f' {k}="{s}"'
3909 part += ']'
3910 parts.append(part)
3911 sdata = ''.join(parts)
3912 return f'{version} {asctime} {hostname} {appname} {procid} {msgid} {sdata} {msg}'
3913
3914 You'll need to be familiar with RFC 5424 to fully understand the above code, and it
3915 may be that you have slightly different needs (e.g. for how you pass structural data
3916 to the log). Nevertheless, the above should be adaptable to your speciric needs. With
3917 the above handler, you'd pass structured data using something like this::
3918
3919 sd = {
3920 'foo@12345': {'bar': 'baz', 'baz': 'bozz', 'fizz': r'buzz'},
3921 'foo@54321': {'rab': 'baz', 'zab': 'bozz', 'zzif': r'buzz'}
3922 }
3923 extra = {'structured_data': sd}
3924 i = 1
3925 logger.debug('Message %d', i, extra=extra)
3926
3927 How to treat a logger like an output stream
3928 -------------------------------------------
3929
3930 Sometimes, you need to interface to a third-party API which expects a file-like
3931 object to write to, but you want to direct the API's output to a logger. You
3932 can do this using a class which wraps a logger with a file-like API.
3933 Here's a short script illustrating such a class:
3934
3935 .. code-block:: python
3936
3937 import logging
3938
3939 class LoggerWriter:
3940 def __init__(self, logger, level):
3941 self.logger = logger
3942 self.level = level
3943
3944 def write(self, message):
3945 if message != '\n': # avoid printing bare newlines, if you like
3946 self.logger.log(self.level, message)
3947
3948 def flush(self):
3949 # doesn't actually do anything, but might be expected of a file-like
3950 # object - so optional depending on your situation
3951 pass
3952
3953 def close(self):
3954 # doesn't actually do anything, but might be expected of a file-like
3955 # object - so optional depending on your situation. You might want
3956 # to set a flag so that later calls to write raise an exception
3957 pass
3958
3959 def main():
3960 logging.basicConfig(level=logging.DEBUG)
3961 logger = logging.getLogger('demo')
3962 info_fp = LoggerWriter(logger, logging.INFO)
3963 debug_fp = LoggerWriter(logger, logging.DEBUG)
3964 print('An INFO message', file=info_fp)
3965 print('A DEBUG message', file=debug_fp)
3966
3967 if __name__ == "__main__":
3968 main()
3969
3970 When this script is run, it prints
3971
3972 .. code-block:: text
3973
3974 INFO:demo:An INFO message
3975 DEBUG:demo:A DEBUG message
3976
3977 You could also use ``LoggerWriter`` to redirect ``sys.stdout`` and
3978 ``sys.stderr`` by doing something like this:
3979
3980 .. code-block:: python
3981
3982 import sys
3983
3984 sys.stdout = LoggerWriter(logger, logging.INFO)
3985 sys.stderr = LoggerWriter(logger, logging.WARNING)
3986
3987 You should do this *after* configuring logging for your needs. In the above
3988 example, the :func:`~logging.basicConfig` call does this (using the
3989 ``sys.stderr`` value *before* it is overwritten by a ``LoggerWriter``
3990 instance). Then, you'd get this kind of result:
3991
3992 .. code-block:: pycon
3993
3994 >>> print('Foo')
3995 INFO:demo:Foo
3996 >>> print('Bar', file=sys.stderr)
3997 WARNING:demo:Bar
3998 >>>
3999
4000 Of course, the examples above show output according to the format used by
4001 :func:`~logging.basicConfig`, but you can use a different formatter when you
4002 configure logging.
4003
4004 Note that with the above scheme, you are somewhat at the mercy of buffering and
4005 the sequence of write calls which you are intercepting. For example, with the
4006 definition of ``LoggerWriter`` above, if you have the snippet
4007
4008 .. code-block:: python
4009
4010 sys.stderr = LoggerWriter(logger, logging.WARNING)
4011 1 / 0
4012
4013 then running the script results in
4014
4015 .. code-block:: text
4016
4017 WARNING:demo:Traceback (most recent call last):
4018
4019 WARNING:demo: File "/home/runner/cookbook-loggerwriter/test.py", line 53, in <module>
4020
4021 WARNING:demo:
4022 WARNING:demo:main()
4023 WARNING:demo: File "/home/runner/cookbook-loggerwriter/test.py", line 49, in main
4024
4025 WARNING:demo:
4026 WARNING:demo:1 / 0
4027 WARNING:demo:ZeroDivisionError
4028 WARNING:demo::
4029 WARNING:demo:division by zero
4030
4031 As you can see, this output isn't ideal. That's because the underlying code
4032 which writes to ``sys.stderr`` makes multiple writes, each of which results in a
4033 separate logged line (for example, the last three lines above). To get around
4034 this problem, you need to buffer things and only output log lines when newlines
4035 are seen. Let's use a slightly better implementation of ``LoggerWriter``:
4036
4037 .. code-block:: python
4038
4039 class BufferingLoggerWriter(LoggerWriter):
4040 def __init__(self, logger, level):
4041 super().__init__(logger, level)
4042 self.buffer = ''
4043
4044 def write(self, message):
4045 if '\n' not in message:
4046 self.buffer += message
4047 else:
4048 parts = message.split('\n')
4049 if self.buffer:
4050 s = self.buffer + parts.pop(0)
4051 self.logger.log(self.level, s)
4052 self.buffer = parts.pop()
4053 for part in parts:
4054 self.logger.log(self.level, part)
4055
4056 This just buffers up stuff until a newline is seen, and then logs complete
4057 lines. With this approach, you get better output:
4058
4059 .. code-block:: text
4060
4061 WARNING:demo:Traceback (most recent call last):
4062 WARNING:demo: File "/home/runner/cookbook-loggerwriter/main.py", line 55, in <module>
4063 WARNING:demo: main()
4064 WARNING:demo: File "/home/runner/cookbook-loggerwriter/main.py", line 52, in main
4065 WARNING:demo: 1/0
4066 WARNING:demo:ZeroDivisionError: division by zero
4067
4068 How to uniformly handle newlines in logging output
4069 --------------------------------------------------
4070
4071 Usually, messages that are logged (say to console or file) consist of a single
4072 line of text. However, sometimes there is a need to handle messages with
4073 multiple lines - whether because a logging format string contains newlines, or
4074 logged data contains newlines. If you want to handle such messages uniformly, so
4075 that each line in the logged message appears uniformly formatted as if it was
4076 logged separately, you can do this using a handler mixin, as in the following
4077 snippet:
4078
4079 .. code-block:: python
4080
4081 # Assume this is in a module mymixins.py
4082 import copy
4083
4084 class MultilineMixin:
4085 def emit(self, record):
4086 s = record.getMessage()
4087 if '\n' not in s:
4088 super().emit(record)
4089 else:
4090 lines = s.splitlines()
4091 rec = copy.copy(record)
4092 rec.args = None
4093 for line in lines:
4094 rec.msg = line
4095 super().emit(rec)
4096
4097 You can use the mixin as in the following script:
4098
4099 .. code-block:: python
4100
4101 import logging
4102
4103 from mymixins import MultilineMixin
4104
4105 logger = logging.getLogger(__name__)
4106
4107 class StreamHandler(MultilineMixin, logging.StreamHandler):
4108 pass
4109
4110 if __name__ == '__main__':
4111 logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-9s %(message)s',
4112 handlers = [StreamHandler()])
4113 logger.debug('Single line')
4114 logger.debug('Multiple lines:\nfool me once ...')
4115 logger.debug('Another single line')
4116 logger.debug('Multiple lines:\n%s', 'fool me ...\ncan\'t get fooled again')
4117
4118 The script, when run, prints something like:
4119
4120 .. code-block:: text
4121
4122 2025-07-02 13:54:47,234 DEBUG Single line
4123 2025-07-02 13:54:47,234 DEBUG Multiple lines:
4124 2025-07-02 13:54:47,234 DEBUG fool me once ...
4125 2025-07-02 13:54:47,234 DEBUG Another single line
4126 2025-07-02 13:54:47,234 DEBUG Multiple lines:
4127 2025-07-02 13:54:47,234 DEBUG fool me ...
4128 2025-07-02 13:54:47,234 DEBUG can't get fooled again
4129
4130 If, on the other hand, you are concerned about `log injection
4131 <https://owasp.org/www-community/attacks/Log_Injection>`_, you can use a
4132 formatter which escapes newlines, as per the following example:
4133
4134 .. code-block:: python
4135
4136 import logging
4137
4138 logger = logging.getLogger(__name__)
4139
4140 class EscapingFormatter(logging.Formatter):
4141 def format(self, record):
4142 s = super().format(record)
4143 return s.replace('\n', r'\n')
4144
4145 if __name__ == '__main__':
4146 h = logging.StreamHandler()
4147 h.setFormatter(EscapingFormatter('%(asctime)s %(levelname)-9s %(message)s'))
4148 logging.basicConfig(level=logging.DEBUG, handlers = [h])
4149 logger.debug('Single line')
4150 logger.debug('Multiple lines:\nfool me once ...')
4151 logger.debug('Another single line')
4152 logger.debug('Multiple lines:\n%s', 'fool me ...\ncan\'t get fooled again')
4153
4154 You can, of course, use whatever escaping scheme makes the most sense for you.
4155 The script, when run, should produce output like this:
4156
4157 .. code-block:: text
4158
4159 2025-07-09 06:47:33,783 DEBUG Single line
4160 2025-07-09 06:47:33,783 DEBUG Multiple lines:\nfool me once ...
4161 2025-07-09 06:47:33,783 DEBUG Another single line
4162 2025-07-09 06:47:33,783 DEBUG Multiple lines:\nfool me ...\ncan't get fooled again
4163
4164 Escaping behaviour can't be the stdlib default , as it would break backwards
4165 compatibility.
4166
4167 .. patterns-to-avoid:
4168
4169 Patterns to avoid
4170 -----------------
4171
4172 Although the preceding sections have described ways of doing things you might
4173 need to do or deal with, it is worth mentioning some usage patterns which are
4174 *unhelpful*, and which should therefore be avoided in most cases. The following
4175 sections are in no particular order.
4176
4177 Opening the same log file multiple times
4178 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4179
4180 On Windows, you will generally not be able to open the same file multiple times
4181 as this will lead to a "file is in use by another process" error. However, on
4182 POSIX platforms you'll not get any errors if you open the same file multiple
4183 times. This could be done accidentally, for example by:
4184
4185 * Adding a file handler more than once which references the same file (e.g. by
4186 a copy/paste/forget-to-change error).
4187
4188 * Opening two files that look different, as they have different names, but are
4189 the same because one is a symbolic link to the other.
4190
4191 * Forking a process, following which both parent and child have a reference to
4192 the same file. This might be through use of the :mod:`multiprocessing` module,
4193 for example.
4194
4195 Opening a file multiple times might *appear* to work most of the time, but can
4196 lead to a number of problems in practice:
4197
4198 * Logging output can be garbled because multiple threads or processes try to
4199 write to the same file. Although logging guards against concurrent use of the
4200 same handler instance by multiple threads, there is no such protection if
4201 concurrent writes are attempted by two different threads using two different
4202 handler instances which happen to point to the same file.
4203
4204 * An attempt to delete a file (e.g. during file rotation) silently fails,
4205 because there is another reference pointing to it. This can lead to confusion
4206 and wasted debugging time - log entries end up in unexpected places, or are
4207 lost altogether. Or a file that was supposed to be moved remains in place,
4208 and grows in size unexpectedly despite size-based rotation being supposedly
4209 in place.
4210
4211 Use the techniques outlined in :ref:`multiple-processes` to circumvent such
4212 issues.
4213
4214 Using loggers as attributes in a class or passing them as parameters
4215 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4216
4217 While there might be unusual cases where you'll need to do this, in general
4218 there is no point because loggers are singletons. Code can always access a
4219 given logger instance by name using ``logging.getLogger(name)``, so passing
4220 instances around and holding them as instance attributes is pointless. Note
4221 that in other languages such as Java and C#, loggers are often static class
4222 attributes. However, this pattern doesn't make sense in Python, where the
4223 module (and not the class) is the unit of software decomposition.
4224
4225 Adding handlers other than :class:`~logging.NullHandler` to a logger in a library
4226 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4227
4228 Configuring logging by adding handlers, formatters and filters is the
4229 responsibility of the application developer, not the library developer. If you
4230 are maintaining a library, ensure that you don't add handlers to any of your
4231 loggers other than a :class:`~logging.NullHandler` instance.
4232
4233 Creating a lot of loggers
4234 ^^^^^^^^^^^^^^^^^^^^^^^^^
4235
4236 Loggers are singletons that are never freed during a script execution, and so
4237 creating lots of loggers will use up memory which can't then be freed. Rather
4238 than create a logger per e.g. file processed or network connection made, use
4239 the :ref:`existing mechanisms <context-info>` for passing contextual
4240 information into your logs and restrict the loggers created to those describing
4241 areas within your application (generally modules, but occasionally slightly
4242 more fine-grained than that).
4243
4244 .. _cookbook-ref-links:
4245
4246 Other resources
4247 ---------------
4248
4249 .. seealso::
4250
4251 Module :mod:`logging`
4252 API reference for the logging module.
4253
4254 Module :mod:`logging.config`
4255 Configuration API for the logging module.
4256
4257 Module :mod:`logging.handlers`
4258 Useful handlers included with the logging module.
4259
4260 :ref:`Basic Tutorial <logging-basic-tutorial>`
4261
4262 :ref:`Advanced Tutorial <logging-advanced-tutorial>`