blob: 4956aa0dd957bc1cf58758fdeaf9b057af9ba218 [file] [log] [blame]
Vinay Sajipc63619b2010-12-19 12:56:57 +00001.. _logging-cookbook:
2
3================
4Logging Cookbook
5================
6
7:Author: Vinay Sajip <vinay_sajip at red-dove dot com>
8
Georg Brandl375aec22011-01-15 17:03:02 +00009This page contains a number of recipes related to logging, which have been found
10useful in the past.
Vinay Sajipc63619b2010-12-19 12:56:57 +000011
Vinay Sajipc63619b2010-12-19 12:56:57 +000012.. currentmodule:: logging
13
14Using logging in multiple modules
15---------------------------------
16
Vinay Sajip1397ce12010-12-24 12:03:48 +000017Multiple calls to ``logging.getLogger('someLogger')`` return a reference to the
18same logger object. This is true not only within the same module, but also
19across modules as long as it is in the same Python interpreter process. It is
20true for references to the same object; additionally, application code can
21define and configure a parent logger in one module and create (but not
22configure) a child logger in a separate module, and all logger calls to the
23child will pass up to the parent. Here is a main module::
Vinay Sajipc63619b2010-12-19 12:56:57 +000024
25 import logging
26 import auxiliary_module
27
28 # create logger with 'spam_application'
29 logger = logging.getLogger('spam_application')
30 logger.setLevel(logging.DEBUG)
31 # create file handler which logs even debug messages
32 fh = logging.FileHandler('spam.log')
33 fh.setLevel(logging.DEBUG)
34 # create console handler with a higher log level
35 ch = logging.StreamHandler()
36 ch.setLevel(logging.ERROR)
37 # create formatter and add it to the handlers
38 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
39 fh.setFormatter(formatter)
40 ch.setFormatter(formatter)
41 # add the handlers to the logger
42 logger.addHandler(fh)
43 logger.addHandler(ch)
44
45 logger.info('creating an instance of auxiliary_module.Auxiliary')
46 a = auxiliary_module.Auxiliary()
47 logger.info('created an instance of auxiliary_module.Auxiliary')
48 logger.info('calling auxiliary_module.Auxiliary.do_something')
49 a.do_something()
50 logger.info('finished auxiliary_module.Auxiliary.do_something')
51 logger.info('calling auxiliary_module.some_function()')
52 auxiliary_module.some_function()
53 logger.info('done with auxiliary_module.some_function()')
54
55Here is the auxiliary module::
56
57 import logging
58
59 # create logger
60 module_logger = logging.getLogger('spam_application.auxiliary')
61
62 class Auxiliary:
63 def __init__(self):
64 self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
65 self.logger.info('creating an instance of Auxiliary')
Serhiy Storchakadba90392016-05-10 12:01:23 +030066
Vinay Sajipc63619b2010-12-19 12:56:57 +000067 def do_something(self):
68 self.logger.info('doing something')
69 a = 1 + 1
70 self.logger.info('done doing something')
71
72 def some_function():
73 module_logger.info('received a call to "some_function"')
74
Serhiy Storchaka46936d52018-04-08 19:18:04 +030075The output looks like this:
76
77.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +000078
79 2005-03-23 23:47:11,663 - spam_application - INFO -
80 creating an instance of auxiliary_module.Auxiliary
81 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
82 creating an instance of Auxiliary
83 2005-03-23 23:47:11,665 - spam_application - INFO -
84 created an instance of auxiliary_module.Auxiliary
85 2005-03-23 23:47:11,668 - spam_application - INFO -
86 calling auxiliary_module.Auxiliary.do_something
87 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
88 doing something
89 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
90 done doing something
91 2005-03-23 23:47:11,670 - spam_application - INFO -
92 finished auxiliary_module.Auxiliary.do_something
93 2005-03-23 23:47:11,671 - spam_application - INFO -
94 calling auxiliary_module.some_function()
95 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
96 received a call to 'some_function'
97 2005-03-23 23:47:11,673 - spam_application - INFO -
98 done with auxiliary_module.some_function()
99
Vinay Sajipe10d3702016-02-20 19:02:46 +0000100Logging from multiple threads
101-----------------------------
102
103Logging from multiple threads requires no special effort. The following example
Berker Peksag563c9492016-03-20 12:50:56 +0200104shows logging from the main (initial) thread and another thread::
Vinay Sajipe10d3702016-02-20 19:02:46 +0000105
106 import logging
107 import threading
108 import time
109
110 def worker(arg):
111 while not arg['stop']:
112 logging.debug('Hi from myfunc')
113 time.sleep(0.5)
114
115 def main():
116 logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
117 info = {'stop': False}
118 thread = threading.Thread(target=worker, args=(info,))
119 thread.start()
120 while True:
121 try:
122 logging.debug('Hello from main')
123 time.sleep(0.75)
124 except KeyboardInterrupt:
125 info['stop'] = True
126 break
127 thread.join()
128
129 if __name__ == '__main__':
130 main()
131
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300132When run, the script should print something like the following:
133
134.. code-block:: none
Vinay Sajipe10d3702016-02-20 19:02:46 +0000135
136 0 Thread-1 Hi from myfunc
137 3 MainThread Hello from main
138 505 Thread-1 Hi from myfunc
139 755 MainThread Hello from main
140 1007 Thread-1 Hi from myfunc
141 1507 MainThread Hello from main
142 1508 Thread-1 Hi from myfunc
143 2010 Thread-1 Hi from myfunc
144 2258 MainThread Hello from main
145 2512 Thread-1 Hi from myfunc
146 3009 MainThread Hello from main
147 3013 Thread-1 Hi from myfunc
148 3515 Thread-1 Hi from myfunc
149 3761 MainThread Hello from main
150 4017 Thread-1 Hi from myfunc
151 4513 MainThread Hello from main
152 4518 Thread-1 Hi from myfunc
153
154This shows the logging output interspersed as one might expect. This approach
155works for more threads than shown here, of course.
156
Vinay Sajipc63619b2010-12-19 12:56:57 +0000157Multiple handlers and formatters
158--------------------------------
159
Vinay Sajip67f39772013-08-17 00:39:42 +0100160Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has no
161minimum or maximum quota for the number of handlers you may add. Sometimes it
162will be beneficial for an application to log all messages of all severities to a
163text file while simultaneously logging errors or above to the console. To set
164this up, simply configure the appropriate handlers. The logging calls in the
Vinay Sajipc63619b2010-12-19 12:56:57 +0000165application code will remain unchanged. Here is a slight modification to the
166previous simple module-based configuration example::
167
168 import logging
169
170 logger = logging.getLogger('simple_example')
171 logger.setLevel(logging.DEBUG)
172 # create file handler which logs even debug messages
173 fh = logging.FileHandler('spam.log')
174 fh.setLevel(logging.DEBUG)
175 # create console handler with a higher log level
176 ch = logging.StreamHandler()
177 ch.setLevel(logging.ERROR)
178 # create formatter and add it to the handlers
179 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
180 ch.setFormatter(formatter)
181 fh.setFormatter(formatter)
182 # add the handlers to logger
183 logger.addHandler(ch)
184 logger.addHandler(fh)
185
186 # 'application' code
187 logger.debug('debug message')
188 logger.info('info message')
yuji38kwmtcda73a52019-01-23 16:27:13 +0900189 logger.warning('warn message')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000190 logger.error('error message')
191 logger.critical('critical message')
192
193Notice that the 'application' code does not care about multiple handlers. All
194that changed was the addition and configuration of a new handler named *fh*.
195
196The ability to create new handlers with higher- or lower-severity filters can be
197very helpful when writing and testing an application. Instead of using many
198``print`` statements for debugging, use ``logger.debug``: Unlike the print
199statements, which you will have to delete or comment out later, the logger.debug
200statements can remain intact in the source code and remain dormant until you
201need them again. At that time, the only change that needs to happen is to
202modify the severity level of the logger and/or handler to debug.
203
204.. _multiple-destinations:
205
206Logging to multiple destinations
207--------------------------------
208
209Let's say you want to log to console and file with different message formats and
210in differing circumstances. Say you want to log messages with levels of DEBUG
211and higher to file, and those messages at level INFO and higher to the console.
212Let's also assume that the file should contain timestamps, but the console
213messages should not. Here's how you can achieve this::
214
215 import logging
216
217 # set up logging to file - see previous section for more details
218 logging.basicConfig(level=logging.DEBUG,
219 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
220 datefmt='%m-%d %H:%M',
221 filename='/temp/myapp.log',
222 filemode='w')
223 # define a Handler which writes INFO messages or higher to the sys.stderr
224 console = logging.StreamHandler()
225 console.setLevel(logging.INFO)
226 # set a format which is simpler for console use
227 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
228 # tell the handler to use this format
229 console.setFormatter(formatter)
230 # add the handler to the root logger
231 logging.getLogger('').addHandler(console)
232
233 # Now, we can log to the root logger, or any other logger. First the root...
234 logging.info('Jackdaws love my big sphinx of quartz.')
235
236 # Now, define a couple of other loggers which might represent areas in your
237 # application:
238
239 logger1 = logging.getLogger('myapp.area1')
240 logger2 = logging.getLogger('myapp.area2')
241
242 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
243 logger1.info('How quickly daft jumping zebras vex.')
244 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
245 logger2.error('The five boxing wizards jump quickly.')
246
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300247When you run this, on the console you will see
248
249.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000250
251 root : INFO Jackdaws love my big sphinx of quartz.
252 myapp.area1 : INFO How quickly daft jumping zebras vex.
253 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
254 myapp.area2 : ERROR The five boxing wizards jump quickly.
255
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300256and in the file you will see something like
257
258.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000259
260 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
261 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
262 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
263 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
264 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
265
266As you can see, the DEBUG message only shows up in the file. The other messages
267are sent to both destinations.
268
269This example uses console and file handlers, but you can use any number and
270combination of handlers you choose.
271
272
273Configuration server example
274----------------------------
275
276Here is an example of a module using the logging configuration server::
277
278 import logging
279 import logging.config
280 import time
281 import os
282
283 # read initial config file
284 logging.config.fileConfig('logging.conf')
285
286 # create and start listener on port 9999
287 t = logging.config.listen(9999)
288 t.start()
289
290 logger = logging.getLogger('simpleExample')
291
292 try:
293 # loop through logging calls to see the difference
294 # new configurations make, until Ctrl+C is pressed
295 while True:
296 logger.debug('debug message')
297 logger.info('info message')
yuji38kwmtcda73a52019-01-23 16:27:13 +0900298 logger.warning('warn message')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000299 logger.error('error message')
300 logger.critical('critical message')
301 time.sleep(5)
302 except KeyboardInterrupt:
303 # cleanup
304 logging.config.stopListening()
305 t.join()
306
307And here is a script that takes a filename and sends that file to the server,
308properly preceded with the binary-encoded length, as the new logging
309configuration::
310
311 #!/usr/bin/env python
312 import socket, sys, struct
313
Vinay Sajip689b68a2010-12-22 15:04:15 +0000314 with open(sys.argv[1], 'rb') as f:
315 data_to_send = f.read()
Vinay Sajipc63619b2010-12-19 12:56:57 +0000316
317 HOST = 'localhost'
318 PORT = 9999
319 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
320 print('connecting...')
321 s.connect((HOST, PORT))
322 print('sending config...')
323 s.send(struct.pack('>L', len(data_to_send)))
324 s.send(data_to_send)
325 s.close()
326 print('complete')
327
328
329Dealing with handlers that block
330--------------------------------
331
332.. currentmodule:: logging.handlers
333
334Sometimes you have to get your logging handlers to do their work without
Vinay Sajip6b883a22012-02-27 11:02:45 +0000335blocking the thread you're logging from. This is common in Web applications,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000336though of course it also occurs in other scenarios.
337
338A common culprit which demonstrates sluggish behaviour is the
339:class:`SMTPHandler`: sending emails can take a long time, for a
Vinay Sajip6b883a22012-02-27 11:02:45 +0000340number of reasons outside the developer's control (for example, a poorly
Vinay Sajipc63619b2010-12-19 12:56:57 +0000341performing mail or network infrastructure). But almost any network-based
342handler can block: Even a :class:`SocketHandler` operation may do a
343DNS query under the hood which is too slow (and this query can be deep in the
344socket library code, below the Python layer, and outside your control).
345
346One solution is to use a two-part approach. For the first part, attach only a
347:class:`QueueHandler` to those loggers which are accessed from
348performance-critical threads. They simply write to their queue, which can be
349sized to a large enough capacity or initialized with no upper bound to their
350size. The write to the queue will typically be accepted quickly, though you
Georg Brandl375aec22011-01-15 17:03:02 +0000351will probably need to catch the :exc:`queue.Full` exception as a precaution
Vinay Sajipc63619b2010-12-19 12:56:57 +0000352in your code. If you are a library developer who has performance-critical
353threads in their code, be sure to document this (together with a suggestion to
354attach only ``QueueHandlers`` to your loggers) for the benefit of other
355developers who will use your code.
356
357The second part of the solution is :class:`QueueListener`, which has been
358designed as the counterpart to :class:`QueueHandler`. A
Vinay Sajip6b883a22012-02-27 11:02:45 +0000359:class:`QueueListener` is very simple: it's passed a queue and some handlers,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000360and it fires up an internal thread which listens to its queue for LogRecords
361sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
362matter). The ``LogRecords`` are removed from the queue and passed to the
363handlers for processing.
364
365The advantage of having a separate :class:`QueueListener` class is that you
366can use the same instance to service multiple ``QueueHandlers``. This is more
367resource-friendly than, say, having threaded versions of the existing handler
368classes, which would eat up one thread per handler for no particular benefit.
369
370An example of using these two classes follows (imports omitted)::
371
Serhiy Storchakadba90392016-05-10 12:01:23 +0300372 que = queue.Queue(-1) # no limit on size
Vinay Sajipc63619b2010-12-19 12:56:57 +0000373 queue_handler = QueueHandler(que)
374 handler = logging.StreamHandler()
375 listener = QueueListener(que, handler)
376 root = logging.getLogger()
377 root.addHandler(queue_handler)
378 formatter = logging.Formatter('%(threadName)s: %(message)s')
379 handler.setFormatter(formatter)
380 listener.start()
381 # The log output will display the thread which generated
382 # the event (the main thread) rather than the internal
383 # thread which monitors the internal queue. This is what
384 # you want to happen.
385 root.warning('Look out!')
386 listener.stop()
387
Martin Panter1050d2d2016-07-26 11:18:21 +0200388which, when run, will produce:
389
390.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000391
392 MainThread: Look out!
393
Vinay Sajip365701a2015-02-09 19:49:00 +0000394.. versionchanged:: 3.5
395 Prior to Python 3.5, the :class:`QueueListener` always passed every message
396 received from the queue to every handler it was initialized with. (This was
397 because it was assumed that level filtering was all done on the other side,
398 where the queue is filled.) From 3.5 onwards, this behaviour can be changed
399 by passing a keyword argument ``respect_handler_level=True`` to the
400 listener's constructor. When this is done, the listener compares the level
401 of each message with the handler's level, and only passes a message to a
402 handler if it's appropriate to do so.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000403
404.. _network-logging:
405
406Sending and receiving logging events across a network
407-----------------------------------------------------
408
409Let's say you want to send logging events across a network, and handle them at
410the receiving end. A simple way of doing this is attaching a
411:class:`SocketHandler` instance to the root logger at the sending end::
412
413 import logging, logging.handlers
414
415 rootLogger = logging.getLogger('')
416 rootLogger.setLevel(logging.DEBUG)
417 socketHandler = logging.handlers.SocketHandler('localhost',
418 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
419 # don't bother with a formatter, since a socket handler sends the event as
420 # an unformatted pickle
421 rootLogger.addHandler(socketHandler)
422
423 # Now, we can log to the root logger, or any other logger. First the root...
424 logging.info('Jackdaws love my big sphinx of quartz.')
425
426 # Now, define a couple of other loggers which might represent areas in your
427 # application:
428
429 logger1 = logging.getLogger('myapp.area1')
430 logger2 = logging.getLogger('myapp.area2')
431
432 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
433 logger1.info('How quickly daft jumping zebras vex.')
434 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
435 logger2.error('The five boxing wizards jump quickly.')
436
437At the receiving end, you can set up a receiver using the :mod:`socketserver`
438module. Here is a basic working example::
439
440 import pickle
441 import logging
442 import logging.handlers
443 import socketserver
444 import struct
445
446
447 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
448 """Handler for a streaming logging request.
449
450 This basically logs the record using whatever logging policy is
451 configured locally.
452 """
453
454 def handle(self):
455 """
456 Handle multiple requests - each expected to be a 4-byte length,
457 followed by the LogRecord in pickle format. Logs the record
458 according to whatever policy is configured locally.
459 """
460 while True:
461 chunk = self.connection.recv(4)
462 if len(chunk) < 4:
463 break
464 slen = struct.unpack('>L', chunk)[0]
465 chunk = self.connection.recv(slen)
466 while len(chunk) < slen:
467 chunk = chunk + self.connection.recv(slen - len(chunk))
468 obj = self.unPickle(chunk)
469 record = logging.makeLogRecord(obj)
470 self.handleLogRecord(record)
471
472 def unPickle(self, data):
473 return pickle.loads(data)
474
475 def handleLogRecord(self, record):
476 # if a name is specified, we use the named logger rather than the one
477 # implied by the record.
478 if self.server.logname is not None:
479 name = self.server.logname
480 else:
481 name = record.name
482 logger = logging.getLogger(name)
483 # N.B. EVERY record gets logged. This is because Logger.handle
484 # is normally called AFTER logger-level filtering. If you want
485 # to do filtering, do it at the client end to save wasting
486 # cycles and network bandwidth!
487 logger.handle(record)
488
489 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
490 """
491 Simple TCP socket-based logging receiver suitable for testing.
492 """
493
Raymond Hettinger4ab532b2014-03-28 16:39:25 -0700494 allow_reuse_address = True
Vinay Sajipc63619b2010-12-19 12:56:57 +0000495
496 def __init__(self, host='localhost',
497 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
498 handler=LogRecordStreamHandler):
499 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
500 self.abort = 0
501 self.timeout = 1
502 self.logname = None
503
504 def serve_until_stopped(self):
505 import select
506 abort = 0
507 while not abort:
508 rd, wr, ex = select.select([self.socket.fileno()],
509 [], [],
510 self.timeout)
511 if rd:
512 self.handle_request()
513 abort = self.abort
514
515 def main():
516 logging.basicConfig(
517 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
518 tcpserver = LogRecordSocketReceiver()
519 print('About to start TCP server...')
520 tcpserver.serve_until_stopped()
521
522 if __name__ == '__main__':
523 main()
524
525First run the server, and then the client. On the client side, nothing is
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300526printed on the console; on the server side, you should see something like:
527
528.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000529
530 About to start TCP server...
531 59 root INFO Jackdaws love my big sphinx of quartz.
532 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
533 69 myapp.area1 INFO How quickly daft jumping zebras vex.
534 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
535 69 myapp.area2 ERROR The five boxing wizards jump quickly.
536
537Note that there are some security issues with pickle in some scenarios. If
538these affect you, you can use an alternative serialization scheme by overriding
Vinay Sajip67f39772013-08-17 00:39:42 +0100539the :meth:`~handlers.SocketHandler.makePickle` method and implementing your
540alternative there, as well as adapting the above script to use your alternative
541serialization.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000542
543
544.. _context-info:
545
546Adding contextual information to your logging output
547----------------------------------------------------
548
549Sometimes you want logging output to contain contextual information in
550addition to the parameters passed to the logging call. For example, in a
551networked application, it may be desirable to log client-specific information
552in the log (e.g. remote client's username, or IP address). Although you could
553use the *extra* parameter to achieve this, it's not always convenient to pass
554the information in this way. While it might be tempting to create
555:class:`Logger` instances on a per-connection basis, this is not a good idea
556because these instances are not garbage collected. While this is not a problem
557in practice, when the number of :class:`Logger` instances is dependent on the
558level of granularity you want to use in logging an application, it could
559be hard to manage if the number of :class:`Logger` instances becomes
560effectively unbounded.
561
562
563Using LoggerAdapters to impart contextual information
564^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
565
566An easy way in which you can pass contextual information to be output along
567with logging event information is to use the :class:`LoggerAdapter` class.
568This class is designed to look like a :class:`Logger`, so that you can call
569:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
570:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
571same signatures as their counterparts in :class:`Logger`, so you can use the
572two types of instances interchangeably.
573
574When you create an instance of :class:`LoggerAdapter`, you pass it a
575:class:`Logger` instance and a dict-like object which contains your contextual
576information. When you call one of the logging methods on an instance of
577:class:`LoggerAdapter`, it delegates the call to the underlying instance of
578:class:`Logger` passed to its constructor, and arranges to pass the contextual
579information in the delegated call. Here's a snippet from the code of
580:class:`LoggerAdapter`::
581
582 def debug(self, msg, *args, **kwargs):
583 """
584 Delegate a debug call to the underlying logger, after adding
585 contextual information from this adapter instance.
586 """
587 msg, kwargs = self.process(msg, kwargs)
588 self.logger.debug(msg, *args, **kwargs)
589
Vinay Sajip67f39772013-08-17 00:39:42 +0100590The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the
591contextual information is added to the logging output. It's passed the message
592and keyword arguments of the logging call, and it passes back (potentially)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000593modified versions of these to use in the call to the underlying logger. The
594default implementation of this method leaves the message alone, but inserts
595an 'extra' key in the keyword argument whose value is the dict-like object
596passed to the constructor. Of course, if you had passed an 'extra' keyword
597argument in the call to the adapter, it will be silently overwritten.
598
599The advantage of using 'extra' is that the values in the dict-like object are
600merged into the :class:`LogRecord` instance's __dict__, allowing you to use
601customized strings with your :class:`Formatter` instances which know about
602the keys of the dict-like object. If you need a different method, e.g. if you
603want to prepend or append the contextual information to the message string,
Vinay Sajip67f39772013-08-17 00:39:42 +0100604you just need to subclass :class:`LoggerAdapter` and override
605:meth:`~LoggerAdapter.process` to do what you need. Here is a simple example::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000606
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100607 class CustomAdapter(logging.LoggerAdapter):
608 """
609 This example adapter expects the passed in dict-like object to have a
610 'connid' key, whose value in brackets is prepended to the log message.
611 """
612 def process(self, msg, kwargs):
613 return '[%s] %s' % (self.extra['connid'], msg), kwargs
Vinay Sajipc63619b2010-12-19 12:56:57 +0000614
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100615which you can use like this::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000616
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100617 logger = logging.getLogger(__name__)
618 adapter = CustomAdapter(logger, {'connid': some_conn_id})
Vinay Sajipc63619b2010-12-19 12:56:57 +0000619
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100620Then any events that you log to the adapter will have the value of
621``some_conn_id`` prepended to the log messages.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000622
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100623Using objects other than dicts to pass contextual information
624~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vinay Sajipc63619b2010-12-19 12:56:57 +0000625
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100626You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could
627pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so
628that it looks like a dict to logging. This would be useful if you want to
629generate values dynamically (whereas the values in a dict would be constant).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000630
631
632.. _filters-contextual:
633
634Using Filters to impart contextual information
635^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
636
637You can also add contextual information to log output using a user-defined
638:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
639passed to them, including adding additional attributes which can then be output
640using a suitable format string, or if needed a custom :class:`Formatter`.
641
642For example in a web application, the request being processed (or at least,
643the interesting parts of it) can be stored in a threadlocal
644(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
645add, say, information from the request - say, the remote IP address and remote
646user's username - to the ``LogRecord``, using the attribute names 'ip' and
647'user' as in the ``LoggerAdapter`` example above. In that case, the same format
648string can be used to get similar output to that shown above. Here's an example
649script::
650
651 import logging
652 from random import choice
653
654 class ContextFilter(logging.Filter):
655 """
656 This is a filter which injects contextual information into the log.
657
658 Rather than use actual contextual information, we just use random
659 data in this demo.
660 """
661
662 USERS = ['jim', 'fred', 'sheila']
663 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
664
665 def filter(self, record):
666
667 record.ip = choice(ContextFilter.IPS)
668 record.user = choice(ContextFilter.USERS)
669 return True
670
671 if __name__ == '__main__':
Serhiy Storchakadba90392016-05-10 12:01:23 +0300672 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
673 logging.basicConfig(level=logging.DEBUG,
674 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
675 a1 = logging.getLogger('a.b.c')
676 a2 = logging.getLogger('d.e.f')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000677
Serhiy Storchakadba90392016-05-10 12:01:23 +0300678 f = ContextFilter()
679 a1.addFilter(f)
680 a2.addFilter(f)
681 a1.debug('A debug message')
682 a1.info('An info message with %s', 'some parameters')
683 for x in range(10):
684 lvl = choice(levels)
685 lvlname = logging.getLevelName(lvl)
686 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000687
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300688which, when run, produces something like:
689
690.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000691
692 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
693 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
694 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
695 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
696 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
697 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
698 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
699 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
700 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
701 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
702 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
703 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
704
705
706.. _multiple-processes:
707
708Logging to a single file from multiple processes
709------------------------------------------------
710
711Although logging is thread-safe, and logging to a single file from multiple
712threads in a single process *is* supported, logging to a single file from
713*multiple processes* is *not* supported, because there is no standard way to
714serialize access to a single file across multiple processes in Python. If you
715need to log to a single file from multiple processes, one way of doing this is
Vinay Sajip67f39772013-08-17 00:39:42 +0100716to have all the processes log to a :class:`~handlers.SocketHandler`, and have a
717separate process which implements a socket server which reads from the socket
718and logs to file. (If you prefer, you can dedicate one thread in one of the
719existing processes to perform this function.)
720:ref:`This section <network-logging>` documents this approach in more detail and
721includes a working socket receiver which can be used as a starting point for you
722to adapt in your own applications.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000723
Cheryl Sabella11c4eaa2018-10-02 12:35:05 -0400724You could also write your own handler which uses the :class:`~multiprocessing.Lock`
725class from the :mod:`multiprocessing` module to serialize access to the
Vinay Sajip67f39772013-08-17 00:39:42 +0100726file from your processes. The existing :class:`FileHandler` and subclasses do
727not make use of :mod:`multiprocessing` at present, though they may do so in the
728future. Note that at present, the :mod:`multiprocessing` module does not provide
Vinay Sajipc63619b2010-12-19 12:56:57 +0000729working lock functionality on all platforms (see
Georg Brandle73778c2014-10-29 08:36:35 +0100730https://bugs.python.org/issue3770).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000731
732.. currentmodule:: logging.handlers
733
734Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
735all logging events to one of the processes in your multi-process application.
736The following example script demonstrates how you can do this; in the example
737a separate listener process listens for events sent by other processes and logs
738them according to its own logging configuration. Although the example only
739demonstrates one way of doing it (for example, you may want to use a listener
Georg Brandl7a0afd32011-02-07 15:44:27 +0000740thread rather than a separate listener process -- the implementation would be
Vinay Sajipc63619b2010-12-19 12:56:57 +0000741analogous) it does allow for completely different logging configurations for
742the listener and the other processes in your application, and can be used as
743the basis for code meeting your own specific requirements::
744
745 # You'll need these imports in your own code
746 import logging
747 import logging.handlers
748 import multiprocessing
749
750 # Next two import lines for this demo only
751 from random import choice, random
752 import time
753
754 #
755 # Because you'll want to define the logging configurations for listener and workers, the
756 # listener and worker process functions take a configurer parameter which is a callable
757 # for configuring logging for that process. These functions are also passed the queue,
758 # which they use for communication.
759 #
760 # In practice, you can configure the listener however you want, but note that in this
761 # simple example, the listener does not apply level or filter logic to received records.
Georg Brandl7a0afd32011-02-07 15:44:27 +0000762 # In practice, you would probably want to do this logic in the worker processes, to avoid
Vinay Sajipc63619b2010-12-19 12:56:57 +0000763 # sending events which would be filtered out between processes.
764 #
765 # The size of the rotated files is made small so you can see the results easily.
766 def listener_configurer():
767 root = logging.getLogger()
Raymond Hettingerb34705f2011-06-26 15:29:06 +0200768 h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000769 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
770 h.setFormatter(f)
771 root.addHandler(h)
772
773 # This is the listener process top-level loop: wait for logging events
774 # (LogRecords)on the queue and handle them, quit when you get a None for a
775 # LogRecord.
776 def listener_process(queue, configurer):
777 configurer()
778 while True:
779 try:
780 record = queue.get()
Serhiy Storchakadba90392016-05-10 12:01:23 +0300781 if record is None: # We send this as a sentinel to tell the listener to quit.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000782 break
783 logger = logging.getLogger(record.name)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300784 logger.handle(record) # No level or filter logic applied - just do it!
Andrew Svetlov47395612012-11-02 22:07:26 +0200785 except Exception:
Vinay Sajipc63619b2010-12-19 12:56:57 +0000786 import sys, traceback
Vinay Sajip6b883a22012-02-27 11:02:45 +0000787 print('Whoops! Problem:', file=sys.stderr)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000788 traceback.print_exc(file=sys.stderr)
789
790 # Arrays used for random selections in this demo
791
792 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
793 logging.ERROR, logging.CRITICAL]
794
795 LOGGERS = ['a.b.c', 'd.e.f']
796
797 MESSAGES = [
798 'Random message #1',
799 'Random message #2',
800 'Random message #3',
801 ]
802
803 # The worker configuration is done at the start of the worker process run.
804 # Note that on Windows you can't rely on fork semantics, so each process
805 # will run the logging configuration code when it starts.
806 def worker_configurer(queue):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300807 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
Vinay Sajipc63619b2010-12-19 12:56:57 +0000808 root = logging.getLogger()
809 root.addHandler(h)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300810 # send all messages, for demo; no other level or filter logic applied.
811 root.setLevel(logging.DEBUG)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000812
813 # This is the worker process top-level loop, which just logs ten events with
814 # random intervening delays before terminating.
815 # The print messages are just so you know it's doing something!
816 def worker_process(queue, configurer):
817 configurer(queue)
818 name = multiprocessing.current_process().name
819 print('Worker started: %s' % name)
820 for i in range(10):
821 time.sleep(random())
822 logger = logging.getLogger(choice(LOGGERS))
823 level = choice(LEVELS)
824 message = choice(MESSAGES)
825 logger.log(level, message)
826 print('Worker finished: %s' % name)
827
828 # Here's where the demo gets orchestrated. Create the queue, create and start
829 # the listener, create ten workers and start them, wait for them to finish,
830 # then send a None to the queue to tell the listener to finish.
831 def main():
832 queue = multiprocessing.Queue(-1)
833 listener = multiprocessing.Process(target=listener_process,
834 args=(queue, listener_configurer))
835 listener.start()
836 workers = []
837 for i in range(10):
838 worker = multiprocessing.Process(target=worker_process,
Serhiy Storchakadba90392016-05-10 12:01:23 +0300839 args=(queue, worker_configurer))
Vinay Sajipc63619b2010-12-19 12:56:57 +0000840 workers.append(worker)
841 worker.start()
842 for w in workers:
843 w.join()
844 queue.put_nowait(None)
845 listener.join()
846
847 if __name__ == '__main__':
848 main()
849
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000850A variant of the above script keeps the logging in the main process, in a
851separate thread::
852
853 import logging
854 import logging.config
855 import logging.handlers
856 from multiprocessing import Process, Queue
857 import random
858 import threading
859 import time
860
861 def logger_thread(q):
862 while True:
863 record = q.get()
864 if record is None:
865 break
866 logger = logging.getLogger(record.name)
867 logger.handle(record)
868
869
870 def worker_process(q):
871 qh = logging.handlers.QueueHandler(q)
872 root = logging.getLogger()
873 root.setLevel(logging.DEBUG)
874 root.addHandler(qh)
875 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
876 logging.CRITICAL]
877 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
878 'spam', 'spam.ham', 'spam.ham.eggs']
879 for i in range(100):
880 lvl = random.choice(levels)
881 logger = logging.getLogger(random.choice(loggers))
882 logger.log(lvl, 'Message no. %d', i)
883
884 if __name__ == '__main__':
885 q = Queue()
886 d = {
887 'version': 1,
888 'formatters': {
889 'detailed': {
890 'class': 'logging.Formatter',
891 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
892 }
893 },
894 'handlers': {
895 'console': {
896 'class': 'logging.StreamHandler',
897 'level': 'INFO',
898 },
899 'file': {
900 'class': 'logging.FileHandler',
901 'filename': 'mplog.log',
902 'mode': 'w',
903 'formatter': 'detailed',
904 },
905 'foofile': {
906 'class': 'logging.FileHandler',
907 'filename': 'mplog-foo.log',
908 'mode': 'w',
909 'formatter': 'detailed',
910 },
911 'errors': {
912 'class': 'logging.FileHandler',
913 'filename': 'mplog-errors.log',
914 'mode': 'w',
915 'level': 'ERROR',
916 'formatter': 'detailed',
917 },
918 },
919 'loggers': {
920 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200921 'handlers': ['foofile']
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000922 }
923 },
924 'root': {
925 'level': 'DEBUG',
926 'handlers': ['console', 'file', 'errors']
927 },
928 }
929 workers = []
930 for i in range(5):
931 wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
932 workers.append(wp)
933 wp.start()
934 logging.config.dictConfig(d)
935 lp = threading.Thread(target=logger_thread, args=(q,))
936 lp.start()
937 # At this point, the main process could do some useful work of its own
938 # Once it's done that, it can wait for the workers to terminate...
939 for wp in workers:
940 wp.join()
941 # And now tell the logging thread to finish up, too
942 q.put(None)
943 lp.join()
944
945This variant shows how you can e.g. apply configuration for particular loggers
946- e.g. the ``foo`` logger has a special handler which stores all events in the
947``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging
948machinery in the main process (even though the logging events are generated in
949the worker processes) to direct the messages to the appropriate destinations.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000950
951Using file rotation
952-------------------
953
954.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
jimmy4f29f3c2017-12-13 13:37:51 +0100955.. (see <https://pymotw.com/3/logging/>)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000956
957Sometimes you want to let a log file grow to a certain size, then open a new
958file and log to that. You may want to keep a certain number of these files, and
959when that many files have been created, rotate the files so that the number of
Georg Brandl7a0afd32011-02-07 15:44:27 +0000960files and the size of the files both remain bounded. For this usage pattern, the
Vinay Sajip67f39772013-08-17 00:39:42 +0100961logging package provides a :class:`~handlers.RotatingFileHandler`::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000962
963 import glob
964 import logging
965 import logging.handlers
966
967 LOG_FILENAME = 'logging_rotatingfile_example.out'
968
969 # Set up a specific logger with our desired output level
970 my_logger = logging.getLogger('MyLogger')
971 my_logger.setLevel(logging.DEBUG)
972
973 # Add the log message handler to the logger
974 handler = logging.handlers.RotatingFileHandler(
975 LOG_FILENAME, maxBytes=20, backupCount=5)
976
977 my_logger.addHandler(handler)
978
979 # Log some messages
980 for i in range(20):
981 my_logger.debug('i = %d' % i)
982
983 # See what files are created
984 logfiles = glob.glob('%s*' % LOG_FILENAME)
985
986 for filename in logfiles:
987 print(filename)
988
989The result should be 6 separate files, each with part of the log history for the
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300990application:
991
992.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000993
994 logging_rotatingfile_example.out
995 logging_rotatingfile_example.out.1
996 logging_rotatingfile_example.out.2
997 logging_rotatingfile_example.out.3
998 logging_rotatingfile_example.out.4
999 logging_rotatingfile_example.out.5
1000
1001The most current file is always :file:`logging_rotatingfile_example.out`,
1002and each time it reaches the size limit it is renamed with the suffix
1003``.1``. Each of the existing backup files is renamed to increment the suffix
1004(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1005
Ezio Melottie130a522011-10-19 10:58:56 +03001006Obviously this example sets the log length much too small as an extreme
Vinay Sajipc63619b2010-12-19 12:56:57 +00001007example. You would want to set *maxBytes* to an appropriate value.
1008
Vinay Sajip6b883a22012-02-27 11:02:45 +00001009.. _format-styles:
1010
1011Use of alternative formatting styles
1012------------------------------------
1013
1014When logging was added to the Python standard library, the only way of
1015formatting messages with variable content was to use the %-formatting
1016method. Since then, Python has gained two new formatting approaches:
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001017:class:`string.Template` (added in Python 2.4) and :meth:`str.format`
1018(added in Python 2.6).
Vinay Sajip6b883a22012-02-27 11:02:45 +00001019
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001020Logging (as of 3.2) provides improved support for these two additional
1021formatting styles. The :class:`Formatter` class been enhanced to take an
1022additional, optional keyword parameter named ``style``. This defaults to
1023``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond
Vinay Sajip6b883a22012-02-27 11:02:45 +00001024to the other two formatting styles. Backwards compatibility is maintained by
1025default (as you would expect), but by explicitly specifying a style parameter,
1026you get the ability to specify format strings which work with
1027:meth:`str.format` or :class:`string.Template`. Here's an example console
1028session to show the possibilities:
1029
1030.. code-block:: pycon
1031
1032 >>> import logging
1033 >>> root = logging.getLogger()
1034 >>> root.setLevel(logging.DEBUG)
1035 >>> handler = logging.StreamHandler()
1036 >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
1037 ... style='{')
1038 >>> handler.setFormatter(bf)
1039 >>> root.addHandler(handler)
1040 >>> logger = logging.getLogger('foo.bar')
1041 >>> logger.debug('This is a DEBUG message')
1042 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message
1043 >>> logger.critical('This is a CRITICAL message')
1044 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
1045 >>> df = logging.Formatter('$asctime $name ${levelname} $message',
1046 ... style='$')
1047 >>> handler.setFormatter(df)
1048 >>> logger.debug('This is a DEBUG message')
1049 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
1050 >>> logger.critical('This is a CRITICAL message')
1051 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
1052 >>>
1053
1054Note that the formatting of logging messages for final output to logs is
1055completely independent of how an individual logging message is constructed.
1056That can still use %-formatting, as shown here::
1057
1058 >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
1059 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
1060 >>>
1061
1062Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take
1063positional parameters for the actual logging message itself, with keyword
1064parameters used only for determining options for how to handle the actual
1065logging call (e.g. the ``exc_info`` keyword parameter to indicate that
1066traceback information should be logged, or the ``extra`` keyword parameter
1067to indicate additional contextual information to be added to the log). So
1068you cannot directly make logging calls using :meth:`str.format` or
1069:class:`string.Template` syntax, because internally the logging package
1070uses %-formatting to merge the format string and the variable arguments.
Brett Cannona3110a02017-08-18 10:00:31 -07001071There would be no changing this while preserving backward compatibility, since
Vinay Sajip6b883a22012-02-27 11:02:45 +00001072all logging calls which are out there in existing code will be using %-format
1073strings.
1074
1075There is, however, a way that you can use {}- and $- formatting to construct
1076your individual log messages. Recall that for a message you can use an
1077arbitrary object as a message format string, and that the logging package will
1078call ``str()`` on that object to get the actual format string. Consider the
1079following two classes::
1080
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001081 class BraceMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001082 def __init__(self, fmt, *args, **kwargs):
1083 self.fmt = fmt
1084 self.args = args
1085 self.kwargs = kwargs
1086
1087 def __str__(self):
1088 return self.fmt.format(*self.args, **self.kwargs)
1089
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001090 class DollarMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001091 def __init__(self, fmt, **kwargs):
1092 self.fmt = fmt
1093 self.kwargs = kwargs
1094
1095 def __str__(self):
1096 from string import Template
1097 return Template(self.fmt).substitute(**self.kwargs)
1098
1099Either of these can be used in place of a format string, to allow {}- or
1100$-formatting to be used to build the actual "message" part which appears in the
1101formatted log output in place of "%(message)s" or "{message}" or "$message".
1102It's a little unwieldy to use the class names whenever you want to log
1103something, but it's quite palatable if you use an alias such as __ (double
Serhiy Storchaka29b0a262016-12-04 10:20:55 +02001104underscore --- not to be confused with _, the single underscore used as a
Vinay Sajip6b883a22012-02-27 11:02:45 +00001105synonym/alias for :func:`gettext.gettext` or its brethren).
1106
1107The above classes are not included in Python, though they're easy enough to
1108copy and paste into your own code. They can be used as follows (assuming that
1109they're declared in a module called ``wherever``):
1110
1111.. code-block:: pycon
1112
1113 >>> from wherever import BraceMessage as __
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001114 >>> print(__('Message with {0} {name}', 2, name='placeholders'))
Vinay Sajip6b883a22012-02-27 11:02:45 +00001115 Message with 2 placeholders
1116 >>> class Point: pass
1117 ...
1118 >>> p = Point()
1119 >>> p.x = 0.5
1120 >>> p.y = 0.5
1121 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
1122 ... point=p))
1123 Message with coordinates: (0.50, 0.50)
1124 >>> from wherever import DollarMessage as __
1125 >>> print(__('Message with $num $what', num=2, what='placeholders'))
1126 Message with 2 placeholders
1127 >>>
1128
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001129While the above examples use ``print()`` to show how the formatting works, you
1130would of course use ``logger.debug()`` or similar to actually log using this
1131approach.
1132
Vinay Sajip6b883a22012-02-27 11:02:45 +00001133One thing to note is that you pay no significant performance penalty with this
1134approach: the actual formatting happens not when you make the logging call, but
1135when (and if) the logged message is actually about to be output to a log by a
1136handler. So the only slightly unusual thing which might trip you up is that the
1137parentheses go around the format string and the arguments, not just the format
1138string. That's because the __ notation is just syntax sugar for a constructor
1139call to one of the XXXMessage classes.
1140
Vinay Sajip8028a5c2013-03-30 11:56:18 +00001141If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect
1142to the above, as in the following example::
1143
1144 import logging
1145
1146 class Message(object):
1147 def __init__(self, fmt, args):
1148 self.fmt = fmt
1149 self.args = args
1150
1151 def __str__(self):
1152 return self.fmt.format(*self.args)
1153
1154 class StyleAdapter(logging.LoggerAdapter):
1155 def __init__(self, logger, extra=None):
1156 super(StyleAdapter, self).__init__(logger, extra or {})
1157
1158 def log(self, level, msg, *args, **kwargs):
1159 if self.isEnabledFor(level):
1160 msg, kwargs = self.process(msg, kwargs)
1161 self.logger._log(level, Message(msg, args), (), **kwargs)
1162
1163 logger = StyleAdapter(logging.getLogger(__name__))
1164
1165 def main():
1166 logger.debug('Hello, {}', 'world!')
1167
1168 if __name__ == '__main__':
1169 logging.basicConfig(level=logging.DEBUG)
1170 main()
1171
1172The above script should log the message ``Hello, world!`` when run with
1173Python 3.2 or later.
1174
Vinay Sajip6b883a22012-02-27 11:02:45 +00001175
Vinay Sajip982f5342012-02-27 11:56:29 +00001176.. currentmodule:: logging
1177
Georg Brandle9983862012-02-28 08:21:40 +01001178.. _custom-logrecord:
Vinay Sajip982f5342012-02-27 11:56:29 +00001179
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001180Customizing ``LogRecord``
Vinay Sajip982f5342012-02-27 11:56:29 +00001181-------------------------
1182
1183Every logging event is represented by a :class:`LogRecord` instance.
1184When an event is logged and not filtered out by a logger's level, a
1185:class:`LogRecord` is created, populated with information about the event and
1186then passed to the handlers for that logger (and its ancestors, up to and
1187including the logger where further propagation up the hierarchy is disabled).
1188Before Python 3.2, there were only two places where this creation was done:
1189
1190* :meth:`Logger.makeRecord`, which is called in the normal process of
1191 logging an event. This invoked :class:`LogRecord` directly to create an
1192 instance.
1193* :func:`makeLogRecord`, which is called with a dictionary containing
1194 attributes to be added to the LogRecord. This is typically invoked when a
1195 suitable dictionary has been received over the network (e.g. in pickle form
1196 via a :class:`~handlers.SocketHandler`, or in JSON form via an
1197 :class:`~handlers.HTTPHandler`).
1198
1199This has usually meant that if you need to do anything special with a
1200:class:`LogRecord`, you've had to do one of the following.
1201
1202* Create your own :class:`Logger` subclass, which overrides
1203 :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass`
1204 before any loggers that you care about are instantiated.
1205* Add a :class:`Filter` to a logger or handler, which does the
1206 necessary special manipulation you need when its
1207 :meth:`~Filter.filter` method is called.
1208
1209The first approach would be a little unwieldy in the scenario where (say)
1210several different libraries wanted to do different things. Each would attempt
1211to set its own :class:`Logger` subclass, and the one which did this last would
1212win.
1213
1214The second approach works reasonably well for many cases, but does not allow
1215you to e.g. use a specialized subclass of :class:`LogRecord`. Library
1216developers can set a suitable filter on their loggers, but they would have to
1217remember to do this every time they introduced a new logger (which they would
Georg Brandle9983862012-02-28 08:21:40 +01001218do simply by adding new packages or modules and doing ::
Vinay Sajip982f5342012-02-27 11:56:29 +00001219
1220 logger = logging.getLogger(__name__)
1221
1222at module level). It's probably one too many things to think about. Developers
1223could also add the filter to a :class:`~logging.NullHandler` attached to their
1224top-level logger, but this would not be invoked if an application developer
Serhiy Storchaka29b0a262016-12-04 10:20:55 +02001225attached a handler to a lower-level library logger --- so output from that
Vinay Sajip982f5342012-02-27 11:56:29 +00001226handler would not reflect the intentions of the library developer.
1227
1228In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a
1229factory, which you can specify. The factory is just a callable you can set with
1230:func:`~logging.setLogRecordFactory`, and interrogate with
1231:func:`~logging.getLogRecordFactory`. The factory is invoked with the same
1232signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord`
1233is the default setting for the factory.
1234
1235This approach allows a custom factory to control all aspects of LogRecord
1236creation. For example, you could return a subclass, or just add some additional
1237attributes to the record once created, using a pattern similar to this::
1238
1239 old_factory = logging.getLogRecordFactory()
1240
1241 def record_factory(*args, **kwargs):
1242 record = old_factory(*args, **kwargs)
1243 record.custom_attribute = 0xdecafbad
1244 return record
1245
1246 logging.setLogRecordFactory(record_factory)
1247
1248This pattern allows different libraries to chain factories together, and as
1249long as they don't overwrite each other's attributes or unintentionally
1250overwrite the attributes provided as standard, there should be no surprises.
1251However, it should be borne in mind that each link in the chain adds run-time
1252overhead to all logging operations, and the technique should only be used when
1253the use of a :class:`Filter` does not provide the desired result.
1254
1255
Vinay Sajipc63619b2010-12-19 12:56:57 +00001256.. _zeromq-handlers:
1257
Vinay Sajip7d101292010-12-26 21:22:33 +00001258Subclassing QueueHandler - a ZeroMQ example
1259-------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001260
1261You can use a :class:`QueueHandler` subclass to send messages to other kinds
1262of queues, for example a ZeroMQ 'publish' socket. In the example below,the
1263socket is created separately and passed to the handler (as its 'queue')::
1264
Serhiy Storchakadba90392016-05-10 12:01:23 +03001265 import zmq # using pyzmq, the Python binding for ZeroMQ
1266 import json # for serializing records portably
Vinay Sajipc63619b2010-12-19 12:56:57 +00001267
1268 ctx = zmq.Context()
Serhiy Storchakadba90392016-05-10 12:01:23 +03001269 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
1270 sock.bind('tcp://*:5556') # or wherever
Vinay Sajipc63619b2010-12-19 12:56:57 +00001271
1272 class ZeroMQSocketHandler(QueueHandler):
1273 def enqueue(self, record):
Pablo Galindo586c0502017-09-07 21:53:13 +01001274 self.queue.send_json(record.__dict__)
1275
Vinay Sajipc63619b2010-12-19 12:56:57 +00001276
1277 handler = ZeroMQSocketHandler(sock)
1278
1279
1280Of course there are other ways of organizing this, for example passing in the
1281data needed by the handler to create the socket::
1282
1283 class ZeroMQSocketHandler(QueueHandler):
1284 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
1285 self.ctx = ctx or zmq.Context()
1286 socket = zmq.Socket(self.ctx, socktype)
1287 socket.bind(uri)
Pablo Galindo586c0502017-09-07 21:53:13 +01001288 super().__init__(socket)
Vinay Sajipc63619b2010-12-19 12:56:57 +00001289
1290 def enqueue(self, record):
Pablo Galindo586c0502017-09-07 21:53:13 +01001291 self.queue.send_json(record.__dict__)
Vinay Sajipc63619b2010-12-19 12:56:57 +00001292
1293 def close(self):
1294 self.queue.close()
1295
1296
Vinay Sajip7d101292010-12-26 21:22:33 +00001297Subclassing QueueListener - a ZeroMQ example
1298--------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001299
1300You can also subclass :class:`QueueListener` to get messages from other kinds
1301of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
1302
1303 class ZeroMQSocketListener(QueueListener):
1304 def __init__(self, uri, *handlers, **kwargs):
1305 self.ctx = kwargs.get('ctx') or zmq.Context()
1306 socket = zmq.Socket(self.ctx, zmq.SUB)
Pablo Galindo586c0502017-09-07 21:53:13 +01001307 socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to everything
Vinay Sajipc63619b2010-12-19 12:56:57 +00001308 socket.connect(uri)
Pablo Galindo586c0502017-09-07 21:53:13 +01001309 super().__init__(socket, *handlers, **kwargs)
Vinay Sajipc63619b2010-12-19 12:56:57 +00001310
1311 def dequeue(self):
Pablo Galindo586c0502017-09-07 21:53:13 +01001312 msg = self.queue.recv_json()
1313 return logging.makeLogRecord(msg)
Vinay Sajipc63619b2010-12-19 12:56:57 +00001314
1315
Vinay Sajip7d101292010-12-26 21:22:33 +00001316.. seealso::
Vinay Sajipc63619b2010-12-19 12:56:57 +00001317
Vinay Sajip7d101292010-12-26 21:22:33 +00001318 Module :mod:`logging`
1319 API reference for the logging module.
1320
1321 Module :mod:`logging.config`
1322 Configuration API for the logging module.
1323
1324 Module :mod:`logging.handlers`
1325 Useful handlers included with the logging module.
1326
1327 :ref:`A basic logging tutorial <logging-basic-tutorial>`
1328
1329 :ref:`A more advanced logging tutorial <logging-advanced-tutorial>`
Vinay Sajip631a7e22011-11-23 14:27:54 +00001330
1331
1332An example dictionary-based configuration
1333-----------------------------------------
1334
1335Below is an example of a logging configuration dictionary - it's taken from
Serhiy Storchaka90be7332016-04-11 12:18:56 +03001336the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_.
Vinay Sajip67f39772013-08-17 00:39:42 +01001337This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::
Vinay Sajip631a7e22011-11-23 14:27:54 +00001338
1339 LOGGING = {
1340 'version': 1,
1341 'disable_existing_loggers': True,
1342 'formatters': {
1343 'verbose': {
1344 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
1345 },
1346 'simple': {
1347 'format': '%(levelname)s %(message)s'
1348 },
1349 },
1350 'filters': {
1351 'special': {
1352 '()': 'project.logging.SpecialFilter',
1353 'foo': 'bar',
1354 }
1355 },
1356 'handlers': {
1357 'null': {
1358 'level':'DEBUG',
1359 'class':'django.utils.log.NullHandler',
1360 },
1361 'console':{
1362 'level':'DEBUG',
1363 'class':'logging.StreamHandler',
1364 'formatter': 'simple'
1365 },
1366 'mail_admins': {
1367 'level': 'ERROR',
1368 'class': 'django.utils.log.AdminEmailHandler',
1369 'filters': ['special']
1370 }
1371 },
1372 'loggers': {
1373 'django': {
1374 'handlers':['null'],
1375 'propagate': True,
1376 'level':'INFO',
1377 },
1378 'django.request': {
1379 'handlers': ['mail_admins'],
1380 'level': 'ERROR',
1381 'propagate': False,
1382 },
1383 'myproject.custom': {
1384 'handlers': ['console', 'mail_admins'],
1385 'level': 'INFO',
1386 'filters': ['special']
1387 }
1388 }
1389 }
1390
1391For more information about this configuration, you can see the `relevant
Serhiy Storchaka90be7332016-04-11 12:18:56 +03001392section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_
Vinay Sajip631a7e22011-11-23 14:27:54 +00001393of the Django documentation.
Vinay Sajip23b94d02012-01-04 12:02:26 +00001394
1395.. _cookbook-rotator-namer:
1396
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001397Using a rotator and namer to customize log rotation processing
Vinay Sajip23b94d02012-01-04 12:02:26 +00001398--------------------------------------------------------------
1399
1400An example of how you can define a namer and rotator is given in the following
1401snippet, which shows zlib-based compression of the log file::
1402
1403 def namer(name):
1404 return name + ".gz"
1405
1406 def rotator(source, dest):
1407 with open(source, "rb") as sf:
1408 data = sf.read()
1409 compressed = zlib.compress(data, 9)
1410 with open(dest, "wb") as df:
1411 df.write(compressed)
1412 os.remove(source)
1413
1414 rh = logging.handlers.RotatingFileHandler(...)
1415 rh.rotator = rotator
1416 rh.namer = namer
1417
Ezio Melotti226231c2012-01-18 05:40:00 +02001418These are not "true" .gz files, as they are bare compressed data, with no
1419"container" such as youd find in an actual gzip file. This snippet is just
Vinay Sajip23b94d02012-01-04 12:02:26 +00001420for illustration purposes.
1421
Vinay Sajip0292fa92012-04-08 01:49:12 +01001422A more elaborate multiprocessing example
1423----------------------------------------
1424
1425The following working example shows how logging can be used with multiprocessing
1426using configuration files. The configurations are fairly simple, but serve to
1427illustrate how more complex ones could be implemented in a real multiprocessing
1428scenario.
1429
1430In the example, the main process spawns a listener process and some worker
1431processes. Each of the main process, the listener and the workers have three
1432separate configurations (the workers all share the same configuration). We can
1433see logging in the main process, how the workers log to a QueueHandler and how
1434the listener implements a QueueListener and a more complex logging
1435configuration, and arranges to dispatch events received via the queue to the
1436handlers specified in the configuration. Note that these configurations are
1437purely illustrative, but you should be able to adapt this example to your own
1438scenario.
1439
1440Here's the script - the docstrings and the comments hopefully explain how it
1441works::
1442
1443 import logging
1444 import logging.config
1445 import logging.handlers
1446 from multiprocessing import Process, Queue, Event, current_process
1447 import os
1448 import random
1449 import time
1450
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001451 class MyHandler:
Vinay Sajip0292fa92012-04-08 01:49:12 +01001452 """
1453 A simple handler for logging events. It runs in the listener process and
1454 dispatches events to loggers based on the name in the received record,
1455 which then get dispatched, by the logging system, to the handlers
Vinay Sajip838e6382012-04-09 19:46:24 +01001456 configured for those loggers.
Vinay Sajip0292fa92012-04-08 01:49:12 +01001457 """
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001458
Vinay Sajip0292fa92012-04-08 01:49:12 +01001459 def handle(self, record):
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001460 if record.name == "root":
1461 logger = logging.getLogger()
1462 else:
1463 logger = logging.getLogger(record.name)
1464
1465 if logger.isEnabledFor(record.levelno):
1466 # The process name is transformed just to show that it's the listener
1467 # doing the logging to files and console
1468 record.processName = '%s (for %s)' % (current_process().name, record.processName)
1469 logger.handle(record)
Vinay Sajip0292fa92012-04-08 01:49:12 +01001470
1471 def listener_process(q, stop_event, config):
1472 """
1473 This could be done in the main process, but is just done in a separate
1474 process for illustrative purposes.
1475
1476 This initialises logging according to the specified configuration,
1477 starts the listener and waits for the main process to signal completion
1478 via the event. The listener is then stopped, and the process exits.
1479 """
1480 logging.config.dictConfig(config)
1481 listener = logging.handlers.QueueListener(q, MyHandler())
1482 listener.start()
1483 if os.name == 'posix':
1484 # On POSIX, the setup logger will have been configured in the
1485 # parent process, but should have been disabled following the
1486 # dictConfig call.
1487 # On Windows, since fork isn't used, the setup logger won't
1488 # exist in the child, so it would be created and the message
1489 # would appear - hence the "if posix" clause.
1490 logger = logging.getLogger('setup')
1491 logger.critical('Should not appear, because of disabled logger ...')
1492 stop_event.wait()
1493 listener.stop()
1494
1495 def worker_process(config):
1496 """
1497 A number of these are spawned for the purpose of illustration. In
Berker Peksag315e1042015-05-19 01:36:55 +03001498 practice, they could be a heterogeneous bunch of processes rather than
Vinay Sajip0292fa92012-04-08 01:49:12 +01001499 ones which are identical to each other.
1500
1501 This initialises logging according to the specified configuration,
1502 and logs a hundred messages with random levels to randomly selected
1503 loggers.
1504
1505 A small sleep is added to allow other processes a chance to run. This
1506 is not strictly needed, but it mixes the output from the different
1507 processes a bit more than if it's left out.
1508 """
1509 logging.config.dictConfig(config)
1510 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
1511 logging.CRITICAL]
1512 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
1513 'spam', 'spam.ham', 'spam.ham.eggs']
1514 if os.name == 'posix':
1515 # On POSIX, the setup logger will have been configured in the
1516 # parent process, but should have been disabled following the
1517 # dictConfig call.
1518 # On Windows, since fork isn't used, the setup logger won't
1519 # exist in the child, so it would be created and the message
1520 # would appear - hence the "if posix" clause.
1521 logger = logging.getLogger('setup')
1522 logger.critical('Should not appear, because of disabled logger ...')
1523 for i in range(100):
1524 lvl = random.choice(levels)
1525 logger = logging.getLogger(random.choice(loggers))
1526 logger.log(lvl, 'Message no. %d', i)
1527 time.sleep(0.01)
1528
1529 def main():
1530 q = Queue()
1531 # The main process gets a simple configuration which prints to the console.
1532 config_initial = {
1533 'version': 1,
Vinay Sajip0292fa92012-04-08 01:49:12 +01001534 'handlers': {
1535 'console': {
1536 'class': 'logging.StreamHandler',
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001537 'level': 'INFO'
1538 }
Vinay Sajip0292fa92012-04-08 01:49:12 +01001539 },
1540 'root': {
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001541 'handlers': ['console'],
1542 'level': 'DEBUG'
1543 }
Vinay Sajip0292fa92012-04-08 01:49:12 +01001544 }
1545 # The worker process configuration is just a QueueHandler attached to the
1546 # root logger, which allows all messages to be sent to the queue.
1547 # We disable existing loggers to disable the "setup" logger used in the
1548 # parent process. This is needed on POSIX because the logger will
1549 # be there in the child following a fork().
1550 config_worker = {
1551 'version': 1,
1552 'disable_existing_loggers': True,
1553 'handlers': {
1554 'queue': {
1555 'class': 'logging.handlers.QueueHandler',
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001556 'queue': q
1557 }
Vinay Sajip0292fa92012-04-08 01:49:12 +01001558 },
1559 'root': {
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001560 'handlers': ['queue'],
1561 'level': 'DEBUG'
1562 }
Vinay Sajip0292fa92012-04-08 01:49:12 +01001563 }
1564 # The listener process configuration shows that the full flexibility of
1565 # logging configuration is available to dispatch events to handlers however
1566 # you want.
1567 # We disable existing loggers to disable the "setup" logger used in the
1568 # parent process. This is needed on POSIX because the logger will
1569 # be there in the child following a fork().
1570 config_listener = {
1571 'version': 1,
1572 'disable_existing_loggers': True,
1573 'formatters': {
1574 'detailed': {
1575 'class': 'logging.Formatter',
1576 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1577 },
1578 'simple': {
1579 'class': 'logging.Formatter',
1580 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1581 }
1582 },
1583 'handlers': {
1584 'console': {
1585 'class': 'logging.StreamHandler',
Vinay Sajip0292fa92012-04-08 01:49:12 +01001586 'formatter': 'simple',
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001587 'level': 'INFO'
Vinay Sajip0292fa92012-04-08 01:49:12 +01001588 },
1589 'file': {
1590 'class': 'logging.FileHandler',
1591 'filename': 'mplog.log',
1592 'mode': 'w',
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001593 'formatter': 'detailed'
Vinay Sajip0292fa92012-04-08 01:49:12 +01001594 },
1595 'foofile': {
1596 'class': 'logging.FileHandler',
1597 'filename': 'mplog-foo.log',
1598 'mode': 'w',
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001599 'formatter': 'detailed'
Vinay Sajip0292fa92012-04-08 01:49:12 +01001600 },
1601 'errors': {
1602 'class': 'logging.FileHandler',
1603 'filename': 'mplog-errors.log',
1604 'mode': 'w',
Vinay Sajip0292fa92012-04-08 01:49:12 +01001605 'formatter': 'detailed',
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001606 'level': 'ERROR'
1607 }
Vinay Sajip0292fa92012-04-08 01:49:12 +01001608 },
1609 'loggers': {
1610 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001611 'handlers': ['foofile']
Vinay Sajip0292fa92012-04-08 01:49:12 +01001612 }
1613 },
1614 'root': {
Géry Ogam5b3cbcd2018-09-25 09:24:52 +02001615 'handlers': ['console', 'file', 'errors'],
1616 'level': 'DEBUG'
1617 }
Vinay Sajip0292fa92012-04-08 01:49:12 +01001618 }
1619 # Log some initial events, just to show that logging in the parent works
1620 # normally.
1621 logging.config.dictConfig(config_initial)
1622 logger = logging.getLogger('setup')
1623 logger.info('About to create workers ...')
1624 workers = []
1625 for i in range(5):
1626 wp = Process(target=worker_process, name='worker %d' % (i + 1),
1627 args=(config_worker,))
1628 workers.append(wp)
1629 wp.start()
1630 logger.info('Started worker: %s', wp.name)
1631 logger.info('About to create listener ...')
1632 stop_event = Event()
1633 lp = Process(target=listener_process, name='listener',
1634 args=(q, stop_event, config_listener))
1635 lp.start()
1636 logger.info('Started listener')
1637 # We now hang around for the workers to finish their work.
1638 for wp in workers:
1639 wp.join()
1640 # Workers all done, listening can now stop.
1641 # Logging in the parent still works normally.
1642 logger.info('Telling listener to stop ...')
1643 stop_event.set()
1644 lp.join()
1645 logger.info('All done.')
1646
1647 if __name__ == '__main__':
1648 main()
1649
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001650
1651Inserting a BOM into messages sent to a SysLogHandler
1652-----------------------------------------------------
1653
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +03001654:rfc:`5424` requires that a
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001655Unicode message be sent to a syslog daemon as a set of bytes which have the
1656following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +03001657Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the
1658:rfc:`relevant section of the specification <5424#section-6>`.)
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001659
Vinay Sajip62930e12012-04-17 00:40:48 +01001660In Python 3.1, code was added to
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001661:class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
1662unfortunately, it was implemented incorrectly, with the BOM appearing at the
1663beginning of the message and hence not allowing any pure-ASCII component to
1664appear before it.
1665
1666As this behaviour is broken, the incorrect BOM insertion code is being removed
Vinay Sajip62930e12012-04-17 00:40:48 +01001667from Python 3.2.4 and later. However, it is not being replaced, and if you
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +03001668want to produce :rfc:`5424`-compliant messages which include a BOM, an optional
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001669pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
1670UTF-8, then you need to do the following:
1671
1672#. Attach a :class:`~logging.Formatter` instance to your
1673 :class:`~logging.handlers.SysLogHandler` instance, with a format string
1674 such as::
1675
Vinay Sajip59b9a792012-04-16 15:46:18 +01001676 'ASCII section\ufeffUnicode section'
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001677
Georg Brandld50fe722013-03-23 16:00:41 +01001678 The Unicode code point U+FEFF, when encoded using UTF-8, will be
Vinay Sajip59b9a792012-04-16 15:46:18 +01001679 encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001680
1681#. Replace the ASCII section with whatever placeholders you like, but make sure
1682 that the data that appears in there after substitution is always ASCII (that
1683 way, it will remain unchanged after UTF-8 encoding).
1684
1685#. Replace the Unicode section with whatever placeholders you like; if the data
Vinay Sajipa58d6682012-07-27 10:54:10 +01001686 which appears there after substitution contains characters outside the ASCII
1687 range, that's fine -- it will be encoded using UTF-8.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001688
Vinay Sajip59b9a792012-04-16 15:46:18 +01001689The formatted message *will* be encoded using UTF-8 encoding by
1690``SysLogHandler``. If you follow the above rules, you should be able to produce
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +03001691:rfc:`5424`-compliant messages. If you don't, logging may not complain, but your
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001692messages will not be RFC 5424-compliant, and your syslog daemon may complain.
1693
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001694
1695Implementing structured logging
1696-------------------------------
1697
1698Although most logging messages are intended for reading by humans, and thus not
delirious-lettuce3378b202017-05-19 14:37:57 -06001699readily machine-parseable, there might be circumstances where you want to output
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001700messages in a structured format which *is* capable of being parsed by a program
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001701(without needing complex regular expressions to parse the log message). This is
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001702straightforward to achieve using the logging package. There are a number of
1703ways in which this could be achieved, but the following is a simple approach
1704which uses JSON to serialise the event in a machine-parseable manner::
1705
1706 import json
1707 import logging
1708
1709 class StructuredMessage(object):
1710 def __init__(self, message, **kwargs):
1711 self.message = message
1712 self.kwargs = kwargs
1713
1714 def __str__(self):
1715 return '%s >>> %s' % (self.message, json.dumps(self.kwargs))
1716
1717 _ = StructuredMessage # optional, to improve readability
1718
1719 logging.basicConfig(level=logging.INFO, format='%(message)s')
1720 logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
1721
Serhiy Storchaka46936d52018-04-08 19:18:04 +03001722If the above script is run, it prints:
1723
1724.. code-block:: none
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001725
1726 message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}
1727
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001728Note that the order of items might be different according to the version of
1729Python used.
1730
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001731If you need more specialised processing, you can use a custom JSON encoder,
1732as in the following complete example::
1733
1734 from __future__ import unicode_literals
1735
1736 import json
1737 import logging
1738
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001739 # This next bit is to ensure the script runs unchanged on 2.x and 3.x
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001740 try:
1741 unicode
1742 except NameError:
1743 unicode = str
1744
1745 class Encoder(json.JSONEncoder):
1746 def default(self, o):
1747 if isinstance(o, set):
1748 return tuple(o)
1749 elif isinstance(o, unicode):
1750 return o.encode('unicode_escape').decode('ascii')
1751 return super(Encoder, self).default(o)
1752
1753 class StructuredMessage(object):
1754 def __init__(self, message, **kwargs):
1755 self.message = message
1756 self.kwargs = kwargs
1757
1758 def __str__(self):
1759 s = Encoder().encode(self.kwargs)
1760 return '%s >>> %s' % (self.message, s)
1761
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001762 _ = StructuredMessage # optional, to improve readability
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001763
1764 def main():
1765 logging.basicConfig(level=logging.INFO, format='%(message)s')
Raymond Hettingerdf1b6992014-11-09 15:56:33 -08001766 logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001767
1768 if __name__ == '__main__':
1769 main()
1770
Serhiy Storchaka46936d52018-04-08 19:18:04 +03001771When the above script is run, it prints:
1772
1773.. code-block:: none
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001774
1775 message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}
1776
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001777Note that the order of items might be different according to the version of
1778Python used.
1779
Vinay Sajip554f22f2014-02-03 11:51:45 +00001780
1781.. _custom-handlers:
1782
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001783.. currentmodule:: logging.config
1784
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001785Customizing handlers with :func:`dictConfig`
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001786--------------------------------------------
1787
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001788There are times when you want to customize logging handlers in particular ways,
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001789and if you use :func:`dictConfig` you may be able to do this without
1790subclassing. As an example, consider that you may want to set the ownership of a
1791log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001792handlers in the stdlib don't offer built-in support. You can customize handler
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001793creation using a plain function such as::
1794
1795 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1796 if owner:
1797 if not os.path.exists(filename):
1798 open(filename, 'a').close()
1799 shutil.chown(filename, *owner)
1800 return logging.FileHandler(filename, mode, encoding)
1801
1802You can then specify, in a logging configuration passed to :func:`dictConfig`,
1803that a logging handler be created by calling this function::
1804
1805 LOGGING = {
1806 'version': 1,
1807 'disable_existing_loggers': False,
1808 'formatters': {
1809 'default': {
1810 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1811 },
1812 },
1813 'handlers': {
1814 'file':{
1815 # The values below are popped from this dictionary and
1816 # used to create the handler, set the handler's level and
1817 # its formatter.
1818 '()': owned_file_handler,
1819 'level':'DEBUG',
1820 'formatter': 'default',
1821 # The values below are passed to the handler creator callable
1822 # as keyword arguments.
1823 'owner': ['pulse', 'pulse'],
1824 'filename': 'chowntest.log',
1825 'mode': 'w',
1826 'encoding': 'utf-8',
1827 },
1828 },
1829 'root': {
1830 'handlers': ['file'],
1831 'level': 'DEBUG',
1832 },
1833 }
1834
1835In this example I am setting the ownership using the ``pulse`` user and group,
1836just for the purposes of illustration. Putting it together into a working
1837script, ``chowntest.py``::
1838
1839 import logging, logging.config, os, shutil
1840
1841 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1842 if owner:
1843 if not os.path.exists(filename):
1844 open(filename, 'a').close()
1845 shutil.chown(filename, *owner)
1846 return logging.FileHandler(filename, mode, encoding)
1847
1848 LOGGING = {
1849 'version': 1,
1850 'disable_existing_loggers': False,
1851 'formatters': {
1852 'default': {
1853 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1854 },
1855 },
1856 'handlers': {
1857 'file':{
1858 # The values below are popped from this dictionary and
1859 # used to create the handler, set the handler's level and
1860 # its formatter.
1861 '()': owned_file_handler,
1862 'level':'DEBUG',
1863 'formatter': 'default',
1864 # The values below are passed to the handler creator callable
1865 # as keyword arguments.
1866 'owner': ['pulse', 'pulse'],
1867 'filename': 'chowntest.log',
1868 'mode': 'w',
1869 'encoding': 'utf-8',
1870 },
1871 },
1872 'root': {
1873 'handlers': ['file'],
1874 'level': 'DEBUG',
1875 },
1876 }
1877
1878 logging.config.dictConfig(LOGGING)
1879 logger = logging.getLogger('mylogger')
1880 logger.debug('A debug message')
1881
Martin Panter1050d2d2016-07-26 11:18:21 +02001882To run this, you will probably need to run as ``root``:
1883
1884.. code-block:: shell-session
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001885
1886 $ sudo python3.3 chowntest.py
1887 $ cat chowntest.log
1888 2013-11-05 09:34:51,128 DEBUG mylogger A debug message
1889 $ ls -l chowntest.log
1890 -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
1891
1892Note that this example uses Python 3.3 because that's where :func:`shutil.chown`
1893makes an appearance. This approach should work with any Python version that
1894supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3
1895versions, you would need to implement the actual ownership change using e.g.
1896:func:`os.chown`.
1897
1898In practice, the handler-creating function may be in a utility module somewhere
1899in your project. Instead of the line in the configuration::
1900
1901 '()': owned_file_handler,
1902
1903you could use e.g.::
1904
1905 '()': 'ext://project.util.owned_file_handler',
1906
1907where ``project.util`` can be replaced with the actual name of the package
1908where the function resides. In the above working script, using
1909``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable
1910is resolved by :func:`dictConfig` from the ``ext://`` specification.
1911
1912This example hopefully also points the way to how you could implement other
1913types of file change - e.g. setting specific POSIX permission bits - in the
1914same way, using :func:`os.chmod`.
1915
1916Of course, the approach could also be extended to types of handler other than a
1917:class:`~logging.FileHandler` - for example, one of the rotating file handlers,
1918or a different type of handler altogether.
1919
Vinay Sajipcbefe3b2014-01-15 15:09:05 +00001920
1921.. currentmodule:: logging
1922
1923.. _formatting-styles:
1924
1925Using particular formatting styles throughout your application
1926--------------------------------------------------------------
1927
1928In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword
1929parameter which, while defaulting to ``%`` for backward compatibility, allowed
1930the specification of ``{`` or ``$`` to support the formatting approaches
1931supported by :meth:`str.format` and :class:`string.Template`. Note that this
1932governs the formatting of logging messages for final output to logs, and is
1933completely orthogonal to how an individual logging message is constructed.
1934
1935Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take
1936positional parameters for the actual logging message itself, with keyword
1937parameters used only for determining options for how to handle the logging call
1938(e.g. the ``exc_info`` keyword parameter to indicate that traceback information
1939should be logged, or the ``extra`` keyword parameter to indicate additional
1940contextual information to be added to the log). So you cannot directly make
1941logging calls using :meth:`str.format` or :class:`string.Template` syntax,
1942because internally the logging package uses %-formatting to merge the format
1943string and the variable arguments. There would no changing this while preserving
1944backward compatibility, since all logging calls which are out there in existing
1945code will be using %-format strings.
1946
1947There have been suggestions to associate format styles with specific loggers,
1948but that approach also runs into backward compatibility problems because any
1949existing code could be using a given logger name and using %-formatting.
1950
1951For logging to work interoperably between any third-party libraries and your
1952code, decisions about formatting need to be made at the level of the
1953individual logging call. This opens up a couple of ways in which alternative
1954formatting styles can be accommodated.
1955
1956
1957Using LogRecord factories
1958^^^^^^^^^^^^^^^^^^^^^^^^^
1959
1960In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned
1961above, the logging package gained the ability to allow users to set their own
1962:class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function.
1963You can use this to set your own subclass of :class:`LogRecord`, which does the
1964Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base
1965class implementation of this method is where the ``msg % args`` formatting
1966happens, and where you can substitute your alternate formatting; however, you
1967should be careful to support all formatting styles and allow %-formatting as
1968the default, to ensure interoperability with other code. Care should also be
1969taken to call ``str(self.msg)``, just as the base implementation does.
1970
1971Refer to the reference documentation on :func:`setLogRecordFactory` and
1972:class:`LogRecord` for more information.
1973
1974
1975Using custom message objects
1976^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1977
1978There is another, perhaps simpler way that you can use {}- and $- formatting to
1979construct your individual log messages. You may recall (from
1980:ref:`arbitrary-object-messages`) that when logging you can use an arbitrary
1981object as a message format string, and that the logging package will call
1982:func:`str` on that object to get the actual format string. Consider the
1983following two classes::
1984
1985 class BraceMessage(object):
1986 def __init__(self, fmt, *args, **kwargs):
1987 self.fmt = fmt
1988 self.args = args
1989 self.kwargs = kwargs
1990
1991 def __str__(self):
1992 return self.fmt.format(*self.args, **self.kwargs)
1993
1994 class DollarMessage(object):
1995 def __init__(self, fmt, **kwargs):
1996 self.fmt = fmt
1997 self.kwargs = kwargs
1998
1999 def __str__(self):
2000 from string import Template
2001 return Template(self.fmt).substitute(**self.kwargs)
2002
2003Either of these can be used in place of a format string, to allow {}- or
2004$-formatting to be used to build the actual "message" part which appears in the
2005formatted log output in place of “%(message)s or “{message}” or $message”.
2006If you find it a little unwieldy to use the class names whenever you want to log
2007something, you can make it more palatable if you use an alias such as ``M`` or
2008``_`` for the message (or perhaps ``__``, if you are using ``_`` for
2009localization).
2010
Vinay Sajipeb14dec2014-01-17 18:36:02 +00002011Examples of this approach are given below. Firstly, formatting with
2012:meth:`str.format`::
2013
2014 >>> __ = BraceMessage
2015 >>> print(__('Message with {0} {1}', 2, 'placeholders'))
2016 Message with 2 placeholders
2017 >>> class Point: pass
2018 ...
2019 >>> p = Point()
2020 >>> p.x = 0.5
2021 >>> p.y = 0.5
2022 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
2023 Message with coordinates: (0.50, 0.50)
2024
2025Secondly, formatting with :class:`string.Template`::
2026
2027 >>> __ = DollarMessage
2028 >>> print(__('Message with $num $what', num=2, what='placeholders'))
2029 Message with 2 placeholders
2030 >>>
2031
2032One thing to note is that you pay no significant performance penalty with this
2033approach: the actual formatting happens not when you make the logging call, but
2034when (and if) the logged message is actually about to be output to a log by a
2035handler. So the only slightly unusual thing which might trip you up is that the
2036parentheses go around the format string and the arguments, not just the format
2037string. Thats because the __ notation is just syntax sugar for a constructor
2038call to one of the ``XXXMessage`` classes shown above.
Vinay Sajip554f22f2014-02-03 11:51:45 +00002039
2040
2041.. _filters-dictconfig:
2042
2043.. currentmodule:: logging.config
2044
2045Configuring filters with :func:`dictConfig`
2046-------------------------------------------
2047
2048You *can* configure filters using :func:`~logging.config.dictConfig`, though it
2049might not be obvious at first glance how to do it (hence this recipe). Since
2050:class:`~logging.Filter` is the only filter class included in the standard
2051library, and it is unlikely to cater to many requirements (it's only there as a
2052base class), you will typically need to define your own :class:`~logging.Filter`
2053subclass with an overridden :meth:`~logging.Filter.filter` method. To do this,
2054specify the ``()`` key in the configuration dictionary for the filter,
2055specifying a callable which will be used to create the filter (a class is the
2056most obvious, but you can provide any callable which returns a
2057:class:`~logging.Filter` instance). Here is a complete example::
2058
2059 import logging
2060 import logging.config
2061 import sys
2062
2063 class MyFilter(logging.Filter):
2064 def __init__(self, param=None):
2065 self.param = param
2066
2067 def filter(self, record):
2068 if self.param is None:
2069 allow = True
2070 else:
2071 allow = self.param not in record.msg
2072 if allow:
2073 record.msg = 'changed: ' + record.msg
2074 return allow
2075
2076 LOGGING = {
2077 'version': 1,
2078 'filters': {
2079 'myfilter': {
2080 '()': MyFilter,
2081 'param': 'noshow',
2082 }
2083 },
2084 'handlers': {
2085 'console': {
2086 'class': 'logging.StreamHandler',
2087 'filters': ['myfilter']
2088 }
2089 },
2090 'root': {
2091 'level': 'DEBUG',
2092 'handlers': ['console']
2093 },
2094 }
2095
2096 if __name__ == '__main__':
2097 logging.config.dictConfig(LOGGING)
2098 logging.debug('hello')
2099 logging.debug('hello - noshow')
2100
2101This example shows how you can pass configuration data to the callable which
2102constructs the instance, in the form of keyword parameters. When run, the above
Serhiy Storchaka46936d52018-04-08 19:18:04 +03002103script will print:
2104
2105.. code-block:: none
Vinay Sajip554f22f2014-02-03 11:51:45 +00002106
2107 changed: hello
2108
2109which shows that the filter is working as configured.
2110
2111A couple of extra points to note:
2112
2113* If you can't refer to the callable directly in the configuration (e.g. if it
2114 lives in a different module, and you can't import it directly where the
2115 configuration dictionary is), you can use the form ``ext://...`` as described
2116 in :ref:`logging-config-dict-externalobj`. For example, you could have used
2117 the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above
2118 example.
2119
2120* As well as for filters, this technique can also be used to configure custom
2121 handlers and formatters. See :ref:`logging-config-dict-userdef` for more
2122 information on how logging supports using user-defined objects in its
2123 configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
2124
Vinay Sajipdb071642015-01-28 07:32:38 +00002125
2126.. _custom-format-exception:
2127
2128Customized exception formatting
2129-------------------------------
2130
2131There might be times when you want to do customized exception formatting - for
2132argument's sake, let's say you want exactly one line per logged event, even
2133when exception information is present. You can do this with a custom formatter
2134class, as shown in the following example::
2135
2136 import logging
2137
2138 class OneLineExceptionFormatter(logging.Formatter):
2139 def formatException(self, exc_info):
2140 """
2141 Format an exception so that it prints on a single line.
2142 """
2143 result = super(OneLineExceptionFormatter, self).formatException(exc_info)
Serhiy Storchakadba90392016-05-10 12:01:23 +03002144 return repr(result) # or format into one line however you want to
Vinay Sajipdb071642015-01-28 07:32:38 +00002145
2146 def format(self, record):
2147 s = super(OneLineExceptionFormatter, self).format(record)
2148 if record.exc_text:
2149 s = s.replace('\n', '') + '|'
2150 return s
2151
2152 def configure_logging():
2153 fh = logging.FileHandler('output.txt', 'w')
2154 f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
2155 '%d/%m/%Y %H:%M:%S')
2156 fh.setFormatter(f)
2157 root = logging.getLogger()
2158 root.setLevel(logging.DEBUG)
2159 root.addHandler(fh)
2160
2161 def main():
2162 configure_logging()
2163 logging.info('Sample message')
2164 try:
2165 x = 1 / 0
2166 except ZeroDivisionError as e:
2167 logging.exception('ZeroDivisionError: %s', e)
2168
2169 if __name__ == '__main__':
2170 main()
2171
Serhiy Storchaka46936d52018-04-08 19:18:04 +03002172When run, this produces a file with exactly two lines:
2173
2174.. code-block:: none
Vinay Sajipdb071642015-01-28 07:32:38 +00002175
2176 28/01/2015 07:21:23|INFO|Sample message|
2177 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'|
2178
2179While the above treatment is simplistic, it points the way to how exception
2180information can be formatted to your liking. The :mod:`traceback` module may be
2181helpful for more specialized needs.
Vinay Sajipf046dfe2015-02-01 15:17:34 +00002182
2183.. _spoken-messages:
2184
2185Speaking logging messages
2186-------------------------
2187
2188There might be situations when it is desirable to have logging messages rendered
Martin Panter8f137832017-01-14 08:24:20 +00002189in an audible rather than a visible format. This is easy to do if you have
2190text-to-speech (TTS) functionality available in your system, even if it doesn't have
Vinay Sajipf046dfe2015-02-01 15:17:34 +00002191a Python binding. Most TTS systems have a command line program you can run, and
2192this can be invoked from a handler using :mod:`subprocess`. It's assumed here
2193that TTS command line programs won't expect to interact with users or take a
2194long time to complete, and that the frequency of logged messages will be not so
2195high as to swamp the user with messages, and that it's acceptable to have the
2196messages spoken one at a time rather than concurrently, The example implementation
2197below waits for one message to be spoken before the next is processed, and this
2198might cause other handlers to be kept waiting. Here is a short example showing
2199the approach, which assumes that the ``espeak`` TTS package is available::
2200
2201 import logging
2202 import subprocess
2203 import sys
2204
2205 class TTSHandler(logging.Handler):
2206 def emit(self, record):
2207 msg = self.format(record)
2208 # Speak slowly in a female English voice
2209 cmd = ['espeak', '-s150', '-ven+f3', msg]
2210 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
2211 stderr=subprocess.STDOUT)
2212 # wait for the program to finish
2213 p.communicate()
2214
2215 def configure_logging():
2216 h = TTSHandler()
2217 root = logging.getLogger()
2218 root.addHandler(h)
2219 # the default formatter just returns the message
2220 root.setLevel(logging.DEBUG)
2221
2222 def main():
2223 logging.info('Hello')
2224 logging.debug('Goodbye')
2225
2226 if __name__ == '__main__':
2227 configure_logging()
2228 sys.exit(main())
2229
2230When run, this script should say "Hello" and then "Goodbye" in a female voice.
2231
2232The above approach can, of course, be adapted to other TTS systems and even
2233other systems altogether which can process messages via external programs run
2234from a command line.
2235
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002236
2237.. _buffered-logging:
2238
2239Buffering logging messages and outputting them conditionally
2240------------------------------------------------------------
2241
2242There might be situations where you want to log messages in a temporary area
2243and only output them if a certain condition occurs. For example, you may want to
2244start logging debug events in a function, and if the function completes without
2245errors, you don't want to clutter the log with the collected debug information,
2246but if there is an error, you want all the debug information to be output as well
2247as the error.
2248
2249Here is an example which shows how you could do this using a decorator for your
2250functions where you want logging to behave this way. It makes use of the
2251:class:`logging.handlers.MemoryHandler`, which allows buffering of logged events
2252until some condition occurs, at which point the buffered events are ``flushed``
2253- passed to another handler (the ``target`` handler) for processing. By default,
2254the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose
2255level is greater than or equal to a specified threshold is seen. You can use this
2256recipe with a more specialised subclass of ``MemoryHandler`` if you want custom
2257flushing behavior.
2258
2259The example script has a simple function, ``foo``, which just cycles through
2260all the logging levels, writing to ``sys.stderr`` to say what level it's about
Martin Panterf05641642016-05-08 13:48:10 +00002261to log at, and then actually logging a message at that level. You can pass a
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002262parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
2263otherwise, it only logs at DEBUG, INFO and WARNING levels.
2264
2265The script just arranges to decorate ``foo`` with a decorator which will do the
2266conditional logging that's required. The decorator takes a logger as a parameter
2267and attaches a memory handler for the duration of the call to the decorated
2268function. The decorator can be additionally parameterised using a target handler,
2269a level at which flushing should occur, and a capacity for the buffer. These
2270default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``,
2271``logging.ERROR`` and ``100`` respectively.
2272
2273Here's the script::
2274
2275 import logging
2276 from logging.handlers import MemoryHandler
2277 import sys
2278
2279 logger = logging.getLogger(__name__)
2280 logger.addHandler(logging.NullHandler())
2281
2282 def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
2283 if target_handler is None:
2284 target_handler = logging.StreamHandler()
2285 if flush_level is None:
2286 flush_level = logging.ERROR
2287 if capacity is None:
2288 capacity = 100
2289 handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)
2290
2291 def decorator(fn):
2292 def wrapper(*args, **kwargs):
2293 logger.addHandler(handler)
2294 try:
2295 return fn(*args, **kwargs)
2296 except Exception:
2297 logger.exception('call failed')
2298 raise
2299 finally:
2300 super(MemoryHandler, handler).flush()
2301 logger.removeHandler(handler)
2302 return wrapper
2303
2304 return decorator
2305
2306 def write_line(s):
2307 sys.stderr.write('%s\n' % s)
2308
2309 def foo(fail=False):
2310 write_line('about to log at DEBUG ...')
2311 logger.debug('Actually logged at DEBUG')
2312 write_line('about to log at INFO ...')
2313 logger.info('Actually logged at INFO')
2314 write_line('about to log at WARNING ...')
2315 logger.warning('Actually logged at WARNING')
2316 if fail:
2317 write_line('about to log at ERROR ...')
2318 logger.error('Actually logged at ERROR')
2319 write_line('about to log at CRITICAL ...')
2320 logger.critical('Actually logged at CRITICAL')
2321 return fail
2322
2323 decorated_foo = log_if_errors(logger)(foo)
2324
2325 if __name__ == '__main__':
2326 logger.setLevel(logging.DEBUG)
2327 write_line('Calling undecorated foo with False')
2328 assert not foo(False)
2329 write_line('Calling undecorated foo with True')
2330 assert foo(True)
2331 write_line('Calling decorated foo with False')
2332 assert not decorated_foo(False)
2333 write_line('Calling decorated foo with True')
2334 assert decorated_foo(True)
2335
Serhiy Storchaka46936d52018-04-08 19:18:04 +03002336When this script is run, the following output should be observed:
2337
2338.. code-block:: none
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002339
2340 Calling undecorated foo with False
2341 about to log at DEBUG ...
2342 about to log at INFO ...
2343 about to log at WARNING ...
2344 Calling undecorated foo with True
2345 about to log at DEBUG ...
2346 about to log at INFO ...
2347 about to log at WARNING ...
2348 about to log at ERROR ...
2349 about to log at CRITICAL ...
2350 Calling decorated foo with False
2351 about to log at DEBUG ...
2352 about to log at INFO ...
2353 about to log at WARNING ...
2354 Calling decorated foo with True
2355 about to log at DEBUG ...
2356 about to log at INFO ...
2357 about to log at WARNING ...
2358 about to log at ERROR ...
2359 Actually logged at DEBUG
2360 Actually logged at INFO
2361 Actually logged at WARNING
2362 Actually logged at ERROR
2363 about to log at CRITICAL ...
2364 Actually logged at CRITICAL
2365
2366As you can see, actual logging output only occurs when an event is logged whose
2367severity is ERROR or greater, but in that case, any previous events at lower
2368severities are also logged.
2369
2370You can of course use the conventional means of decoration::
2371
2372 @log_if_errors(logger)
2373 def foo(fail=False):
2374 ...
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002375
2376
2377.. _utc-formatting:
2378
2379Formatting times using UTC (GMT) via configuration
2380--------------------------------------------------
2381
2382Sometimes you want to format times using UTC, which can be done using a class
2383such as `UTCFormatter`, shown below::
2384
2385 import logging
2386 import time
2387
2388 class UTCFormatter(logging.Formatter):
2389 converter = time.gmtime
2390
Berker Peksagf84499a2015-10-20 03:41:38 +03002391and you can then use the ``UTCFormatter`` in your code instead of
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002392:class:`~logging.Formatter`. If you want to do that via configuration, you can
2393use the :func:`~logging.config.dictConfig` API with an approach illustrated by
2394the following complete example::
2395
2396 import logging
2397 import logging.config
2398 import time
2399
2400 class UTCFormatter(logging.Formatter):
2401 converter = time.gmtime
2402
2403 LOGGING = {
2404 'version': 1,
2405 'disable_existing_loggers': False,
2406 'formatters': {
2407 'utc': {
2408 '()': UTCFormatter,
2409 'format': '%(asctime)s %(message)s',
2410 },
2411 'local': {
2412 'format': '%(asctime)s %(message)s',
2413 }
2414 },
2415 'handlers': {
2416 'console1': {
2417 'class': 'logging.StreamHandler',
2418 'formatter': 'utc',
2419 },
2420 'console2': {
2421 'class': 'logging.StreamHandler',
2422 'formatter': 'local',
2423 },
2424 },
2425 'root': {
2426 'handlers': ['console1', 'console2'],
2427 }
2428 }
2429
2430 if __name__ == '__main__':
2431 logging.config.dictConfig(LOGGING)
2432 logging.warning('The local time is %s', time.asctime())
2433
Serhiy Storchaka46936d52018-04-08 19:18:04 +03002434When this script is run, it should print something like:
2435
2436.. code-block:: none
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002437
2438 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2439 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2440
2441showing how the time is formatted both as local time and UTC, one for each
2442handler.
Vinay Sajipd93a6012016-04-01 23:13:01 +01002443
2444
2445.. _context-manager:
2446
2447Using a context manager for selective logging
2448---------------------------------------------
2449
2450There are times when it would be useful to temporarily change the logging
2451configuration and revert it back after doing something. For this, a context
2452manager is the most obvious way of saving and restoring the logging context.
2453Here is a simple example of such a context manager, which allows you to
2454optionally change the logging level and add a logging handler purely in the
2455scope of the context manager::
2456
2457 import logging
2458 import sys
2459
2460 class LoggingContext(object):
2461 def __init__(self, logger, level=None, handler=None, close=True):
2462 self.logger = logger
2463 self.level = level
2464 self.handler = handler
2465 self.close = close
2466
2467 def __enter__(self):
2468 if self.level is not None:
2469 self.old_level = self.logger.level
2470 self.logger.setLevel(self.level)
2471 if self.handler:
2472 self.logger.addHandler(self.handler)
2473
2474 def __exit__(self, et, ev, tb):
2475 if self.level is not None:
2476 self.logger.setLevel(self.old_level)
2477 if self.handler:
2478 self.logger.removeHandler(self.handler)
2479 if self.handler and self.close:
2480 self.handler.close()
2481 # implicit return of None => don't swallow exceptions
2482
2483If you specify a level value, the logger's level is set to that value in the
2484scope of the with block covered by the context manager. If you specify a
2485handler, it is added to the logger on entry to the block and removed on exit
2486from the block. You can also ask the manager to close the handler for you on
2487block exit - you could do this if you don't need the handler any more.
2488
2489To illustrate how it works, we can add the following block of code to the
2490above::
2491
2492 if __name__ == '__main__':
2493 logger = logging.getLogger('foo')
2494 logger.addHandler(logging.StreamHandler())
2495 logger.setLevel(logging.INFO)
2496 logger.info('1. This should appear just once on stderr.')
2497 logger.debug('2. This should not appear.')
2498 with LoggingContext(logger, level=logging.DEBUG):
2499 logger.debug('3. This should appear once on stderr.')
2500 logger.debug('4. This should not appear.')
2501 h = logging.StreamHandler(sys.stdout)
2502 with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
2503 logger.debug('5. This should appear twice - once on stderr and once on stdout.')
2504 logger.info('6. This should appear just once on stderr.')
2505 logger.debug('7. This should not appear.')
2506
2507We initially set the logger's level to ``INFO``, so message #1 appears and
2508message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the
2509following ``with`` block, and so message #3 appears. After the block exits, the
2510logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the
2511next ``with`` block, we set the level to ``DEBUG`` again but also add a handler
2512writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once
2513via ``stderr`` and once via ``stdout``). After the ``with`` statement's
2514completion, the status is as it was before so message #6 appears (like message
2515#1) whereas message #7 doesn't (just like message #2).
2516
Martin Panter1050d2d2016-07-26 11:18:21 +02002517If we run the resulting script, the result is as follows:
2518
2519.. code-block:: shell-session
Vinay Sajipd93a6012016-04-01 23:13:01 +01002520
2521 $ python logctx.py
2522 1. This should appear just once on stderr.
2523 3. This should appear once on stderr.
2524 5. This should appear twice - once on stderr and once on stdout.
2525 5. This should appear twice - once on stderr and once on stdout.
2526 6. This should appear just once on stderr.
2527
2528If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
Martin Panter1050d2d2016-07-26 11:18:21 +02002529which is the only message written to ``stdout``:
2530
2531.. code-block:: shell-session
Vinay Sajipd93a6012016-04-01 23:13:01 +01002532
2533 $ python logctx.py 2>/dev/null
2534 5. This should appear twice - once on stderr and once on stdout.
2535
Martin Panter1050d2d2016-07-26 11:18:21 +02002536Once again, but piping ``stdout`` to ``/dev/null``, we get:
2537
2538.. code-block:: shell-session
Vinay Sajipd93a6012016-04-01 23:13:01 +01002539
2540 $ python logctx.py >/dev/null
2541 1. This should appear just once on stderr.
2542 3. This should appear once on stderr.
2543 5. This should appear twice - once on stderr and once on stdout.
2544 6. This should appear just once on stderr.
2545
2546In this case, the message #5 printed to ``stdout`` doesn't appear, as expected.
2547
2548Of course, the approach described here can be generalised, for example to attach
2549logging filters temporarily. Note that the above code works in Python 2 as well
2550as Python 3.
Vinay Sajip1a4a10d2018-10-16 12:36:52 +01002551
2552
2553.. _starter-template:
2554
2555A CLI application starter template
2556----------------------------------
2557
2558Here's an example which shows how you can:
2559
2560* Use a logging level based on command-line arguments
2561* Dispatch to multiple subcommands in separate files, all logging at the same
2562 level in a consistent way
2563* Make use of simple, minimal configuration
2564
2565Suppose we have a command-line application whose job is to stop, start or
2566restart some services. This could be organised for the purposes of illustration
2567as a file ``app.py`` that is the main script for the application, with individual
2568commands implemented in ``start.py``, ``stop.py`` and ``restart.py``. Suppose
2569further that we want to control the verbosity of the application via a
2570command-line argument, defaulting to ``logging.INFO``. Here's one way that
2571``app.py`` could be written::
2572
2573 import argparse
2574 import importlib
2575 import logging
2576 import os
2577 import sys
2578
2579 def main(args=None):
2580 scriptname = os.path.basename(__file__)
2581 parser = argparse.ArgumentParser(scriptname)
2582 levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
2583 parser.add_argument('--log-level', default='INFO', choices=levels)
2584 subparsers = parser.add_subparsers(dest='command',
2585 help='Available commands:')
2586 start_cmd = subparsers.add_parser('start', help='Start a service')
2587 start_cmd.add_argument('name', metavar='NAME',
2588 help='Name of service to start')
2589 stop_cmd = subparsers.add_parser('stop',
2590 help='Stop one or more services')
2591 stop_cmd.add_argument('names', metavar='NAME', nargs='+',
2592 help='Name of service to stop')
2593 restart_cmd = subparsers.add_parser('restart',
2594 help='Restart one or more services')
2595 restart_cmd.add_argument('names', metavar='NAME', nargs='+',
2596 help='Name of service to restart')
2597 options = parser.parse_args()
2598 # the code to dispatch commands could all be in this file. For the purposes
2599 # of illustration only, we implement each command in a separate module.
2600 try:
2601 mod = importlib.import_module(options.command)
2602 cmd = getattr(mod, 'command')
2603 except (ImportError, AttributeError):
2604 print('Unable to find the code for command \'%s\'' % options.command)
2605 return 1
2606 # Could get fancy here and load configuration from file or dictionary
2607 logging.basicConfig(level=options.log_level,
2608 format='%(levelname)s %(name)s %(message)s')
2609 cmd(options)
2610
2611 if __name__ == '__main__':
2612 sys.exit(main())
2613
2614And the ``start``, ``stop`` and ``restart`` commands can be implemented in
2615separate modules, like so for starting::
2616
2617 # start.py
2618 import logging
2619
2620 logger = logging.getLogger(__name__)
2621
2622 def command(options):
2623 logger.debug('About to start %s', options.name)
2624 # actually do the command processing here ...
2625 logger.info('Started the \'%s\' service.', options.name)
2626
2627and thus for stopping::
2628
2629 # stop.py
2630 import logging
2631
2632 logger = logging.getLogger(__name__)
2633
2634 def command(options):
2635 n = len(options.names)
2636 if n == 1:
2637 plural = ''
2638 services = '\'%s\'' % options.names[0]
2639 else:
2640 plural = 's'
2641 services = ', '.join('\'%s\'' % name for name in options.names)
2642 i = services.rfind(', ')
2643 services = services[:i] + ' and ' + services[i + 2:]
2644 logger.debug('About to stop %s', services)
2645 # actually do the command processing here ...
2646 logger.info('Stopped the %s service%s.', services, plural)
2647
2648and similarly for restarting::
2649
2650 # restart.py
2651 import logging
2652
2653 logger = logging.getLogger(__name__)
2654
2655 def command(options):
2656 n = len(options.names)
2657 if n == 1:
2658 plural = ''
2659 services = '\'%s\'' % options.names[0]
2660 else:
2661 plural = 's'
2662 services = ', '.join('\'%s\'' % name for name in options.names)
2663 i = services.rfind(', ')
2664 services = services[:i] + ' and ' + services[i + 2:]
2665 logger.debug('About to restart %s', services)
2666 # actually do the command processing here ...
2667 logger.info('Restarted the %s service%s.', services, plural)
2668
2669If we run this application with the default log level, we get output like this:
2670
2671.. code-block:: shell-session
2672
2673 $ python app.py start foo
2674 INFO start Started the 'foo' service.
2675
2676 $ python app.py stop foo bar
2677 INFO stop Stopped the 'foo' and 'bar' services.
2678
2679 $ python app.py restart foo bar baz
2680 INFO restart Restarted the 'foo', 'bar' and 'baz' services.
2681
2682The first word is the logging level, and the second word is the module or
2683package name of the place where the event was logged.
2684
2685If we change the logging level, then we can change the information sent to the
2686log. For example, if we want more information:
2687
2688.. code-block:: shell-session
2689
2690 $ python app.py --log-level DEBUG start foo
2691 DEBUG start About to start foo
2692 INFO start Started the 'foo' service.
2693
2694 $ python app.py --log-level DEBUG stop foo bar
2695 DEBUG stop About to stop 'foo' and 'bar'
2696 INFO stop Stopped the 'foo' and 'bar' services.
2697
2698 $ python app.py --log-level DEBUG restart foo bar baz
2699 DEBUG restart About to restart 'foo', 'bar' and 'baz'
2700 INFO restart Restarted the 'foo', 'bar' and 'baz' services.
2701
2702And if we want less:
2703
2704.. code-block:: shell-session
2705
2706 $ python app.py --log-level WARNING start foo
2707 $ python app.py --log-level WARNING stop foo bar
2708 $ python app.py --log-level WARNING restart foo bar baz
2709
2710In this case, the commands don't print anything to the console, since nothing
2711at ``WARNING`` level or above is logged by them.