blob: f962cd8872bc82d2e6743df82abc00c6afe17902 [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
75The output looks like this::
76
77 2005-03-23 23:47:11,663 - spam_application - INFO -
78 creating an instance of auxiliary_module.Auxiliary
79 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
80 creating an instance of Auxiliary
81 2005-03-23 23:47:11,665 - spam_application - INFO -
82 created an instance of auxiliary_module.Auxiliary
83 2005-03-23 23:47:11,668 - spam_application - INFO -
84 calling auxiliary_module.Auxiliary.do_something
85 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
86 doing something
87 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
88 done doing something
89 2005-03-23 23:47:11,670 - spam_application - INFO -
90 finished auxiliary_module.Auxiliary.do_something
91 2005-03-23 23:47:11,671 - spam_application - INFO -
92 calling auxiliary_module.some_function()
93 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
94 received a call to 'some_function'
95 2005-03-23 23:47:11,673 - spam_application - INFO -
96 done with auxiliary_module.some_function()
97
Vinay Sajipe10d3702016-02-20 19:02:46 +000098Logging from multiple threads
99-----------------------------
100
101Logging from multiple threads requires no special effort. The following example
Berker Peksag563c9492016-03-20 12:50:56 +0200102shows logging from the main (initial) thread and another thread::
Vinay Sajipe10d3702016-02-20 19:02:46 +0000103
104 import logging
105 import threading
106 import time
107
108 def worker(arg):
109 while not arg['stop']:
110 logging.debug('Hi from myfunc')
111 time.sleep(0.5)
112
113 def main():
114 logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
115 info = {'stop': False}
116 thread = threading.Thread(target=worker, args=(info,))
117 thread.start()
118 while True:
119 try:
120 logging.debug('Hello from main')
121 time.sleep(0.75)
122 except KeyboardInterrupt:
123 info['stop'] = True
124 break
125 thread.join()
126
127 if __name__ == '__main__':
128 main()
129
130When run, the script should print something like the following::
131
132 0 Thread-1 Hi from myfunc
133 3 MainThread Hello from main
134 505 Thread-1 Hi from myfunc
135 755 MainThread Hello from main
136 1007 Thread-1 Hi from myfunc
137 1507 MainThread Hello from main
138 1508 Thread-1 Hi from myfunc
139 2010 Thread-1 Hi from myfunc
140 2258 MainThread Hello from main
141 2512 Thread-1 Hi from myfunc
142 3009 MainThread Hello from main
143 3013 Thread-1 Hi from myfunc
144 3515 Thread-1 Hi from myfunc
145 3761 MainThread Hello from main
146 4017 Thread-1 Hi from myfunc
147 4513 MainThread Hello from main
148 4518 Thread-1 Hi from myfunc
149
150This shows the logging output interspersed as one might expect. This approach
151works for more threads than shown here, of course.
152
Vinay Sajipc63619b2010-12-19 12:56:57 +0000153Multiple handlers and formatters
154--------------------------------
155
Vinay Sajip67f39772013-08-17 00:39:42 +0100156Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has no
157minimum or maximum quota for the number of handlers you may add. Sometimes it
158will be beneficial for an application to log all messages of all severities to a
159text file while simultaneously logging errors or above to the console. To set
160this up, simply configure the appropriate handlers. The logging calls in the
Vinay Sajipc63619b2010-12-19 12:56:57 +0000161application code will remain unchanged. Here is a slight modification to the
162previous simple module-based configuration example::
163
164 import logging
165
166 logger = logging.getLogger('simple_example')
167 logger.setLevel(logging.DEBUG)
168 # create file handler which logs even debug messages
169 fh = logging.FileHandler('spam.log')
170 fh.setLevel(logging.DEBUG)
171 # create console handler with a higher log level
172 ch = logging.StreamHandler()
173 ch.setLevel(logging.ERROR)
174 # create formatter and add it to the handlers
175 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
176 ch.setFormatter(formatter)
177 fh.setFormatter(formatter)
178 # add the handlers to logger
179 logger.addHandler(ch)
180 logger.addHandler(fh)
181
182 # 'application' code
183 logger.debug('debug message')
184 logger.info('info message')
185 logger.warn('warn message')
186 logger.error('error message')
187 logger.critical('critical message')
188
189Notice that the 'application' code does not care about multiple handlers. All
190that changed was the addition and configuration of a new handler named *fh*.
191
192The ability to create new handlers with higher- or lower-severity filters can be
193very helpful when writing and testing an application. Instead of using many
194``print`` statements for debugging, use ``logger.debug``: Unlike the print
195statements, which you will have to delete or comment out later, the logger.debug
196statements can remain intact in the source code and remain dormant until you
197need them again. At that time, the only change that needs to happen is to
198modify the severity level of the logger and/or handler to debug.
199
200.. _multiple-destinations:
201
202Logging to multiple destinations
203--------------------------------
204
205Let's say you want to log to console and file with different message formats and
206in differing circumstances. Say you want to log messages with levels of DEBUG
207and higher to file, and those messages at level INFO and higher to the console.
208Let's also assume that the file should contain timestamps, but the console
209messages should not. Here's how you can achieve this::
210
211 import logging
212
213 # set up logging to file - see previous section for more details
214 logging.basicConfig(level=logging.DEBUG,
215 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
216 datefmt='%m-%d %H:%M',
217 filename='/temp/myapp.log',
218 filemode='w')
219 # define a Handler which writes INFO messages or higher to the sys.stderr
220 console = logging.StreamHandler()
221 console.setLevel(logging.INFO)
222 # set a format which is simpler for console use
223 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
224 # tell the handler to use this format
225 console.setFormatter(formatter)
226 # add the handler to the root logger
227 logging.getLogger('').addHandler(console)
228
229 # Now, we can log to the root logger, or any other logger. First the root...
230 logging.info('Jackdaws love my big sphinx of quartz.')
231
232 # Now, define a couple of other loggers which might represent areas in your
233 # application:
234
235 logger1 = logging.getLogger('myapp.area1')
236 logger2 = logging.getLogger('myapp.area2')
237
238 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
239 logger1.info('How quickly daft jumping zebras vex.')
240 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
241 logger2.error('The five boxing wizards jump quickly.')
242
243When you run this, on the console you will see ::
244
245 root : INFO Jackdaws love my big sphinx of quartz.
246 myapp.area1 : INFO How quickly daft jumping zebras vex.
247 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
248 myapp.area2 : ERROR The five boxing wizards jump quickly.
249
250and in the file you will see something like ::
251
252 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
253 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
254 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
255 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
256 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
257
258As you can see, the DEBUG message only shows up in the file. The other messages
259are sent to both destinations.
260
261This example uses console and file handlers, but you can use any number and
262combination of handlers you choose.
263
264
265Configuration server example
266----------------------------
267
268Here is an example of a module using the logging configuration server::
269
270 import logging
271 import logging.config
272 import time
273 import os
274
275 # read initial config file
276 logging.config.fileConfig('logging.conf')
277
278 # create and start listener on port 9999
279 t = logging.config.listen(9999)
280 t.start()
281
282 logger = logging.getLogger('simpleExample')
283
284 try:
285 # loop through logging calls to see the difference
286 # new configurations make, until Ctrl+C is pressed
287 while True:
288 logger.debug('debug message')
289 logger.info('info message')
290 logger.warn('warn message')
291 logger.error('error message')
292 logger.critical('critical message')
293 time.sleep(5)
294 except KeyboardInterrupt:
295 # cleanup
296 logging.config.stopListening()
297 t.join()
298
299And here is a script that takes a filename and sends that file to the server,
300properly preceded with the binary-encoded length, as the new logging
301configuration::
302
303 #!/usr/bin/env python
304 import socket, sys, struct
305
Vinay Sajip689b68a2010-12-22 15:04:15 +0000306 with open(sys.argv[1], 'rb') as f:
307 data_to_send = f.read()
Vinay Sajipc63619b2010-12-19 12:56:57 +0000308
309 HOST = 'localhost'
310 PORT = 9999
311 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
312 print('connecting...')
313 s.connect((HOST, PORT))
314 print('sending config...')
315 s.send(struct.pack('>L', len(data_to_send)))
316 s.send(data_to_send)
317 s.close()
318 print('complete')
319
320
321Dealing with handlers that block
322--------------------------------
323
324.. currentmodule:: logging.handlers
325
326Sometimes you have to get your logging handlers to do their work without
Vinay Sajip6b883a22012-02-27 11:02:45 +0000327blocking the thread you're logging from. This is common in Web applications,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000328though of course it also occurs in other scenarios.
329
330A common culprit which demonstrates sluggish behaviour is the
331:class:`SMTPHandler`: sending emails can take a long time, for a
Vinay Sajip6b883a22012-02-27 11:02:45 +0000332number of reasons outside the developer's control (for example, a poorly
Vinay Sajipc63619b2010-12-19 12:56:57 +0000333performing mail or network infrastructure). But almost any network-based
334handler can block: Even a :class:`SocketHandler` operation may do a
335DNS query under the hood which is too slow (and this query can be deep in the
336socket library code, below the Python layer, and outside your control).
337
338One solution is to use a two-part approach. For the first part, attach only a
339:class:`QueueHandler` to those loggers which are accessed from
340performance-critical threads. They simply write to their queue, which can be
341sized to a large enough capacity or initialized with no upper bound to their
342size. The write to the queue will typically be accepted quickly, though you
Georg Brandl375aec22011-01-15 17:03:02 +0000343will probably need to catch the :exc:`queue.Full` exception as a precaution
Vinay Sajipc63619b2010-12-19 12:56:57 +0000344in your code. If you are a library developer who has performance-critical
345threads in their code, be sure to document this (together with a suggestion to
346attach only ``QueueHandlers`` to your loggers) for the benefit of other
347developers who will use your code.
348
349The second part of the solution is :class:`QueueListener`, which has been
350designed as the counterpart to :class:`QueueHandler`. A
Vinay Sajip6b883a22012-02-27 11:02:45 +0000351:class:`QueueListener` is very simple: it's passed a queue and some handlers,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000352and it fires up an internal thread which listens to its queue for LogRecords
353sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
354matter). The ``LogRecords`` are removed from the queue and passed to the
355handlers for processing.
356
357The advantage of having a separate :class:`QueueListener` class is that you
358can use the same instance to service multiple ``QueueHandlers``. This is more
359resource-friendly than, say, having threaded versions of the existing handler
360classes, which would eat up one thread per handler for no particular benefit.
361
362An example of using these two classes follows (imports omitted)::
363
Serhiy Storchakadba90392016-05-10 12:01:23 +0300364 que = queue.Queue(-1) # no limit on size
Vinay Sajipc63619b2010-12-19 12:56:57 +0000365 queue_handler = QueueHandler(que)
366 handler = logging.StreamHandler()
367 listener = QueueListener(que, handler)
368 root = logging.getLogger()
369 root.addHandler(queue_handler)
370 formatter = logging.Formatter('%(threadName)s: %(message)s')
371 handler.setFormatter(formatter)
372 listener.start()
373 # The log output will display the thread which generated
374 # the event (the main thread) rather than the internal
375 # thread which monitors the internal queue. This is what
376 # you want to happen.
377 root.warning('Look out!')
378 listener.stop()
379
Martin Panter1050d2d2016-07-26 11:18:21 +0200380which, when run, will produce:
381
382.. code-block:: none
Vinay Sajipc63619b2010-12-19 12:56:57 +0000383
384 MainThread: Look out!
385
Vinay Sajip365701a2015-02-09 19:49:00 +0000386.. versionchanged:: 3.5
387 Prior to Python 3.5, the :class:`QueueListener` always passed every message
388 received from the queue to every handler it was initialized with. (This was
389 because it was assumed that level filtering was all done on the other side,
390 where the queue is filled.) From 3.5 onwards, this behaviour can be changed
391 by passing a keyword argument ``respect_handler_level=True`` to the
392 listener's constructor. When this is done, the listener compares the level
393 of each message with the handler's level, and only passes a message to a
394 handler if it's appropriate to do so.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000395
396.. _network-logging:
397
398Sending and receiving logging events across a network
399-----------------------------------------------------
400
401Let's say you want to send logging events across a network, and handle them at
402the receiving end. A simple way of doing this is attaching a
403:class:`SocketHandler` instance to the root logger at the sending end::
404
405 import logging, logging.handlers
406
407 rootLogger = logging.getLogger('')
408 rootLogger.setLevel(logging.DEBUG)
409 socketHandler = logging.handlers.SocketHandler('localhost',
410 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
411 # don't bother with a formatter, since a socket handler sends the event as
412 # an unformatted pickle
413 rootLogger.addHandler(socketHandler)
414
415 # Now, we can log to the root logger, or any other logger. First the root...
416 logging.info('Jackdaws love my big sphinx of quartz.')
417
418 # Now, define a couple of other loggers which might represent areas in your
419 # application:
420
421 logger1 = logging.getLogger('myapp.area1')
422 logger2 = logging.getLogger('myapp.area2')
423
424 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
425 logger1.info('How quickly daft jumping zebras vex.')
426 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
427 logger2.error('The five boxing wizards jump quickly.')
428
429At the receiving end, you can set up a receiver using the :mod:`socketserver`
430module. Here is a basic working example::
431
432 import pickle
433 import logging
434 import logging.handlers
435 import socketserver
436 import struct
437
438
439 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
440 """Handler for a streaming logging request.
441
442 This basically logs the record using whatever logging policy is
443 configured locally.
444 """
445
446 def handle(self):
447 """
448 Handle multiple requests - each expected to be a 4-byte length,
449 followed by the LogRecord in pickle format. Logs the record
450 according to whatever policy is configured locally.
451 """
452 while True:
453 chunk = self.connection.recv(4)
454 if len(chunk) < 4:
455 break
456 slen = struct.unpack('>L', chunk)[0]
457 chunk = self.connection.recv(slen)
458 while len(chunk) < slen:
459 chunk = chunk + self.connection.recv(slen - len(chunk))
460 obj = self.unPickle(chunk)
461 record = logging.makeLogRecord(obj)
462 self.handleLogRecord(record)
463
464 def unPickle(self, data):
465 return pickle.loads(data)
466
467 def handleLogRecord(self, record):
468 # if a name is specified, we use the named logger rather than the one
469 # implied by the record.
470 if self.server.logname is not None:
471 name = self.server.logname
472 else:
473 name = record.name
474 logger = logging.getLogger(name)
475 # N.B. EVERY record gets logged. This is because Logger.handle
476 # is normally called AFTER logger-level filtering. If you want
477 # to do filtering, do it at the client end to save wasting
478 # cycles and network bandwidth!
479 logger.handle(record)
480
481 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
482 """
483 Simple TCP socket-based logging receiver suitable for testing.
484 """
485
Raymond Hettinger4ab532b2014-03-28 16:39:25 -0700486 allow_reuse_address = True
Vinay Sajipc63619b2010-12-19 12:56:57 +0000487
488 def __init__(self, host='localhost',
489 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
490 handler=LogRecordStreamHandler):
491 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
492 self.abort = 0
493 self.timeout = 1
494 self.logname = None
495
496 def serve_until_stopped(self):
497 import select
498 abort = 0
499 while not abort:
500 rd, wr, ex = select.select([self.socket.fileno()],
501 [], [],
502 self.timeout)
503 if rd:
504 self.handle_request()
505 abort = self.abort
506
507 def main():
508 logging.basicConfig(
509 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
510 tcpserver = LogRecordSocketReceiver()
511 print('About to start TCP server...')
512 tcpserver.serve_until_stopped()
513
514 if __name__ == '__main__':
515 main()
516
517First run the server, and then the client. On the client side, nothing is
518printed on the console; on the server side, you should see something like::
519
520 About to start TCP server...
521 59 root INFO Jackdaws love my big sphinx of quartz.
522 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
523 69 myapp.area1 INFO How quickly daft jumping zebras vex.
524 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
525 69 myapp.area2 ERROR The five boxing wizards jump quickly.
526
527Note that there are some security issues with pickle in some scenarios. If
528these affect you, you can use an alternative serialization scheme by overriding
Vinay Sajip67f39772013-08-17 00:39:42 +0100529the :meth:`~handlers.SocketHandler.makePickle` method and implementing your
530alternative there, as well as adapting the above script to use your alternative
531serialization.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000532
533
534.. _context-info:
535
536Adding contextual information to your logging output
537----------------------------------------------------
538
539Sometimes you want logging output to contain contextual information in
540addition to the parameters passed to the logging call. For example, in a
541networked application, it may be desirable to log client-specific information
542in the log (e.g. remote client's username, or IP address). Although you could
543use the *extra* parameter to achieve this, it's not always convenient to pass
544the information in this way. While it might be tempting to create
545:class:`Logger` instances on a per-connection basis, this is not a good idea
546because these instances are not garbage collected. While this is not a problem
547in practice, when the number of :class:`Logger` instances is dependent on the
548level of granularity you want to use in logging an application, it could
549be hard to manage if the number of :class:`Logger` instances becomes
550effectively unbounded.
551
552
553Using LoggerAdapters to impart contextual information
554^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
555
556An easy way in which you can pass contextual information to be output along
557with logging event information is to use the :class:`LoggerAdapter` class.
558This class is designed to look like a :class:`Logger`, so that you can call
559:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
560:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
561same signatures as their counterparts in :class:`Logger`, so you can use the
562two types of instances interchangeably.
563
564When you create an instance of :class:`LoggerAdapter`, you pass it a
565:class:`Logger` instance and a dict-like object which contains your contextual
566information. When you call one of the logging methods on an instance of
567:class:`LoggerAdapter`, it delegates the call to the underlying instance of
568:class:`Logger` passed to its constructor, and arranges to pass the contextual
569information in the delegated call. Here's a snippet from the code of
570:class:`LoggerAdapter`::
571
572 def debug(self, msg, *args, **kwargs):
573 """
574 Delegate a debug call to the underlying logger, after adding
575 contextual information from this adapter instance.
576 """
577 msg, kwargs = self.process(msg, kwargs)
578 self.logger.debug(msg, *args, **kwargs)
579
Vinay Sajip67f39772013-08-17 00:39:42 +0100580The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the
581contextual information is added to the logging output. It's passed the message
582and keyword arguments of the logging call, and it passes back (potentially)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000583modified versions of these to use in the call to the underlying logger. The
584default implementation of this method leaves the message alone, but inserts
585an 'extra' key in the keyword argument whose value is the dict-like object
586passed to the constructor. Of course, if you had passed an 'extra' keyword
587argument in the call to the adapter, it will be silently overwritten.
588
589The advantage of using 'extra' is that the values in the dict-like object are
590merged into the :class:`LogRecord` instance's __dict__, allowing you to use
591customized strings with your :class:`Formatter` instances which know about
592the keys of the dict-like object. If you need a different method, e.g. if you
593want to prepend or append the contextual information to the message string,
Vinay Sajip67f39772013-08-17 00:39:42 +0100594you just need to subclass :class:`LoggerAdapter` and override
595:meth:`~LoggerAdapter.process` to do what you need. Here is a simple example::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000596
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100597 class CustomAdapter(logging.LoggerAdapter):
598 """
599 This example adapter expects the passed in dict-like object to have a
600 'connid' key, whose value in brackets is prepended to the log message.
601 """
602 def process(self, msg, kwargs):
603 return '[%s] %s' % (self.extra['connid'], msg), kwargs
Vinay Sajipc63619b2010-12-19 12:56:57 +0000604
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100605which you can use like this::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000606
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100607 logger = logging.getLogger(__name__)
608 adapter = CustomAdapter(logger, {'connid': some_conn_id})
Vinay Sajipc63619b2010-12-19 12:56:57 +0000609
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100610Then any events that you log to the adapter will have the value of
611``some_conn_id`` prepended to the log messages.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000612
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100613Using objects other than dicts to pass contextual information
614~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vinay Sajipc63619b2010-12-19 12:56:57 +0000615
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100616You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could
617pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so
618that it looks like a dict to logging. This would be useful if you want to
619generate values dynamically (whereas the values in a dict would be constant).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000620
621
622.. _filters-contextual:
623
624Using Filters to impart contextual information
625^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
626
627You can also add contextual information to log output using a user-defined
628:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
629passed to them, including adding additional attributes which can then be output
630using a suitable format string, or if needed a custom :class:`Formatter`.
631
632For example in a web application, the request being processed (or at least,
633the interesting parts of it) can be stored in a threadlocal
634(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
635add, say, information from the request - say, the remote IP address and remote
636user's username - to the ``LogRecord``, using the attribute names 'ip' and
637'user' as in the ``LoggerAdapter`` example above. In that case, the same format
638string can be used to get similar output to that shown above. Here's an example
639script::
640
641 import logging
642 from random import choice
643
644 class ContextFilter(logging.Filter):
645 """
646 This is a filter which injects contextual information into the log.
647
648 Rather than use actual contextual information, we just use random
649 data in this demo.
650 """
651
652 USERS = ['jim', 'fred', 'sheila']
653 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
654
655 def filter(self, record):
656
657 record.ip = choice(ContextFilter.IPS)
658 record.user = choice(ContextFilter.USERS)
659 return True
660
661 if __name__ == '__main__':
Serhiy Storchakadba90392016-05-10 12:01:23 +0300662 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
663 logging.basicConfig(level=logging.DEBUG,
664 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
665 a1 = logging.getLogger('a.b.c')
666 a2 = logging.getLogger('d.e.f')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000667
Serhiy Storchakadba90392016-05-10 12:01:23 +0300668 f = ContextFilter()
669 a1.addFilter(f)
670 a2.addFilter(f)
671 a1.debug('A debug message')
672 a1.info('An info message with %s', 'some parameters')
673 for x in range(10):
674 lvl = choice(levels)
675 lvlname = logging.getLevelName(lvl)
676 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000677
678which, when run, produces something like::
679
680 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
681 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
682 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
683 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
684 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
685 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
686 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
687 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
688 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
689 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
690 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
691 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
692
693
694.. _multiple-processes:
695
696Logging to a single file from multiple processes
697------------------------------------------------
698
699Although logging is thread-safe, and logging to a single file from multiple
700threads in a single process *is* supported, logging to a single file from
701*multiple processes* is *not* supported, because there is no standard way to
702serialize access to a single file across multiple processes in Python. If you
703need to log to a single file from multiple processes, one way of doing this is
Vinay Sajip67f39772013-08-17 00:39:42 +0100704to have all the processes log to a :class:`~handlers.SocketHandler`, and have a
705separate process which implements a socket server which reads from the socket
706and logs to file. (If you prefer, you can dedicate one thread in one of the
707existing processes to perform this function.)
708:ref:`This section <network-logging>` documents this approach in more detail and
709includes a working socket receiver which can be used as a starting point for you
710to adapt in your own applications.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000711
712If you are using a recent version of Python which includes the
713:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip67f39772013-08-17 00:39:42 +0100714:class:`~multiprocessing.Lock` class from this module to serialize access to the
715file from your processes. The existing :class:`FileHandler` and subclasses do
716not make use of :mod:`multiprocessing` at present, though they may do so in the
717future. Note that at present, the :mod:`multiprocessing` module does not provide
Vinay Sajipc63619b2010-12-19 12:56:57 +0000718working lock functionality on all platforms (see
Georg Brandle73778c2014-10-29 08:36:35 +0100719https://bugs.python.org/issue3770).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000720
721.. currentmodule:: logging.handlers
722
723Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
724all logging events to one of the processes in your multi-process application.
725The following example script demonstrates how you can do this; in the example
726a separate listener process listens for events sent by other processes and logs
727them according to its own logging configuration. Although the example only
728demonstrates one way of doing it (for example, you may want to use a listener
Georg Brandl7a0afd32011-02-07 15:44:27 +0000729thread rather than a separate listener process -- the implementation would be
Vinay Sajipc63619b2010-12-19 12:56:57 +0000730analogous) it does allow for completely different logging configurations for
731the listener and the other processes in your application, and can be used as
732the basis for code meeting your own specific requirements::
733
734 # You'll need these imports in your own code
735 import logging
736 import logging.handlers
737 import multiprocessing
738
739 # Next two import lines for this demo only
740 from random import choice, random
741 import time
742
743 #
744 # Because you'll want to define the logging configurations for listener and workers, the
745 # listener and worker process functions take a configurer parameter which is a callable
746 # for configuring logging for that process. These functions are also passed the queue,
747 # which they use for communication.
748 #
749 # In practice, you can configure the listener however you want, but note that in this
750 # simple example, the listener does not apply level or filter logic to received records.
Georg Brandl7a0afd32011-02-07 15:44:27 +0000751 # In practice, you would probably want to do this logic in the worker processes, to avoid
Vinay Sajipc63619b2010-12-19 12:56:57 +0000752 # sending events which would be filtered out between processes.
753 #
754 # The size of the rotated files is made small so you can see the results easily.
755 def listener_configurer():
756 root = logging.getLogger()
Raymond Hettingerb34705f2011-06-26 15:29:06 +0200757 h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000758 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
759 h.setFormatter(f)
760 root.addHandler(h)
761
762 # This is the listener process top-level loop: wait for logging events
763 # (LogRecords)on the queue and handle them, quit when you get a None for a
764 # LogRecord.
765 def listener_process(queue, configurer):
766 configurer()
767 while True:
768 try:
769 record = queue.get()
Serhiy Storchakadba90392016-05-10 12:01:23 +0300770 if record is None: # We send this as a sentinel to tell the listener to quit.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000771 break
772 logger = logging.getLogger(record.name)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300773 logger.handle(record) # No level or filter logic applied - just do it!
Andrew Svetlov47395612012-11-02 22:07:26 +0200774 except Exception:
Vinay Sajipc63619b2010-12-19 12:56:57 +0000775 import sys, traceback
Vinay Sajip6b883a22012-02-27 11:02:45 +0000776 print('Whoops! Problem:', file=sys.stderr)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000777 traceback.print_exc(file=sys.stderr)
778
779 # Arrays used for random selections in this demo
780
781 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
782 logging.ERROR, logging.CRITICAL]
783
784 LOGGERS = ['a.b.c', 'd.e.f']
785
786 MESSAGES = [
787 'Random message #1',
788 'Random message #2',
789 'Random message #3',
790 ]
791
792 # The worker configuration is done at the start of the worker process run.
793 # Note that on Windows you can't rely on fork semantics, so each process
794 # will run the logging configuration code when it starts.
795 def worker_configurer(queue):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300796 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
Vinay Sajipc63619b2010-12-19 12:56:57 +0000797 root = logging.getLogger()
798 root.addHandler(h)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300799 # send all messages, for demo; no other level or filter logic applied.
800 root.setLevel(logging.DEBUG)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000801
802 # This is the worker process top-level loop, which just logs ten events with
803 # random intervening delays before terminating.
804 # The print messages are just so you know it's doing something!
805 def worker_process(queue, configurer):
806 configurer(queue)
807 name = multiprocessing.current_process().name
808 print('Worker started: %s' % name)
809 for i in range(10):
810 time.sleep(random())
811 logger = logging.getLogger(choice(LOGGERS))
812 level = choice(LEVELS)
813 message = choice(MESSAGES)
814 logger.log(level, message)
815 print('Worker finished: %s' % name)
816
817 # Here's where the demo gets orchestrated. Create the queue, create and start
818 # the listener, create ten workers and start them, wait for them to finish,
819 # then send a None to the queue to tell the listener to finish.
820 def main():
821 queue = multiprocessing.Queue(-1)
822 listener = multiprocessing.Process(target=listener_process,
823 args=(queue, listener_configurer))
824 listener.start()
825 workers = []
826 for i in range(10):
827 worker = multiprocessing.Process(target=worker_process,
Serhiy Storchakadba90392016-05-10 12:01:23 +0300828 args=(queue, worker_configurer))
Vinay Sajipc63619b2010-12-19 12:56:57 +0000829 workers.append(worker)
830 worker.start()
831 for w in workers:
832 w.join()
833 queue.put_nowait(None)
834 listener.join()
835
836 if __name__ == '__main__':
837 main()
838
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000839A variant of the above script keeps the logging in the main process, in a
840separate thread::
841
842 import logging
843 import logging.config
844 import logging.handlers
845 from multiprocessing import Process, Queue
846 import random
847 import threading
848 import time
849
850 def logger_thread(q):
851 while True:
852 record = q.get()
853 if record is None:
854 break
855 logger = logging.getLogger(record.name)
856 logger.handle(record)
857
858
859 def worker_process(q):
860 qh = logging.handlers.QueueHandler(q)
861 root = logging.getLogger()
862 root.setLevel(logging.DEBUG)
863 root.addHandler(qh)
864 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
865 logging.CRITICAL]
866 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
867 'spam', 'spam.ham', 'spam.ham.eggs']
868 for i in range(100):
869 lvl = random.choice(levels)
870 logger = logging.getLogger(random.choice(loggers))
871 logger.log(lvl, 'Message no. %d', i)
872
873 if __name__ == '__main__':
874 q = Queue()
875 d = {
876 'version': 1,
877 'formatters': {
878 'detailed': {
879 'class': 'logging.Formatter',
880 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
881 }
882 },
883 'handlers': {
884 'console': {
885 'class': 'logging.StreamHandler',
886 'level': 'INFO',
887 },
888 'file': {
889 'class': 'logging.FileHandler',
890 'filename': 'mplog.log',
891 'mode': 'w',
892 'formatter': 'detailed',
893 },
894 'foofile': {
895 'class': 'logging.FileHandler',
896 'filename': 'mplog-foo.log',
897 'mode': 'w',
898 'formatter': 'detailed',
899 },
900 'errors': {
901 'class': 'logging.FileHandler',
902 'filename': 'mplog-errors.log',
903 'mode': 'w',
904 'level': 'ERROR',
905 'formatter': 'detailed',
906 },
907 },
908 'loggers': {
909 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200910 'handlers': ['foofile']
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000911 }
912 },
913 'root': {
914 'level': 'DEBUG',
915 'handlers': ['console', 'file', 'errors']
916 },
917 }
918 workers = []
919 for i in range(5):
920 wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
921 workers.append(wp)
922 wp.start()
923 logging.config.dictConfig(d)
924 lp = threading.Thread(target=logger_thread, args=(q,))
925 lp.start()
926 # At this point, the main process could do some useful work of its own
927 # Once it's done that, it can wait for the workers to terminate...
928 for wp in workers:
929 wp.join()
930 # And now tell the logging thread to finish up, too
931 q.put(None)
932 lp.join()
933
934This variant shows how you can e.g. apply configuration for particular loggers
935- e.g. the ``foo`` logger has a special handler which stores all events in the
936``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging
937machinery in the main process (even though the logging events are generated in
938the worker processes) to direct the messages to the appropriate destinations.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000939
940Using file rotation
941-------------------
942
943.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
944.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
945
946Sometimes you want to let a log file grow to a certain size, then open a new
947file and log to that. You may want to keep a certain number of these files, and
948when that many files have been created, rotate the files so that the number of
Georg Brandl7a0afd32011-02-07 15:44:27 +0000949files and the size of the files both remain bounded. For this usage pattern, the
Vinay Sajip67f39772013-08-17 00:39:42 +0100950logging package provides a :class:`~handlers.RotatingFileHandler`::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000951
952 import glob
953 import logging
954 import logging.handlers
955
956 LOG_FILENAME = 'logging_rotatingfile_example.out'
957
958 # Set up a specific logger with our desired output level
959 my_logger = logging.getLogger('MyLogger')
960 my_logger.setLevel(logging.DEBUG)
961
962 # Add the log message handler to the logger
963 handler = logging.handlers.RotatingFileHandler(
964 LOG_FILENAME, maxBytes=20, backupCount=5)
965
966 my_logger.addHandler(handler)
967
968 # Log some messages
969 for i in range(20):
970 my_logger.debug('i = %d' % i)
971
972 # See what files are created
973 logfiles = glob.glob('%s*' % LOG_FILENAME)
974
975 for filename in logfiles:
976 print(filename)
977
978The result should be 6 separate files, each with part of the log history for the
979application::
980
981 logging_rotatingfile_example.out
982 logging_rotatingfile_example.out.1
983 logging_rotatingfile_example.out.2
984 logging_rotatingfile_example.out.3
985 logging_rotatingfile_example.out.4
986 logging_rotatingfile_example.out.5
987
988The most current file is always :file:`logging_rotatingfile_example.out`,
989and each time it reaches the size limit it is renamed with the suffix
990``.1``. Each of the existing backup files is renamed to increment the suffix
991(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
992
Ezio Melottie130a522011-10-19 10:58:56 +0300993Obviously this example sets the log length much too small as an extreme
Vinay Sajipc63619b2010-12-19 12:56:57 +0000994example. You would want to set *maxBytes* to an appropriate value.
995
Vinay Sajip6b883a22012-02-27 11:02:45 +0000996.. _format-styles:
997
998Use of alternative formatting styles
999------------------------------------
1000
1001When logging was added to the Python standard library, the only way of
1002formatting messages with variable content was to use the %-formatting
1003method. Since then, Python has gained two new formatting approaches:
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001004:class:`string.Template` (added in Python 2.4) and :meth:`str.format`
1005(added in Python 2.6).
Vinay Sajip6b883a22012-02-27 11:02:45 +00001006
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001007Logging (as of 3.2) provides improved support for these two additional
1008formatting styles. The :class:`Formatter` class been enhanced to take an
1009additional, optional keyword parameter named ``style``. This defaults to
1010``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond
Vinay Sajip6b883a22012-02-27 11:02:45 +00001011to the other two formatting styles. Backwards compatibility is maintained by
1012default (as you would expect), but by explicitly specifying a style parameter,
1013you get the ability to specify format strings which work with
1014:meth:`str.format` or :class:`string.Template`. Here's an example console
1015session to show the possibilities:
1016
1017.. code-block:: pycon
1018
1019 >>> import logging
1020 >>> root = logging.getLogger()
1021 >>> root.setLevel(logging.DEBUG)
1022 >>> handler = logging.StreamHandler()
1023 >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
1024 ... style='{')
1025 >>> handler.setFormatter(bf)
1026 >>> root.addHandler(handler)
1027 >>> logger = logging.getLogger('foo.bar')
1028 >>> logger.debug('This is a DEBUG message')
1029 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message
1030 >>> logger.critical('This is a CRITICAL message')
1031 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
1032 >>> df = logging.Formatter('$asctime $name ${levelname} $message',
1033 ... style='$')
1034 >>> handler.setFormatter(df)
1035 >>> logger.debug('This is a DEBUG message')
1036 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
1037 >>> logger.critical('This is a CRITICAL message')
1038 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
1039 >>>
1040
1041Note that the formatting of logging messages for final output to logs is
1042completely independent of how an individual logging message is constructed.
1043That can still use %-formatting, as shown here::
1044
1045 >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
1046 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
1047 >>>
1048
1049Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take
1050positional parameters for the actual logging message itself, with keyword
1051parameters used only for determining options for how to handle the actual
1052logging call (e.g. the ``exc_info`` keyword parameter to indicate that
1053traceback information should be logged, or the ``extra`` keyword parameter
1054to indicate additional contextual information to be added to the log). So
1055you cannot directly make logging calls using :meth:`str.format` or
1056:class:`string.Template` syntax, because internally the logging package
1057uses %-formatting to merge the format string and the variable arguments.
1058There would no changing this while preserving backward compatibility, since
1059all logging calls which are out there in existing code will be using %-format
1060strings.
1061
1062There is, however, a way that you can use {}- and $- formatting to construct
1063your individual log messages. Recall that for a message you can use an
1064arbitrary object as a message format string, and that the logging package will
1065call ``str()`` on that object to get the actual format string. Consider the
1066following two classes::
1067
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001068 class BraceMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001069 def __init__(self, fmt, *args, **kwargs):
1070 self.fmt = fmt
1071 self.args = args
1072 self.kwargs = kwargs
1073
1074 def __str__(self):
1075 return self.fmt.format(*self.args, **self.kwargs)
1076
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001077 class DollarMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001078 def __init__(self, fmt, **kwargs):
1079 self.fmt = fmt
1080 self.kwargs = kwargs
1081
1082 def __str__(self):
1083 from string import Template
1084 return Template(self.fmt).substitute(**self.kwargs)
1085
1086Either of these can be used in place of a format string, to allow {}- or
1087$-formatting to be used to build the actual "message" part which appears in the
1088formatted log output in place of "%(message)s" or "{message}" or "$message".
1089It's a little unwieldy to use the class names whenever you want to log
1090something, but it's quite palatable if you use an alias such as __ (double
Serhiy Storchaka29b0a262016-12-04 10:20:55 +02001091underscore --- not to be confused with _, the single underscore used as a
Vinay Sajip6b883a22012-02-27 11:02:45 +00001092synonym/alias for :func:`gettext.gettext` or its brethren).
1093
1094The above classes are not included in Python, though they're easy enough to
1095copy and paste into your own code. They can be used as follows (assuming that
1096they're declared in a module called ``wherever``):
1097
1098.. code-block:: pycon
1099
1100 >>> from wherever import BraceMessage as __
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001101 >>> print(__('Message with {0} {name}', 2, name='placeholders'))
Vinay Sajip6b883a22012-02-27 11:02:45 +00001102 Message with 2 placeholders
1103 >>> class Point: pass
1104 ...
1105 >>> p = Point()
1106 >>> p.x = 0.5
1107 >>> p.y = 0.5
1108 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
1109 ... point=p))
1110 Message with coordinates: (0.50, 0.50)
1111 >>> from wherever import DollarMessage as __
1112 >>> print(__('Message with $num $what', num=2, what='placeholders'))
1113 Message with 2 placeholders
1114 >>>
1115
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001116While the above examples use ``print()`` to show how the formatting works, you
1117would of course use ``logger.debug()`` or similar to actually log using this
1118approach.
1119
Vinay Sajip6b883a22012-02-27 11:02:45 +00001120One thing to note is that you pay no significant performance penalty with this
1121approach: the actual formatting happens not when you make the logging call, but
1122when (and if) the logged message is actually about to be output to a log by a
1123handler. So the only slightly unusual thing which might trip you up is that the
1124parentheses go around the format string and the arguments, not just the format
1125string. That's because the __ notation is just syntax sugar for a constructor
1126call to one of the XXXMessage classes.
1127
Vinay Sajip8028a5c2013-03-30 11:56:18 +00001128If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect
1129to the above, as in the following example::
1130
1131 import logging
1132
1133 class Message(object):
1134 def __init__(self, fmt, args):
1135 self.fmt = fmt
1136 self.args = args
1137
1138 def __str__(self):
1139 return self.fmt.format(*self.args)
1140
1141 class StyleAdapter(logging.LoggerAdapter):
1142 def __init__(self, logger, extra=None):
1143 super(StyleAdapter, self).__init__(logger, extra or {})
1144
1145 def log(self, level, msg, *args, **kwargs):
1146 if self.isEnabledFor(level):
1147 msg, kwargs = self.process(msg, kwargs)
1148 self.logger._log(level, Message(msg, args), (), **kwargs)
1149
1150 logger = StyleAdapter(logging.getLogger(__name__))
1151
1152 def main():
1153 logger.debug('Hello, {}', 'world!')
1154
1155 if __name__ == '__main__':
1156 logging.basicConfig(level=logging.DEBUG)
1157 main()
1158
1159The above script should log the message ``Hello, world!`` when run with
1160Python 3.2 or later.
1161
Vinay Sajip6b883a22012-02-27 11:02:45 +00001162
Vinay Sajip982f5342012-02-27 11:56:29 +00001163.. currentmodule:: logging
1164
Georg Brandle9983862012-02-28 08:21:40 +01001165.. _custom-logrecord:
Vinay Sajip982f5342012-02-27 11:56:29 +00001166
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001167Customizing ``LogRecord``
Vinay Sajip982f5342012-02-27 11:56:29 +00001168-------------------------
1169
1170Every logging event is represented by a :class:`LogRecord` instance.
1171When an event is logged and not filtered out by a logger's level, a
1172:class:`LogRecord` is created, populated with information about the event and
1173then passed to the handlers for that logger (and its ancestors, up to and
1174including the logger where further propagation up the hierarchy is disabled).
1175Before Python 3.2, there were only two places where this creation was done:
1176
1177* :meth:`Logger.makeRecord`, which is called in the normal process of
1178 logging an event. This invoked :class:`LogRecord` directly to create an
1179 instance.
1180* :func:`makeLogRecord`, which is called with a dictionary containing
1181 attributes to be added to the LogRecord. This is typically invoked when a
1182 suitable dictionary has been received over the network (e.g. in pickle form
1183 via a :class:`~handlers.SocketHandler`, or in JSON form via an
1184 :class:`~handlers.HTTPHandler`).
1185
1186This has usually meant that if you need to do anything special with a
1187:class:`LogRecord`, you've had to do one of the following.
1188
1189* Create your own :class:`Logger` subclass, which overrides
1190 :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass`
1191 before any loggers that you care about are instantiated.
1192* Add a :class:`Filter` to a logger or handler, which does the
1193 necessary special manipulation you need when its
1194 :meth:`~Filter.filter` method is called.
1195
1196The first approach would be a little unwieldy in the scenario where (say)
1197several different libraries wanted to do different things. Each would attempt
1198to set its own :class:`Logger` subclass, and the one which did this last would
1199win.
1200
1201The second approach works reasonably well for many cases, but does not allow
1202you to e.g. use a specialized subclass of :class:`LogRecord`. Library
1203developers can set a suitable filter on their loggers, but they would have to
1204remember to do this every time they introduced a new logger (which they would
Georg Brandle9983862012-02-28 08:21:40 +01001205do simply by adding new packages or modules and doing ::
Vinay Sajip982f5342012-02-27 11:56:29 +00001206
1207 logger = logging.getLogger(__name__)
1208
1209at module level). It's probably one too many things to think about. Developers
1210could also add the filter to a :class:`~logging.NullHandler` attached to their
1211top-level logger, but this would not be invoked if an application developer
Serhiy Storchaka29b0a262016-12-04 10:20:55 +02001212attached a handler to a lower-level library logger --- so output from that
Vinay Sajip982f5342012-02-27 11:56:29 +00001213handler would not reflect the intentions of the library developer.
1214
1215In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a
1216factory, which you can specify. The factory is just a callable you can set with
1217:func:`~logging.setLogRecordFactory`, and interrogate with
1218:func:`~logging.getLogRecordFactory`. The factory is invoked with the same
1219signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord`
1220is the default setting for the factory.
1221
1222This approach allows a custom factory to control all aspects of LogRecord
1223creation. For example, you could return a subclass, or just add some additional
1224attributes to the record once created, using a pattern similar to this::
1225
1226 old_factory = logging.getLogRecordFactory()
1227
1228 def record_factory(*args, **kwargs):
1229 record = old_factory(*args, **kwargs)
1230 record.custom_attribute = 0xdecafbad
1231 return record
1232
1233 logging.setLogRecordFactory(record_factory)
1234
1235This pattern allows different libraries to chain factories together, and as
1236long as they don't overwrite each other's attributes or unintentionally
1237overwrite the attributes provided as standard, there should be no surprises.
1238However, it should be borne in mind that each link in the chain adds run-time
1239overhead to all logging operations, and the technique should only be used when
1240the use of a :class:`Filter` does not provide the desired result.
1241
1242
Vinay Sajipc63619b2010-12-19 12:56:57 +00001243.. _zeromq-handlers:
1244
Vinay Sajip7d101292010-12-26 21:22:33 +00001245Subclassing QueueHandler - a ZeroMQ example
1246-------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001247
1248You can use a :class:`QueueHandler` subclass to send messages to other kinds
1249of queues, for example a ZeroMQ 'publish' socket. In the example below,the
1250socket is created separately and passed to the handler (as its 'queue')::
1251
Serhiy Storchakadba90392016-05-10 12:01:23 +03001252 import zmq # using pyzmq, the Python binding for ZeroMQ
1253 import json # for serializing records portably
Vinay Sajipc63619b2010-12-19 12:56:57 +00001254
1255 ctx = zmq.Context()
Serhiy Storchakadba90392016-05-10 12:01:23 +03001256 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
1257 sock.bind('tcp://*:5556') # or wherever
Vinay Sajipc63619b2010-12-19 12:56:57 +00001258
1259 class ZeroMQSocketHandler(QueueHandler):
1260 def enqueue(self, record):
1261 data = json.dumps(record.__dict__)
1262 self.queue.send(data)
1263
1264 handler = ZeroMQSocketHandler(sock)
1265
1266
1267Of course there are other ways of organizing this, for example passing in the
1268data needed by the handler to create the socket::
1269
1270 class ZeroMQSocketHandler(QueueHandler):
1271 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
1272 self.ctx = ctx or zmq.Context()
1273 socket = zmq.Socket(self.ctx, socktype)
1274 socket.bind(uri)
1275 QueueHandler.__init__(self, socket)
1276
1277 def enqueue(self, record):
1278 data = json.dumps(record.__dict__)
1279 self.queue.send(data)
1280
1281 def close(self):
1282 self.queue.close()
1283
1284
Vinay Sajip7d101292010-12-26 21:22:33 +00001285Subclassing QueueListener - a ZeroMQ example
1286--------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001287
1288You can also subclass :class:`QueueListener` to get messages from other kinds
1289of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
1290
1291 class ZeroMQSocketListener(QueueListener):
1292 def __init__(self, uri, *handlers, **kwargs):
1293 self.ctx = kwargs.get('ctx') or zmq.Context()
1294 socket = zmq.Socket(self.ctx, zmq.SUB)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001295 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
Vinay Sajipc63619b2010-12-19 12:56:57 +00001296 socket.connect(uri)
1297
1298 def dequeue(self):
1299 msg = self.queue.recv()
1300 return logging.makeLogRecord(json.loads(msg))
1301
1302
Vinay Sajip7d101292010-12-26 21:22:33 +00001303.. seealso::
Vinay Sajipc63619b2010-12-19 12:56:57 +00001304
Vinay Sajip7d101292010-12-26 21:22:33 +00001305 Module :mod:`logging`
1306 API reference for the logging module.
1307
1308 Module :mod:`logging.config`
1309 Configuration API for the logging module.
1310
1311 Module :mod:`logging.handlers`
1312 Useful handlers included with the logging module.
1313
1314 :ref:`A basic logging tutorial <logging-basic-tutorial>`
1315
1316 :ref:`A more advanced logging tutorial <logging-advanced-tutorial>`
Vinay Sajip631a7e22011-11-23 14:27:54 +00001317
1318
1319An example dictionary-based configuration
1320-----------------------------------------
1321
1322Below is an example of a logging configuration dictionary - it's taken from
Serhiy Storchaka90be7332016-04-11 12:18:56 +03001323the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_.
Vinay Sajip67f39772013-08-17 00:39:42 +01001324This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::
Vinay Sajip631a7e22011-11-23 14:27:54 +00001325
1326 LOGGING = {
1327 'version': 1,
1328 'disable_existing_loggers': True,
1329 'formatters': {
1330 'verbose': {
1331 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
1332 },
1333 'simple': {
1334 'format': '%(levelname)s %(message)s'
1335 },
1336 },
1337 'filters': {
1338 'special': {
1339 '()': 'project.logging.SpecialFilter',
1340 'foo': 'bar',
1341 }
1342 },
1343 'handlers': {
1344 'null': {
1345 'level':'DEBUG',
1346 'class':'django.utils.log.NullHandler',
1347 },
1348 'console':{
1349 'level':'DEBUG',
1350 'class':'logging.StreamHandler',
1351 'formatter': 'simple'
1352 },
1353 'mail_admins': {
1354 'level': 'ERROR',
1355 'class': 'django.utils.log.AdminEmailHandler',
1356 'filters': ['special']
1357 }
1358 },
1359 'loggers': {
1360 'django': {
1361 'handlers':['null'],
1362 'propagate': True,
1363 'level':'INFO',
1364 },
1365 'django.request': {
1366 'handlers': ['mail_admins'],
1367 'level': 'ERROR',
1368 'propagate': False,
1369 },
1370 'myproject.custom': {
1371 'handlers': ['console', 'mail_admins'],
1372 'level': 'INFO',
1373 'filters': ['special']
1374 }
1375 }
1376 }
1377
1378For more information about this configuration, you can see the `relevant
Serhiy Storchaka90be7332016-04-11 12:18:56 +03001379section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_
Vinay Sajip631a7e22011-11-23 14:27:54 +00001380of the Django documentation.
Vinay Sajip23b94d02012-01-04 12:02:26 +00001381
1382.. _cookbook-rotator-namer:
1383
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001384Using a rotator and namer to customize log rotation processing
Vinay Sajip23b94d02012-01-04 12:02:26 +00001385--------------------------------------------------------------
1386
1387An example of how you can define a namer and rotator is given in the following
1388snippet, which shows zlib-based compression of the log file::
1389
1390 def namer(name):
1391 return name + ".gz"
1392
1393 def rotator(source, dest):
1394 with open(source, "rb") as sf:
1395 data = sf.read()
1396 compressed = zlib.compress(data, 9)
1397 with open(dest, "wb") as df:
1398 df.write(compressed)
1399 os.remove(source)
1400
1401 rh = logging.handlers.RotatingFileHandler(...)
1402 rh.rotator = rotator
1403 rh.namer = namer
1404
Ezio Melotti226231c2012-01-18 05:40:00 +02001405These are not "true" .gz files, as they are bare compressed data, with no
1406"container" such as youd find in an actual gzip file. This snippet is just
Vinay Sajip23b94d02012-01-04 12:02:26 +00001407for illustration purposes.
1408
Vinay Sajip0292fa92012-04-08 01:49:12 +01001409A more elaborate multiprocessing example
1410----------------------------------------
1411
1412The following working example shows how logging can be used with multiprocessing
1413using configuration files. The configurations are fairly simple, but serve to
1414illustrate how more complex ones could be implemented in a real multiprocessing
1415scenario.
1416
1417In the example, the main process spawns a listener process and some worker
1418processes. Each of the main process, the listener and the workers have three
1419separate configurations (the workers all share the same configuration). We can
1420see logging in the main process, how the workers log to a QueueHandler and how
1421the listener implements a QueueListener and a more complex logging
1422configuration, and arranges to dispatch events received via the queue to the
1423handlers specified in the configuration. Note that these configurations are
1424purely illustrative, but you should be able to adapt this example to your own
1425scenario.
1426
1427Here's the script - the docstrings and the comments hopefully explain how it
1428works::
1429
1430 import logging
1431 import logging.config
1432 import logging.handlers
1433 from multiprocessing import Process, Queue, Event, current_process
1434 import os
1435 import random
1436 import time
1437
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001438 class MyHandler:
Vinay Sajip0292fa92012-04-08 01:49:12 +01001439 """
1440 A simple handler for logging events. It runs in the listener process and
1441 dispatches events to loggers based on the name in the received record,
1442 which then get dispatched, by the logging system, to the handlers
Vinay Sajip838e6382012-04-09 19:46:24 +01001443 configured for those loggers.
Vinay Sajip0292fa92012-04-08 01:49:12 +01001444 """
1445 def handle(self, record):
1446 logger = logging.getLogger(record.name)
1447 # The process name is transformed just to show that it's the listener
1448 # doing the logging to files and console
1449 record.processName = '%s (for %s)' % (current_process().name, record.processName)
1450 logger.handle(record)
1451
1452 def listener_process(q, stop_event, config):
1453 """
1454 This could be done in the main process, but is just done in a separate
1455 process for illustrative purposes.
1456
1457 This initialises logging according to the specified configuration,
1458 starts the listener and waits for the main process to signal completion
1459 via the event. The listener is then stopped, and the process exits.
1460 """
1461 logging.config.dictConfig(config)
1462 listener = logging.handlers.QueueListener(q, MyHandler())
1463 listener.start()
1464 if os.name == 'posix':
1465 # On POSIX, the setup logger will have been configured in the
1466 # parent process, but should have been disabled following the
1467 # dictConfig call.
1468 # On Windows, since fork isn't used, the setup logger won't
1469 # exist in the child, so it would be created and the message
1470 # would appear - hence the "if posix" clause.
1471 logger = logging.getLogger('setup')
1472 logger.critical('Should not appear, because of disabled logger ...')
1473 stop_event.wait()
1474 listener.stop()
1475
1476 def worker_process(config):
1477 """
1478 A number of these are spawned for the purpose of illustration. In
Berker Peksag315e1042015-05-19 01:36:55 +03001479 practice, they could be a heterogeneous bunch of processes rather than
Vinay Sajip0292fa92012-04-08 01:49:12 +01001480 ones which are identical to each other.
1481
1482 This initialises logging according to the specified configuration,
1483 and logs a hundred messages with random levels to randomly selected
1484 loggers.
1485
1486 A small sleep is added to allow other processes a chance to run. This
1487 is not strictly needed, but it mixes the output from the different
1488 processes a bit more than if it's left out.
1489 """
1490 logging.config.dictConfig(config)
1491 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
1492 logging.CRITICAL]
1493 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
1494 'spam', 'spam.ham', 'spam.ham.eggs']
1495 if os.name == 'posix':
1496 # On POSIX, the setup logger will have been configured in the
1497 # parent process, but should have been disabled following the
1498 # dictConfig call.
1499 # On Windows, since fork isn't used, the setup logger won't
1500 # exist in the child, so it would be created and the message
1501 # would appear - hence the "if posix" clause.
1502 logger = logging.getLogger('setup')
1503 logger.critical('Should not appear, because of disabled logger ...')
1504 for i in range(100):
1505 lvl = random.choice(levels)
1506 logger = logging.getLogger(random.choice(loggers))
1507 logger.log(lvl, 'Message no. %d', i)
1508 time.sleep(0.01)
1509
1510 def main():
1511 q = Queue()
1512 # The main process gets a simple configuration which prints to the console.
1513 config_initial = {
1514 'version': 1,
1515 'formatters': {
1516 'detailed': {
1517 'class': 'logging.Formatter',
1518 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1519 }
1520 },
1521 'handlers': {
1522 'console': {
1523 'class': 'logging.StreamHandler',
1524 'level': 'INFO',
1525 },
1526 },
1527 'root': {
1528 'level': 'DEBUG',
1529 'handlers': ['console']
1530 },
1531 }
1532 # The worker process configuration is just a QueueHandler attached to the
1533 # root logger, which allows all messages to be sent to the queue.
1534 # We disable existing loggers to disable the "setup" logger used in the
1535 # parent process. This is needed on POSIX because the logger will
1536 # be there in the child following a fork().
1537 config_worker = {
1538 'version': 1,
1539 'disable_existing_loggers': True,
1540 'handlers': {
1541 'queue': {
1542 'class': 'logging.handlers.QueueHandler',
1543 'queue': q,
1544 },
1545 },
1546 'root': {
1547 'level': 'DEBUG',
1548 'handlers': ['queue']
1549 },
1550 }
1551 # The listener process configuration shows that the full flexibility of
1552 # logging configuration is available to dispatch events to handlers however
1553 # you want.
1554 # We disable existing loggers to disable the "setup" logger used in the
1555 # parent process. This is needed on POSIX because the logger will
1556 # be there in the child following a fork().
1557 config_listener = {
1558 'version': 1,
1559 'disable_existing_loggers': True,
1560 'formatters': {
1561 'detailed': {
1562 'class': 'logging.Formatter',
1563 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1564 },
1565 'simple': {
1566 'class': 'logging.Formatter',
1567 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1568 }
1569 },
1570 'handlers': {
1571 'console': {
1572 'class': 'logging.StreamHandler',
1573 'level': 'INFO',
1574 'formatter': 'simple',
1575 },
1576 'file': {
1577 'class': 'logging.FileHandler',
1578 'filename': 'mplog.log',
1579 'mode': 'w',
1580 'formatter': 'detailed',
1581 },
1582 'foofile': {
1583 'class': 'logging.FileHandler',
1584 'filename': 'mplog-foo.log',
1585 'mode': 'w',
1586 'formatter': 'detailed',
1587 },
1588 'errors': {
1589 'class': 'logging.FileHandler',
1590 'filename': 'mplog-errors.log',
1591 'mode': 'w',
1592 'level': 'ERROR',
1593 'formatter': 'detailed',
1594 },
1595 },
1596 'loggers': {
1597 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001598 'handlers': ['foofile']
Vinay Sajip0292fa92012-04-08 01:49:12 +01001599 }
1600 },
1601 'root': {
1602 'level': 'DEBUG',
1603 'handlers': ['console', 'file', 'errors']
1604 },
1605 }
1606 # Log some initial events, just to show that logging in the parent works
1607 # normally.
1608 logging.config.dictConfig(config_initial)
1609 logger = logging.getLogger('setup')
1610 logger.info('About to create workers ...')
1611 workers = []
1612 for i in range(5):
1613 wp = Process(target=worker_process, name='worker %d' % (i + 1),
1614 args=(config_worker,))
1615 workers.append(wp)
1616 wp.start()
1617 logger.info('Started worker: %s', wp.name)
1618 logger.info('About to create listener ...')
1619 stop_event = Event()
1620 lp = Process(target=listener_process, name='listener',
1621 args=(q, stop_event, config_listener))
1622 lp.start()
1623 logger.info('Started listener')
1624 # We now hang around for the workers to finish their work.
1625 for wp in workers:
1626 wp.join()
1627 # Workers all done, listening can now stop.
1628 # Logging in the parent still works normally.
1629 logger.info('Telling listener to stop ...')
1630 stop_event.set()
1631 lp.join()
1632 logger.info('All done.')
1633
1634 if __name__ == '__main__':
1635 main()
1636
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001637
1638Inserting a BOM into messages sent to a SysLogHandler
1639-----------------------------------------------------
1640
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001641`RFC 5424 <https://tools.ietf.org/html/rfc5424>`_ requires that a
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001642Unicode message be sent to a syslog daemon as a set of bytes which have the
1643following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
1644Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001645section of the specification <https://tools.ietf.org/html/rfc5424#section-6>`_.)
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001646
Vinay Sajip62930e12012-04-17 00:40:48 +01001647In Python 3.1, code was added to
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001648:class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
1649unfortunately, it was implemented incorrectly, with the BOM appearing at the
1650beginning of the message and hence not allowing any pure-ASCII component to
1651appear before it.
1652
1653As this behaviour is broken, the incorrect BOM insertion code is being removed
Vinay Sajip62930e12012-04-17 00:40:48 +01001654from Python 3.2.4 and later. However, it is not being replaced, and if you
Vinay Sajipa58d6682012-07-27 10:54:10 +01001655want to produce RFC 5424-compliant messages which include a BOM, an optional
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001656pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
1657UTF-8, then you need to do the following:
1658
1659#. Attach a :class:`~logging.Formatter` instance to your
1660 :class:`~logging.handlers.SysLogHandler` instance, with a format string
1661 such as::
1662
Vinay Sajip59b9a792012-04-16 15:46:18 +01001663 'ASCII section\ufeffUnicode section'
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001664
Georg Brandld50fe722013-03-23 16:00:41 +01001665 The Unicode code point U+FEFF, when encoded using UTF-8, will be
Vinay Sajip59b9a792012-04-16 15:46:18 +01001666 encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001667
1668#. Replace the ASCII section with whatever placeholders you like, but make sure
1669 that the data that appears in there after substitution is always ASCII (that
1670 way, it will remain unchanged after UTF-8 encoding).
1671
1672#. Replace the Unicode section with whatever placeholders you like; if the data
Vinay Sajipa58d6682012-07-27 10:54:10 +01001673 which appears there after substitution contains characters outside the ASCII
1674 range, that's fine -- it will be encoded using UTF-8.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001675
Vinay Sajip59b9a792012-04-16 15:46:18 +01001676The formatted message *will* be encoded using UTF-8 encoding by
1677``SysLogHandler``. If you follow the above rules, you should be able to produce
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001678RFC 5424-compliant messages. If you don't, logging may not complain, but your
1679messages will not be RFC 5424-compliant, and your syslog daemon may complain.
1680
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001681
1682Implementing structured logging
1683-------------------------------
1684
1685Although most logging messages are intended for reading by humans, and thus not
1686readily machine-parseable, there might be cirumstances where you want to output
1687messages in a structured format which *is* capable of being parsed by a program
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001688(without needing complex regular expressions to parse the log message). This is
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001689straightforward to achieve using the logging package. There are a number of
1690ways in which this could be achieved, but the following is a simple approach
1691which uses JSON to serialise the event in a machine-parseable manner::
1692
1693 import json
1694 import logging
1695
1696 class StructuredMessage(object):
1697 def __init__(self, message, **kwargs):
1698 self.message = message
1699 self.kwargs = kwargs
1700
1701 def __str__(self):
1702 return '%s >>> %s' % (self.message, json.dumps(self.kwargs))
1703
1704 _ = StructuredMessage # optional, to improve readability
1705
1706 logging.basicConfig(level=logging.INFO, format='%(message)s')
1707 logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
1708
1709If the above script is run, it prints::
1710
1711 message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}
1712
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001713Note that the order of items might be different according to the version of
1714Python used.
1715
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001716If you need more specialised processing, you can use a custom JSON encoder,
1717as in the following complete example::
1718
1719 from __future__ import unicode_literals
1720
1721 import json
1722 import logging
1723
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001724 # This next bit is to ensure the script runs unchanged on 2.x and 3.x
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001725 try:
1726 unicode
1727 except NameError:
1728 unicode = str
1729
1730 class Encoder(json.JSONEncoder):
1731 def default(self, o):
1732 if isinstance(o, set):
1733 return tuple(o)
1734 elif isinstance(o, unicode):
1735 return o.encode('unicode_escape').decode('ascii')
1736 return super(Encoder, self).default(o)
1737
1738 class StructuredMessage(object):
1739 def __init__(self, message, **kwargs):
1740 self.message = message
1741 self.kwargs = kwargs
1742
1743 def __str__(self):
1744 s = Encoder().encode(self.kwargs)
1745 return '%s >>> %s' % (self.message, s)
1746
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001747 _ = StructuredMessage # optional, to improve readability
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001748
1749 def main():
1750 logging.basicConfig(level=logging.INFO, format='%(message)s')
Raymond Hettingerdf1b6992014-11-09 15:56:33 -08001751 logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001752
1753 if __name__ == '__main__':
1754 main()
1755
1756When the above script is run, it prints::
1757
1758 message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}
1759
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001760Note that the order of items might be different according to the version of
1761Python used.
1762
Vinay Sajip554f22f2014-02-03 11:51:45 +00001763
1764.. _custom-handlers:
1765
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001766.. currentmodule:: logging.config
1767
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001768Customizing handlers with :func:`dictConfig`
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001769--------------------------------------------
1770
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001771There are times when you want to customize logging handlers in particular ways,
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001772and if you use :func:`dictConfig` you may be able to do this without
1773subclassing. As an example, consider that you may want to set the ownership of a
1774log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001775handlers in the stdlib don't offer built-in support. You can customize handler
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001776creation using a plain function such as::
1777
1778 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1779 if owner:
1780 if not os.path.exists(filename):
1781 open(filename, 'a').close()
1782 shutil.chown(filename, *owner)
1783 return logging.FileHandler(filename, mode, encoding)
1784
1785You can then specify, in a logging configuration passed to :func:`dictConfig`,
1786that a logging handler be created by calling this function::
1787
1788 LOGGING = {
1789 'version': 1,
1790 'disable_existing_loggers': False,
1791 'formatters': {
1792 'default': {
1793 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1794 },
1795 },
1796 'handlers': {
1797 'file':{
1798 # The values below are popped from this dictionary and
1799 # used to create the handler, set the handler's level and
1800 # its formatter.
1801 '()': owned_file_handler,
1802 'level':'DEBUG',
1803 'formatter': 'default',
1804 # The values below are passed to the handler creator callable
1805 # as keyword arguments.
1806 'owner': ['pulse', 'pulse'],
1807 'filename': 'chowntest.log',
1808 'mode': 'w',
1809 'encoding': 'utf-8',
1810 },
1811 },
1812 'root': {
1813 'handlers': ['file'],
1814 'level': 'DEBUG',
1815 },
1816 }
1817
1818In this example I am setting the ownership using the ``pulse`` user and group,
1819just for the purposes of illustration. Putting it together into a working
1820script, ``chowntest.py``::
1821
1822 import logging, logging.config, os, shutil
1823
1824 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1825 if owner:
1826 if not os.path.exists(filename):
1827 open(filename, 'a').close()
1828 shutil.chown(filename, *owner)
1829 return logging.FileHandler(filename, mode, encoding)
1830
1831 LOGGING = {
1832 'version': 1,
1833 'disable_existing_loggers': False,
1834 'formatters': {
1835 'default': {
1836 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1837 },
1838 },
1839 'handlers': {
1840 'file':{
1841 # The values below are popped from this dictionary and
1842 # used to create the handler, set the handler's level and
1843 # its formatter.
1844 '()': owned_file_handler,
1845 'level':'DEBUG',
1846 'formatter': 'default',
1847 # The values below are passed to the handler creator callable
1848 # as keyword arguments.
1849 'owner': ['pulse', 'pulse'],
1850 'filename': 'chowntest.log',
1851 'mode': 'w',
1852 'encoding': 'utf-8',
1853 },
1854 },
1855 'root': {
1856 'handlers': ['file'],
1857 'level': 'DEBUG',
1858 },
1859 }
1860
1861 logging.config.dictConfig(LOGGING)
1862 logger = logging.getLogger('mylogger')
1863 logger.debug('A debug message')
1864
Martin Panter1050d2d2016-07-26 11:18:21 +02001865To run this, you will probably need to run as ``root``:
1866
1867.. code-block:: shell-session
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001868
1869 $ sudo python3.3 chowntest.py
1870 $ cat chowntest.log
1871 2013-11-05 09:34:51,128 DEBUG mylogger A debug message
1872 $ ls -l chowntest.log
1873 -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
1874
1875Note that this example uses Python 3.3 because that's where :func:`shutil.chown`
1876makes an appearance. This approach should work with any Python version that
1877supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3
1878versions, you would need to implement the actual ownership change using e.g.
1879:func:`os.chown`.
1880
1881In practice, the handler-creating function may be in a utility module somewhere
1882in your project. Instead of the line in the configuration::
1883
1884 '()': owned_file_handler,
1885
1886you could use e.g.::
1887
1888 '()': 'ext://project.util.owned_file_handler',
1889
1890where ``project.util`` can be replaced with the actual name of the package
1891where the function resides. In the above working script, using
1892``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable
1893is resolved by :func:`dictConfig` from the ``ext://`` specification.
1894
1895This example hopefully also points the way to how you could implement other
1896types of file change - e.g. setting specific POSIX permission bits - in the
1897same way, using :func:`os.chmod`.
1898
1899Of course, the approach could also be extended to types of handler other than a
1900:class:`~logging.FileHandler` - for example, one of the rotating file handlers,
1901or a different type of handler altogether.
1902
Vinay Sajipcbefe3b2014-01-15 15:09:05 +00001903
1904.. currentmodule:: logging
1905
1906.. _formatting-styles:
1907
1908Using particular formatting styles throughout your application
1909--------------------------------------------------------------
1910
1911In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword
1912parameter which, while defaulting to ``%`` for backward compatibility, allowed
1913the specification of ``{`` or ``$`` to support the formatting approaches
1914supported by :meth:`str.format` and :class:`string.Template`. Note that this
1915governs the formatting of logging messages for final output to logs, and is
1916completely orthogonal to how an individual logging message is constructed.
1917
1918Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take
1919positional parameters for the actual logging message itself, with keyword
1920parameters used only for determining options for how to handle the logging call
1921(e.g. the ``exc_info`` keyword parameter to indicate that traceback information
1922should be logged, or the ``extra`` keyword parameter to indicate additional
1923contextual information to be added to the log). So you cannot directly make
1924logging calls using :meth:`str.format` or :class:`string.Template` syntax,
1925because internally the logging package uses %-formatting to merge the format
1926string and the variable arguments. There would no changing this while preserving
1927backward compatibility, since all logging calls which are out there in existing
1928code will be using %-format strings.
1929
1930There have been suggestions to associate format styles with specific loggers,
1931but that approach also runs into backward compatibility problems because any
1932existing code could be using a given logger name and using %-formatting.
1933
1934For logging to work interoperably between any third-party libraries and your
1935code, decisions about formatting need to be made at the level of the
1936individual logging call. This opens up a couple of ways in which alternative
1937formatting styles can be accommodated.
1938
1939
1940Using LogRecord factories
1941^^^^^^^^^^^^^^^^^^^^^^^^^
1942
1943In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned
1944above, the logging package gained the ability to allow users to set their own
1945:class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function.
1946You can use this to set your own subclass of :class:`LogRecord`, which does the
1947Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base
1948class implementation of this method is where the ``msg % args`` formatting
1949happens, and where you can substitute your alternate formatting; however, you
1950should be careful to support all formatting styles and allow %-formatting as
1951the default, to ensure interoperability with other code. Care should also be
1952taken to call ``str(self.msg)``, just as the base implementation does.
1953
1954Refer to the reference documentation on :func:`setLogRecordFactory` and
1955:class:`LogRecord` for more information.
1956
1957
1958Using custom message objects
1959^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1960
1961There is another, perhaps simpler way that you can use {}- and $- formatting to
1962construct your individual log messages. You may recall (from
1963:ref:`arbitrary-object-messages`) that when logging you can use an arbitrary
1964object as a message format string, and that the logging package will call
1965:func:`str` on that object to get the actual format string. Consider the
1966following two classes::
1967
1968 class BraceMessage(object):
1969 def __init__(self, fmt, *args, **kwargs):
1970 self.fmt = fmt
1971 self.args = args
1972 self.kwargs = kwargs
1973
1974 def __str__(self):
1975 return self.fmt.format(*self.args, **self.kwargs)
1976
1977 class DollarMessage(object):
1978 def __init__(self, fmt, **kwargs):
1979 self.fmt = fmt
1980 self.kwargs = kwargs
1981
1982 def __str__(self):
1983 from string import Template
1984 return Template(self.fmt).substitute(**self.kwargs)
1985
1986Either of these can be used in place of a format string, to allow {}- or
1987$-formatting to be used to build the actual "message" part which appears in the
1988formatted log output in place of “%(message)s or “{message}” or $message”.
1989If you find it a little unwieldy to use the class names whenever you want to log
1990something, you can make it more palatable if you use an alias such as ``M`` or
1991``_`` for the message (or perhaps ``__``, if you are using ``_`` for
1992localization).
1993
Vinay Sajipeb14dec2014-01-17 18:36:02 +00001994Examples of this approach are given below. Firstly, formatting with
1995:meth:`str.format`::
1996
1997 >>> __ = BraceMessage
1998 >>> print(__('Message with {0} {1}', 2, 'placeholders'))
1999 Message with 2 placeholders
2000 >>> class Point: pass
2001 ...
2002 >>> p = Point()
2003 >>> p.x = 0.5
2004 >>> p.y = 0.5
2005 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
2006 Message with coordinates: (0.50, 0.50)
2007
2008Secondly, formatting with :class:`string.Template`::
2009
2010 >>> __ = DollarMessage
2011 >>> print(__('Message with $num $what', num=2, what='placeholders'))
2012 Message with 2 placeholders
2013 >>>
2014
2015One thing to note is that you pay no significant performance penalty with this
2016approach: the actual formatting happens not when you make the logging call, but
2017when (and if) the logged message is actually about to be output to a log by a
2018handler. So the only slightly unusual thing which might trip you up is that the
2019parentheses go around the format string and the arguments, not just the format
2020string. Thats because the __ notation is just syntax sugar for a constructor
2021call to one of the ``XXXMessage`` classes shown above.
Vinay Sajip554f22f2014-02-03 11:51:45 +00002022
2023
2024.. _filters-dictconfig:
2025
2026.. currentmodule:: logging.config
2027
2028Configuring filters with :func:`dictConfig`
2029-------------------------------------------
2030
2031You *can* configure filters using :func:`~logging.config.dictConfig`, though it
2032might not be obvious at first glance how to do it (hence this recipe). Since
2033:class:`~logging.Filter` is the only filter class included in the standard
2034library, and it is unlikely to cater to many requirements (it's only there as a
2035base class), you will typically need to define your own :class:`~logging.Filter`
2036subclass with an overridden :meth:`~logging.Filter.filter` method. To do this,
2037specify the ``()`` key in the configuration dictionary for the filter,
2038specifying a callable which will be used to create the filter (a class is the
2039most obvious, but you can provide any callable which returns a
2040:class:`~logging.Filter` instance). Here is a complete example::
2041
2042 import logging
2043 import logging.config
2044 import sys
2045
2046 class MyFilter(logging.Filter):
2047 def __init__(self, param=None):
2048 self.param = param
2049
2050 def filter(self, record):
2051 if self.param is None:
2052 allow = True
2053 else:
2054 allow = self.param not in record.msg
2055 if allow:
2056 record.msg = 'changed: ' + record.msg
2057 return allow
2058
2059 LOGGING = {
2060 'version': 1,
2061 'filters': {
2062 'myfilter': {
2063 '()': MyFilter,
2064 'param': 'noshow',
2065 }
2066 },
2067 'handlers': {
2068 'console': {
2069 'class': 'logging.StreamHandler',
2070 'filters': ['myfilter']
2071 }
2072 },
2073 'root': {
2074 'level': 'DEBUG',
2075 'handlers': ['console']
2076 },
2077 }
2078
2079 if __name__ == '__main__':
2080 logging.config.dictConfig(LOGGING)
2081 logging.debug('hello')
2082 logging.debug('hello - noshow')
2083
2084This example shows how you can pass configuration data to the callable which
2085constructs the instance, in the form of keyword parameters. When run, the above
2086script will print::
2087
2088 changed: hello
2089
2090which shows that the filter is working as configured.
2091
2092A couple of extra points to note:
2093
2094* If you can't refer to the callable directly in the configuration (e.g. if it
2095 lives in a different module, and you can't import it directly where the
2096 configuration dictionary is), you can use the form ``ext://...`` as described
2097 in :ref:`logging-config-dict-externalobj`. For example, you could have used
2098 the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above
2099 example.
2100
2101* As well as for filters, this technique can also be used to configure custom
2102 handlers and formatters. See :ref:`logging-config-dict-userdef` for more
2103 information on how logging supports using user-defined objects in its
2104 configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
2105
Vinay Sajipdb071642015-01-28 07:32:38 +00002106
2107.. _custom-format-exception:
2108
2109Customized exception formatting
2110-------------------------------
2111
2112There might be times when you want to do customized exception formatting - for
2113argument's sake, let's say you want exactly one line per logged event, even
2114when exception information is present. You can do this with a custom formatter
2115class, as shown in the following example::
2116
2117 import logging
2118
2119 class OneLineExceptionFormatter(logging.Formatter):
2120 def formatException(self, exc_info):
2121 """
2122 Format an exception so that it prints on a single line.
2123 """
2124 result = super(OneLineExceptionFormatter, self).formatException(exc_info)
Serhiy Storchakadba90392016-05-10 12:01:23 +03002125 return repr(result) # or format into one line however you want to
Vinay Sajipdb071642015-01-28 07:32:38 +00002126
2127 def format(self, record):
2128 s = super(OneLineExceptionFormatter, self).format(record)
2129 if record.exc_text:
2130 s = s.replace('\n', '') + '|'
2131 return s
2132
2133 def configure_logging():
2134 fh = logging.FileHandler('output.txt', 'w')
2135 f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
2136 '%d/%m/%Y %H:%M:%S')
2137 fh.setFormatter(f)
2138 root = logging.getLogger()
2139 root.setLevel(logging.DEBUG)
2140 root.addHandler(fh)
2141
2142 def main():
2143 configure_logging()
2144 logging.info('Sample message')
2145 try:
2146 x = 1 / 0
2147 except ZeroDivisionError as e:
2148 logging.exception('ZeroDivisionError: %s', e)
2149
2150 if __name__ == '__main__':
2151 main()
2152
2153When run, this produces a file with exactly two lines::
2154
2155 28/01/2015 07:21:23|INFO|Sample message|
2156 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'|
2157
2158While the above treatment is simplistic, it points the way to how exception
2159information can be formatted to your liking. The :mod:`traceback` module may be
2160helpful for more specialized needs.
Vinay Sajipf046dfe2015-02-01 15:17:34 +00002161
2162.. _spoken-messages:
2163
2164Speaking logging messages
2165-------------------------
2166
2167There might be situations when it is desirable to have logging messages rendered
2168in an audible rather than a visible format. This is easy to do if you have text-
2169to-speech (TTS) functionality available in your system, even if it doesn't have
2170a Python binding. Most TTS systems have a command line program you can run, and
2171this can be invoked from a handler using :mod:`subprocess`. It's assumed here
2172that TTS command line programs won't expect to interact with users or take a
2173long time to complete, and that the frequency of logged messages will be not so
2174high as to swamp the user with messages, and that it's acceptable to have the
2175messages spoken one at a time rather than concurrently, The example implementation
2176below waits for one message to be spoken before the next is processed, and this
2177might cause other handlers to be kept waiting. Here is a short example showing
2178the approach, which assumes that the ``espeak`` TTS package is available::
2179
2180 import logging
2181 import subprocess
2182 import sys
2183
2184 class TTSHandler(logging.Handler):
2185 def emit(self, record):
2186 msg = self.format(record)
2187 # Speak slowly in a female English voice
2188 cmd = ['espeak', '-s150', '-ven+f3', msg]
2189 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
2190 stderr=subprocess.STDOUT)
2191 # wait for the program to finish
2192 p.communicate()
2193
2194 def configure_logging():
2195 h = TTSHandler()
2196 root = logging.getLogger()
2197 root.addHandler(h)
2198 # the default formatter just returns the message
2199 root.setLevel(logging.DEBUG)
2200
2201 def main():
2202 logging.info('Hello')
2203 logging.debug('Goodbye')
2204
2205 if __name__ == '__main__':
2206 configure_logging()
2207 sys.exit(main())
2208
2209When run, this script should say "Hello" and then "Goodbye" in a female voice.
2210
2211The above approach can, of course, be adapted to other TTS systems and even
2212other systems altogether which can process messages via external programs run
2213from a command line.
2214
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002215
2216.. _buffered-logging:
2217
2218Buffering logging messages and outputting them conditionally
2219------------------------------------------------------------
2220
2221There might be situations where you want to log messages in a temporary area
2222and only output them if a certain condition occurs. For example, you may want to
2223start logging debug events in a function, and if the function completes without
2224errors, you don't want to clutter the log with the collected debug information,
2225but if there is an error, you want all the debug information to be output as well
2226as the error.
2227
2228Here is an example which shows how you could do this using a decorator for your
2229functions where you want logging to behave this way. It makes use of the
2230:class:`logging.handlers.MemoryHandler`, which allows buffering of logged events
2231until some condition occurs, at which point the buffered events are ``flushed``
2232- passed to another handler (the ``target`` handler) for processing. By default,
2233the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose
2234level is greater than or equal to a specified threshold is seen. You can use this
2235recipe with a more specialised subclass of ``MemoryHandler`` if you want custom
2236flushing behavior.
2237
2238The example script has a simple function, ``foo``, which just cycles through
2239all the logging levels, writing to ``sys.stderr`` to say what level it's about
Martin Panterf05641642016-05-08 13:48:10 +00002240to log at, and then actually logging a message at that level. You can pass a
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002241parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
2242otherwise, it only logs at DEBUG, INFO and WARNING levels.
2243
2244The script just arranges to decorate ``foo`` with a decorator which will do the
2245conditional logging that's required. The decorator takes a logger as a parameter
2246and attaches a memory handler for the duration of the call to the decorated
2247function. The decorator can be additionally parameterised using a target handler,
2248a level at which flushing should occur, and a capacity for the buffer. These
2249default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``,
2250``logging.ERROR`` and ``100`` respectively.
2251
2252Here's the script::
2253
2254 import logging
2255 from logging.handlers import MemoryHandler
2256 import sys
2257
2258 logger = logging.getLogger(__name__)
2259 logger.addHandler(logging.NullHandler())
2260
2261 def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
2262 if target_handler is None:
2263 target_handler = logging.StreamHandler()
2264 if flush_level is None:
2265 flush_level = logging.ERROR
2266 if capacity is None:
2267 capacity = 100
2268 handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)
2269
2270 def decorator(fn):
2271 def wrapper(*args, **kwargs):
2272 logger.addHandler(handler)
2273 try:
2274 return fn(*args, **kwargs)
2275 except Exception:
2276 logger.exception('call failed')
2277 raise
2278 finally:
2279 super(MemoryHandler, handler).flush()
2280 logger.removeHandler(handler)
2281 return wrapper
2282
2283 return decorator
2284
2285 def write_line(s):
2286 sys.stderr.write('%s\n' % s)
2287
2288 def foo(fail=False):
2289 write_line('about to log at DEBUG ...')
2290 logger.debug('Actually logged at DEBUG')
2291 write_line('about to log at INFO ...')
2292 logger.info('Actually logged at INFO')
2293 write_line('about to log at WARNING ...')
2294 logger.warning('Actually logged at WARNING')
2295 if fail:
2296 write_line('about to log at ERROR ...')
2297 logger.error('Actually logged at ERROR')
2298 write_line('about to log at CRITICAL ...')
2299 logger.critical('Actually logged at CRITICAL')
2300 return fail
2301
2302 decorated_foo = log_if_errors(logger)(foo)
2303
2304 if __name__ == '__main__':
2305 logger.setLevel(logging.DEBUG)
2306 write_line('Calling undecorated foo with False')
2307 assert not foo(False)
2308 write_line('Calling undecorated foo with True')
2309 assert foo(True)
2310 write_line('Calling decorated foo with False')
2311 assert not decorated_foo(False)
2312 write_line('Calling decorated foo with True')
2313 assert decorated_foo(True)
2314
2315When this script is run, the following output should be observed::
2316
2317 Calling undecorated foo with False
2318 about to log at DEBUG ...
2319 about to log at INFO ...
2320 about to log at WARNING ...
2321 Calling undecorated foo with True
2322 about to log at DEBUG ...
2323 about to log at INFO ...
2324 about to log at WARNING ...
2325 about to log at ERROR ...
2326 about to log at CRITICAL ...
2327 Calling decorated foo with False
2328 about to log at DEBUG ...
2329 about to log at INFO ...
2330 about to log at WARNING ...
2331 Calling decorated foo with True
2332 about to log at DEBUG ...
2333 about to log at INFO ...
2334 about to log at WARNING ...
2335 about to log at ERROR ...
2336 Actually logged at DEBUG
2337 Actually logged at INFO
2338 Actually logged at WARNING
2339 Actually logged at ERROR
2340 about to log at CRITICAL ...
2341 Actually logged at CRITICAL
2342
2343As you can see, actual logging output only occurs when an event is logged whose
2344severity is ERROR or greater, but in that case, any previous events at lower
2345severities are also logged.
2346
2347You can of course use the conventional means of decoration::
2348
2349 @log_if_errors(logger)
2350 def foo(fail=False):
2351 ...
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002352
2353
2354.. _utc-formatting:
2355
2356Formatting times using UTC (GMT) via configuration
2357--------------------------------------------------
2358
2359Sometimes you want to format times using UTC, which can be done using a class
2360such as `UTCFormatter`, shown below::
2361
2362 import logging
2363 import time
2364
2365 class UTCFormatter(logging.Formatter):
2366 converter = time.gmtime
2367
Berker Peksagf84499a2015-10-20 03:41:38 +03002368and you can then use the ``UTCFormatter`` in your code instead of
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002369:class:`~logging.Formatter`. If you want to do that via configuration, you can
2370use the :func:`~logging.config.dictConfig` API with an approach illustrated by
2371the following complete example::
2372
2373 import logging
2374 import logging.config
2375 import time
2376
2377 class UTCFormatter(logging.Formatter):
2378 converter = time.gmtime
2379
2380 LOGGING = {
2381 'version': 1,
2382 'disable_existing_loggers': False,
2383 'formatters': {
2384 'utc': {
2385 '()': UTCFormatter,
2386 'format': '%(asctime)s %(message)s',
2387 },
2388 'local': {
2389 'format': '%(asctime)s %(message)s',
2390 }
2391 },
2392 'handlers': {
2393 'console1': {
2394 'class': 'logging.StreamHandler',
2395 'formatter': 'utc',
2396 },
2397 'console2': {
2398 'class': 'logging.StreamHandler',
2399 'formatter': 'local',
2400 },
2401 },
2402 'root': {
2403 'handlers': ['console1', 'console2'],
2404 }
2405 }
2406
2407 if __name__ == '__main__':
2408 logging.config.dictConfig(LOGGING)
2409 logging.warning('The local time is %s', time.asctime())
2410
2411When this script is run, it should print something like::
2412
2413 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2414 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2415
2416showing how the time is formatted both as local time and UTC, one for each
2417handler.
Vinay Sajipd93a6012016-04-01 23:13:01 +01002418
2419
2420.. _context-manager:
2421
2422Using a context manager for selective logging
2423---------------------------------------------
2424
2425There are times when it would be useful to temporarily change the logging
2426configuration and revert it back after doing something. For this, a context
2427manager is the most obvious way of saving and restoring the logging context.
2428Here is a simple example of such a context manager, which allows you to
2429optionally change the logging level and add a logging handler purely in the
2430scope of the context manager::
2431
2432 import logging
2433 import sys
2434
2435 class LoggingContext(object):
2436 def __init__(self, logger, level=None, handler=None, close=True):
2437 self.logger = logger
2438 self.level = level
2439 self.handler = handler
2440 self.close = close
2441
2442 def __enter__(self):
2443 if self.level is not None:
2444 self.old_level = self.logger.level
2445 self.logger.setLevel(self.level)
2446 if self.handler:
2447 self.logger.addHandler(self.handler)
2448
2449 def __exit__(self, et, ev, tb):
2450 if self.level is not None:
2451 self.logger.setLevel(self.old_level)
2452 if self.handler:
2453 self.logger.removeHandler(self.handler)
2454 if self.handler and self.close:
2455 self.handler.close()
2456 # implicit return of None => don't swallow exceptions
2457
2458If you specify a level value, the logger's level is set to that value in the
2459scope of the with block covered by the context manager. If you specify a
2460handler, it is added to the logger on entry to the block and removed on exit
2461from the block. You can also ask the manager to close the handler for you on
2462block exit - you could do this if you don't need the handler any more.
2463
2464To illustrate how it works, we can add the following block of code to the
2465above::
2466
2467 if __name__ == '__main__':
2468 logger = logging.getLogger('foo')
2469 logger.addHandler(logging.StreamHandler())
2470 logger.setLevel(logging.INFO)
2471 logger.info('1. This should appear just once on stderr.')
2472 logger.debug('2. This should not appear.')
2473 with LoggingContext(logger, level=logging.DEBUG):
2474 logger.debug('3. This should appear once on stderr.')
2475 logger.debug('4. This should not appear.')
2476 h = logging.StreamHandler(sys.stdout)
2477 with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
2478 logger.debug('5. This should appear twice - once on stderr and once on stdout.')
2479 logger.info('6. This should appear just once on stderr.')
2480 logger.debug('7. This should not appear.')
2481
2482We initially set the logger's level to ``INFO``, so message #1 appears and
2483message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the
2484following ``with`` block, and so message #3 appears. After the block exits, the
2485logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the
2486next ``with`` block, we set the level to ``DEBUG`` again but also add a handler
2487writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once
2488via ``stderr`` and once via ``stdout``). After the ``with`` statement's
2489completion, the status is as it was before so message #6 appears (like message
2490#1) whereas message #7 doesn't (just like message #2).
2491
Martin Panter1050d2d2016-07-26 11:18:21 +02002492If we run the resulting script, the result is as follows:
2493
2494.. code-block:: shell-session
Vinay Sajipd93a6012016-04-01 23:13:01 +01002495
2496 $ python logctx.py
2497 1. This should appear just once on stderr.
2498 3. This should appear once on stderr.
2499 5. This should appear twice - once on stderr and once on stdout.
2500 5. This should appear twice - once on stderr and once on stdout.
2501 6. This should appear just once on stderr.
2502
2503If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
Martin Panter1050d2d2016-07-26 11:18:21 +02002504which is the only message written to ``stdout``:
2505
2506.. code-block:: shell-session
Vinay Sajipd93a6012016-04-01 23:13:01 +01002507
2508 $ python logctx.py 2>/dev/null
2509 5. This should appear twice - once on stderr and once on stdout.
2510
Martin Panter1050d2d2016-07-26 11:18:21 +02002511Once again, but piping ``stdout`` to ``/dev/null``, we get:
2512
2513.. code-block:: shell-session
Vinay Sajipd93a6012016-04-01 23:13:01 +01002514
2515 $ python logctx.py >/dev/null
2516 1. This should appear just once on stderr.
2517 3. This should appear once on stderr.
2518 5. This should appear twice - once on stderr and once on stdout.
2519 6. This should appear just once on stderr.
2520
2521In this case, the message #5 printed to ``stdout`` doesn't appear, as expected.
2522
2523Of course, the approach described here can be generalised, for example to attach
2524logging filters temporarily. Note that the above code works in Python 2 as well
2525as Python 3.