blob: 99b4cdcb5fa848d4e5d8cb9916df63ce3b35af6e [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
380which, when run, will produce::
381
382 MainThread: Look out!
383
Vinay Sajip365701a2015-02-09 19:49:00 +0000384.. versionchanged:: 3.5
385 Prior to Python 3.5, the :class:`QueueListener` always passed every message
386 received from the queue to every handler it was initialized with. (This was
387 because it was assumed that level filtering was all done on the other side,
388 where the queue is filled.) From 3.5 onwards, this behaviour can be changed
389 by passing a keyword argument ``respect_handler_level=True`` to the
390 listener's constructor. When this is done, the listener compares the level
391 of each message with the handler's level, and only passes a message to a
392 handler if it's appropriate to do so.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000393
394.. _network-logging:
395
396Sending and receiving logging events across a network
397-----------------------------------------------------
398
399Let's say you want to send logging events across a network, and handle them at
400the receiving end. A simple way of doing this is attaching a
401:class:`SocketHandler` instance to the root logger at the sending end::
402
403 import logging, logging.handlers
404
405 rootLogger = logging.getLogger('')
406 rootLogger.setLevel(logging.DEBUG)
407 socketHandler = logging.handlers.SocketHandler('localhost',
408 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
409 # don't bother with a formatter, since a socket handler sends the event as
410 # an unformatted pickle
411 rootLogger.addHandler(socketHandler)
412
413 # Now, we can log to the root logger, or any other logger. First the root...
414 logging.info('Jackdaws love my big sphinx of quartz.')
415
416 # Now, define a couple of other loggers which might represent areas in your
417 # application:
418
419 logger1 = logging.getLogger('myapp.area1')
420 logger2 = logging.getLogger('myapp.area2')
421
422 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
423 logger1.info('How quickly daft jumping zebras vex.')
424 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
425 logger2.error('The five boxing wizards jump quickly.')
426
427At the receiving end, you can set up a receiver using the :mod:`socketserver`
428module. Here is a basic working example::
429
430 import pickle
431 import logging
432 import logging.handlers
433 import socketserver
434 import struct
435
436
437 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
438 """Handler for a streaming logging request.
439
440 This basically logs the record using whatever logging policy is
441 configured locally.
442 """
443
444 def handle(self):
445 """
446 Handle multiple requests - each expected to be a 4-byte length,
447 followed by the LogRecord in pickle format. Logs the record
448 according to whatever policy is configured locally.
449 """
450 while True:
451 chunk = self.connection.recv(4)
452 if len(chunk) < 4:
453 break
454 slen = struct.unpack('>L', chunk)[0]
455 chunk = self.connection.recv(slen)
456 while len(chunk) < slen:
457 chunk = chunk + self.connection.recv(slen - len(chunk))
458 obj = self.unPickle(chunk)
459 record = logging.makeLogRecord(obj)
460 self.handleLogRecord(record)
461
462 def unPickle(self, data):
463 return pickle.loads(data)
464
465 def handleLogRecord(self, record):
466 # if a name is specified, we use the named logger rather than the one
467 # implied by the record.
468 if self.server.logname is not None:
469 name = self.server.logname
470 else:
471 name = record.name
472 logger = logging.getLogger(name)
473 # N.B. EVERY record gets logged. This is because Logger.handle
474 # is normally called AFTER logger-level filtering. If you want
475 # to do filtering, do it at the client end to save wasting
476 # cycles and network bandwidth!
477 logger.handle(record)
478
479 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
480 """
481 Simple TCP socket-based logging receiver suitable for testing.
482 """
483
Raymond Hettinger4ab532b2014-03-28 16:39:25 -0700484 allow_reuse_address = True
Vinay Sajipc63619b2010-12-19 12:56:57 +0000485
486 def __init__(self, host='localhost',
487 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
488 handler=LogRecordStreamHandler):
489 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
490 self.abort = 0
491 self.timeout = 1
492 self.logname = None
493
494 def serve_until_stopped(self):
495 import select
496 abort = 0
497 while not abort:
498 rd, wr, ex = select.select([self.socket.fileno()],
499 [], [],
500 self.timeout)
501 if rd:
502 self.handle_request()
503 abort = self.abort
504
505 def main():
506 logging.basicConfig(
507 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
508 tcpserver = LogRecordSocketReceiver()
509 print('About to start TCP server...')
510 tcpserver.serve_until_stopped()
511
512 if __name__ == '__main__':
513 main()
514
515First run the server, and then the client. On the client side, nothing is
516printed on the console; on the server side, you should see something like::
517
518 About to start TCP server...
519 59 root INFO Jackdaws love my big sphinx of quartz.
520 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
521 69 myapp.area1 INFO How quickly daft jumping zebras vex.
522 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
523 69 myapp.area2 ERROR The five boxing wizards jump quickly.
524
525Note that there are some security issues with pickle in some scenarios. If
526these affect you, you can use an alternative serialization scheme by overriding
Vinay Sajip67f39772013-08-17 00:39:42 +0100527the :meth:`~handlers.SocketHandler.makePickle` method and implementing your
528alternative there, as well as adapting the above script to use your alternative
529serialization.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000530
531
532.. _context-info:
533
534Adding contextual information to your logging output
535----------------------------------------------------
536
537Sometimes you want logging output to contain contextual information in
538addition to the parameters passed to the logging call. For example, in a
539networked application, it may be desirable to log client-specific information
540in the log (e.g. remote client's username, or IP address). Although you could
541use the *extra* parameter to achieve this, it's not always convenient to pass
542the information in this way. While it might be tempting to create
543:class:`Logger` instances on a per-connection basis, this is not a good idea
544because these instances are not garbage collected. While this is not a problem
545in practice, when the number of :class:`Logger` instances is dependent on the
546level of granularity you want to use in logging an application, it could
547be hard to manage if the number of :class:`Logger` instances becomes
548effectively unbounded.
549
550
551Using LoggerAdapters to impart contextual information
552^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
553
554An easy way in which you can pass contextual information to be output along
555with logging event information is to use the :class:`LoggerAdapter` class.
556This class is designed to look like a :class:`Logger`, so that you can call
557:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
558:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
559same signatures as their counterparts in :class:`Logger`, so you can use the
560two types of instances interchangeably.
561
562When you create an instance of :class:`LoggerAdapter`, you pass it a
563:class:`Logger` instance and a dict-like object which contains your contextual
564information. When you call one of the logging methods on an instance of
565:class:`LoggerAdapter`, it delegates the call to the underlying instance of
566:class:`Logger` passed to its constructor, and arranges to pass the contextual
567information in the delegated call. Here's a snippet from the code of
568:class:`LoggerAdapter`::
569
570 def debug(self, msg, *args, **kwargs):
571 """
572 Delegate a debug call to the underlying logger, after adding
573 contextual information from this adapter instance.
574 """
575 msg, kwargs = self.process(msg, kwargs)
576 self.logger.debug(msg, *args, **kwargs)
577
Vinay Sajip67f39772013-08-17 00:39:42 +0100578The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the
579contextual information is added to the logging output. It's passed the message
580and keyword arguments of the logging call, and it passes back (potentially)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000581modified versions of these to use in the call to the underlying logger. The
582default implementation of this method leaves the message alone, but inserts
583an 'extra' key in the keyword argument whose value is the dict-like object
584passed to the constructor. Of course, if you had passed an 'extra' keyword
585argument in the call to the adapter, it will be silently overwritten.
586
587The advantage of using 'extra' is that the values in the dict-like object are
588merged into the :class:`LogRecord` instance's __dict__, allowing you to use
589customized strings with your :class:`Formatter` instances which know about
590the keys of the dict-like object. If you need a different method, e.g. if you
591want to prepend or append the contextual information to the message string,
Vinay Sajip67f39772013-08-17 00:39:42 +0100592you just need to subclass :class:`LoggerAdapter` and override
593:meth:`~LoggerAdapter.process` to do what you need. Here is a simple example::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000594
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100595 class CustomAdapter(logging.LoggerAdapter):
596 """
597 This example adapter expects the passed in dict-like object to have a
598 'connid' key, whose value in brackets is prepended to the log message.
599 """
600 def process(self, msg, kwargs):
601 return '[%s] %s' % (self.extra['connid'], msg), kwargs
Vinay Sajipc63619b2010-12-19 12:56:57 +0000602
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100603which you can use like this::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000604
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100605 logger = logging.getLogger(__name__)
606 adapter = CustomAdapter(logger, {'connid': some_conn_id})
Vinay Sajipc63619b2010-12-19 12:56:57 +0000607
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100608Then any events that you log to the adapter will have the value of
609``some_conn_id`` prepended to the log messages.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000610
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100611Using objects other than dicts to pass contextual information
612~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vinay Sajipc63619b2010-12-19 12:56:57 +0000613
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100614You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could
615pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so
616that it looks like a dict to logging. This would be useful if you want to
617generate values dynamically (whereas the values in a dict would be constant).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000618
619
620.. _filters-contextual:
621
622Using Filters to impart contextual information
623^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
624
625You can also add contextual information to log output using a user-defined
626:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
627passed to them, including adding additional attributes which can then be output
628using a suitable format string, or if needed a custom :class:`Formatter`.
629
630For example in a web application, the request being processed (or at least,
631the interesting parts of it) can be stored in a threadlocal
632(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
633add, say, information from the request - say, the remote IP address and remote
634user's username - to the ``LogRecord``, using the attribute names 'ip' and
635'user' as in the ``LoggerAdapter`` example above. In that case, the same format
636string can be used to get similar output to that shown above. Here's an example
637script::
638
639 import logging
640 from random import choice
641
642 class ContextFilter(logging.Filter):
643 """
644 This is a filter which injects contextual information into the log.
645
646 Rather than use actual contextual information, we just use random
647 data in this demo.
648 """
649
650 USERS = ['jim', 'fred', 'sheila']
651 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
652
653 def filter(self, record):
654
655 record.ip = choice(ContextFilter.IPS)
656 record.user = choice(ContextFilter.USERS)
657 return True
658
659 if __name__ == '__main__':
Serhiy Storchakadba90392016-05-10 12:01:23 +0300660 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
661 logging.basicConfig(level=logging.DEBUG,
662 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
663 a1 = logging.getLogger('a.b.c')
664 a2 = logging.getLogger('d.e.f')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000665
Serhiy Storchakadba90392016-05-10 12:01:23 +0300666 f = ContextFilter()
667 a1.addFilter(f)
668 a2.addFilter(f)
669 a1.debug('A debug message')
670 a1.info('An info message with %s', 'some parameters')
671 for x in range(10):
672 lvl = choice(levels)
673 lvlname = logging.getLevelName(lvl)
674 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Vinay Sajipc63619b2010-12-19 12:56:57 +0000675
676which, when run, produces something like::
677
678 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
679 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
680 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
681 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
682 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
683 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
684 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
685 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
686 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
687 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
688 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
689 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
690
691
692.. _multiple-processes:
693
694Logging to a single file from multiple processes
695------------------------------------------------
696
697Although logging is thread-safe, and logging to a single file from multiple
698threads in a single process *is* supported, logging to a single file from
699*multiple processes* is *not* supported, because there is no standard way to
700serialize access to a single file across multiple processes in Python. If you
701need to log to a single file from multiple processes, one way of doing this is
Vinay Sajip67f39772013-08-17 00:39:42 +0100702to have all the processes log to a :class:`~handlers.SocketHandler`, and have a
703separate process which implements a socket server which reads from the socket
704and logs to file. (If you prefer, you can dedicate one thread in one of the
705existing processes to perform this function.)
706:ref:`This section <network-logging>` documents this approach in more detail and
707includes a working socket receiver which can be used as a starting point for you
708to adapt in your own applications.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000709
710If you are using a recent version of Python which includes the
711:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip67f39772013-08-17 00:39:42 +0100712:class:`~multiprocessing.Lock` class from this module to serialize access to the
713file from your processes. The existing :class:`FileHandler` and subclasses do
714not make use of :mod:`multiprocessing` at present, though they may do so in the
715future. Note that at present, the :mod:`multiprocessing` module does not provide
Vinay Sajipc63619b2010-12-19 12:56:57 +0000716working lock functionality on all platforms (see
Georg Brandle73778c2014-10-29 08:36:35 +0100717https://bugs.python.org/issue3770).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000718
719.. currentmodule:: logging.handlers
720
721Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
722all logging events to one of the processes in your multi-process application.
723The following example script demonstrates how you can do this; in the example
724a separate listener process listens for events sent by other processes and logs
725them according to its own logging configuration. Although the example only
726demonstrates one way of doing it (for example, you may want to use a listener
Georg Brandl7a0afd32011-02-07 15:44:27 +0000727thread rather than a separate listener process -- the implementation would be
Vinay Sajipc63619b2010-12-19 12:56:57 +0000728analogous) it does allow for completely different logging configurations for
729the listener and the other processes in your application, and can be used as
730the basis for code meeting your own specific requirements::
731
732 # You'll need these imports in your own code
733 import logging
734 import logging.handlers
735 import multiprocessing
736
737 # Next two import lines for this demo only
738 from random import choice, random
739 import time
740
741 #
742 # Because you'll want to define the logging configurations for listener and workers, the
743 # listener and worker process functions take a configurer parameter which is a callable
744 # for configuring logging for that process. These functions are also passed the queue,
745 # which they use for communication.
746 #
747 # In practice, you can configure the listener however you want, but note that in this
748 # simple example, the listener does not apply level or filter logic to received records.
Georg Brandl7a0afd32011-02-07 15:44:27 +0000749 # In practice, you would probably want to do this logic in the worker processes, to avoid
Vinay Sajipc63619b2010-12-19 12:56:57 +0000750 # sending events which would be filtered out between processes.
751 #
752 # The size of the rotated files is made small so you can see the results easily.
753 def listener_configurer():
754 root = logging.getLogger()
Raymond Hettingerb34705f2011-06-26 15:29:06 +0200755 h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000756 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
757 h.setFormatter(f)
758 root.addHandler(h)
759
760 # This is the listener process top-level loop: wait for logging events
761 # (LogRecords)on the queue and handle them, quit when you get a None for a
762 # LogRecord.
763 def listener_process(queue, configurer):
764 configurer()
765 while True:
766 try:
767 record = queue.get()
Serhiy Storchakadba90392016-05-10 12:01:23 +0300768 if record is None: # We send this as a sentinel to tell the listener to quit.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000769 break
770 logger = logging.getLogger(record.name)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300771 logger.handle(record) # No level or filter logic applied - just do it!
Andrew Svetlov47395612012-11-02 22:07:26 +0200772 except Exception:
Vinay Sajipc63619b2010-12-19 12:56:57 +0000773 import sys, traceback
Vinay Sajip6b883a22012-02-27 11:02:45 +0000774 print('Whoops! Problem:', file=sys.stderr)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000775 traceback.print_exc(file=sys.stderr)
776
777 # Arrays used for random selections in this demo
778
779 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
780 logging.ERROR, logging.CRITICAL]
781
782 LOGGERS = ['a.b.c', 'd.e.f']
783
784 MESSAGES = [
785 'Random message #1',
786 'Random message #2',
787 'Random message #3',
788 ]
789
790 # The worker configuration is done at the start of the worker process run.
791 # Note that on Windows you can't rely on fork semantics, so each process
792 # will run the logging configuration code when it starts.
793 def worker_configurer(queue):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300794 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
Vinay Sajipc63619b2010-12-19 12:56:57 +0000795 root = logging.getLogger()
796 root.addHandler(h)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300797 # send all messages, for demo; no other level or filter logic applied.
798 root.setLevel(logging.DEBUG)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000799
800 # This is the worker process top-level loop, which just logs ten events with
801 # random intervening delays before terminating.
802 # The print messages are just so you know it's doing something!
803 def worker_process(queue, configurer):
804 configurer(queue)
805 name = multiprocessing.current_process().name
806 print('Worker started: %s' % name)
807 for i in range(10):
808 time.sleep(random())
809 logger = logging.getLogger(choice(LOGGERS))
810 level = choice(LEVELS)
811 message = choice(MESSAGES)
812 logger.log(level, message)
813 print('Worker finished: %s' % name)
814
815 # Here's where the demo gets orchestrated. Create the queue, create and start
816 # the listener, create ten workers and start them, wait for them to finish,
817 # then send a None to the queue to tell the listener to finish.
818 def main():
819 queue = multiprocessing.Queue(-1)
820 listener = multiprocessing.Process(target=listener_process,
821 args=(queue, listener_configurer))
822 listener.start()
823 workers = []
824 for i in range(10):
825 worker = multiprocessing.Process(target=worker_process,
Serhiy Storchakadba90392016-05-10 12:01:23 +0300826 args=(queue, worker_configurer))
Vinay Sajipc63619b2010-12-19 12:56:57 +0000827 workers.append(worker)
828 worker.start()
829 for w in workers:
830 w.join()
831 queue.put_nowait(None)
832 listener.join()
833
834 if __name__ == '__main__':
835 main()
836
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000837A variant of the above script keeps the logging in the main process, in a
838separate thread::
839
840 import logging
841 import logging.config
842 import logging.handlers
843 from multiprocessing import Process, Queue
844 import random
845 import threading
846 import time
847
848 def logger_thread(q):
849 while True:
850 record = q.get()
851 if record is None:
852 break
853 logger = logging.getLogger(record.name)
854 logger.handle(record)
855
856
857 def worker_process(q):
858 qh = logging.handlers.QueueHandler(q)
859 root = logging.getLogger()
860 root.setLevel(logging.DEBUG)
861 root.addHandler(qh)
862 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
863 logging.CRITICAL]
864 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
865 'spam', 'spam.ham', 'spam.ham.eggs']
866 for i in range(100):
867 lvl = random.choice(levels)
868 logger = logging.getLogger(random.choice(loggers))
869 logger.log(lvl, 'Message no. %d', i)
870
871 if __name__ == '__main__':
872 q = Queue()
873 d = {
874 'version': 1,
875 'formatters': {
876 'detailed': {
877 'class': 'logging.Formatter',
878 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
879 }
880 },
881 'handlers': {
882 'console': {
883 'class': 'logging.StreamHandler',
884 'level': 'INFO',
885 },
886 'file': {
887 'class': 'logging.FileHandler',
888 'filename': 'mplog.log',
889 'mode': 'w',
890 'formatter': 'detailed',
891 },
892 'foofile': {
893 'class': 'logging.FileHandler',
894 'filename': 'mplog-foo.log',
895 'mode': 'w',
896 'formatter': 'detailed',
897 },
898 'errors': {
899 'class': 'logging.FileHandler',
900 'filename': 'mplog-errors.log',
901 'mode': 'w',
902 'level': 'ERROR',
903 'formatter': 'detailed',
904 },
905 },
906 'loggers': {
907 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200908 'handlers': ['foofile']
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000909 }
910 },
911 'root': {
912 'level': 'DEBUG',
913 'handlers': ['console', 'file', 'errors']
914 },
915 }
916 workers = []
917 for i in range(5):
918 wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
919 workers.append(wp)
920 wp.start()
921 logging.config.dictConfig(d)
922 lp = threading.Thread(target=logger_thread, args=(q,))
923 lp.start()
924 # At this point, the main process could do some useful work of its own
925 # Once it's done that, it can wait for the workers to terminate...
926 for wp in workers:
927 wp.join()
928 # And now tell the logging thread to finish up, too
929 q.put(None)
930 lp.join()
931
932This variant shows how you can e.g. apply configuration for particular loggers
933- e.g. the ``foo`` logger has a special handler which stores all events in the
934``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging
935machinery in the main process (even though the logging events are generated in
936the worker processes) to direct the messages to the appropriate destinations.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000937
938Using file rotation
939-------------------
940
941.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
942.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
943
944Sometimes you want to let a log file grow to a certain size, then open a new
945file and log to that. You may want to keep a certain number of these files, and
946when that many files have been created, rotate the files so that the number of
Georg Brandl7a0afd32011-02-07 15:44:27 +0000947files and the size of the files both remain bounded. For this usage pattern, the
Vinay Sajip67f39772013-08-17 00:39:42 +0100948logging package provides a :class:`~handlers.RotatingFileHandler`::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000949
950 import glob
951 import logging
952 import logging.handlers
953
954 LOG_FILENAME = 'logging_rotatingfile_example.out'
955
956 # Set up a specific logger with our desired output level
957 my_logger = logging.getLogger('MyLogger')
958 my_logger.setLevel(logging.DEBUG)
959
960 # Add the log message handler to the logger
961 handler = logging.handlers.RotatingFileHandler(
962 LOG_FILENAME, maxBytes=20, backupCount=5)
963
964 my_logger.addHandler(handler)
965
966 # Log some messages
967 for i in range(20):
968 my_logger.debug('i = %d' % i)
969
970 # See what files are created
971 logfiles = glob.glob('%s*' % LOG_FILENAME)
972
973 for filename in logfiles:
974 print(filename)
975
976The result should be 6 separate files, each with part of the log history for the
977application::
978
979 logging_rotatingfile_example.out
980 logging_rotatingfile_example.out.1
981 logging_rotatingfile_example.out.2
982 logging_rotatingfile_example.out.3
983 logging_rotatingfile_example.out.4
984 logging_rotatingfile_example.out.5
985
986The most current file is always :file:`logging_rotatingfile_example.out`,
987and each time it reaches the size limit it is renamed with the suffix
988``.1``. Each of the existing backup files is renamed to increment the suffix
989(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
990
Ezio Melottie130a522011-10-19 10:58:56 +0300991Obviously this example sets the log length much too small as an extreme
Vinay Sajipc63619b2010-12-19 12:56:57 +0000992example. You would want to set *maxBytes* to an appropriate value.
993
Vinay Sajip6b883a22012-02-27 11:02:45 +0000994.. _format-styles:
995
996Use of alternative formatting styles
997------------------------------------
998
999When logging was added to the Python standard library, the only way of
1000formatting messages with variable content was to use the %-formatting
1001method. Since then, Python has gained two new formatting approaches:
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001002:class:`string.Template` (added in Python 2.4) and :meth:`str.format`
1003(added in Python 2.6).
Vinay Sajip6b883a22012-02-27 11:02:45 +00001004
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001005Logging (as of 3.2) provides improved support for these two additional
1006formatting styles. The :class:`Formatter` class been enhanced to take an
1007additional, optional keyword parameter named ``style``. This defaults to
1008``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond
Vinay Sajip6b883a22012-02-27 11:02:45 +00001009to the other two formatting styles. Backwards compatibility is maintained by
1010default (as you would expect), but by explicitly specifying a style parameter,
1011you get the ability to specify format strings which work with
1012:meth:`str.format` or :class:`string.Template`. Here's an example console
1013session to show the possibilities:
1014
1015.. code-block:: pycon
1016
1017 >>> import logging
1018 >>> root = logging.getLogger()
1019 >>> root.setLevel(logging.DEBUG)
1020 >>> handler = logging.StreamHandler()
1021 >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
1022 ... style='{')
1023 >>> handler.setFormatter(bf)
1024 >>> root.addHandler(handler)
1025 >>> logger = logging.getLogger('foo.bar')
1026 >>> logger.debug('This is a DEBUG message')
1027 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message
1028 >>> logger.critical('This is a CRITICAL message')
1029 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
1030 >>> df = logging.Formatter('$asctime $name ${levelname} $message',
1031 ... style='$')
1032 >>> handler.setFormatter(df)
1033 >>> logger.debug('This is a DEBUG message')
1034 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
1035 >>> logger.critical('This is a CRITICAL message')
1036 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
1037 >>>
1038
1039Note that the formatting of logging messages for final output to logs is
1040completely independent of how an individual logging message is constructed.
1041That can still use %-formatting, as shown here::
1042
1043 >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
1044 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
1045 >>>
1046
1047Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take
1048positional parameters for the actual logging message itself, with keyword
1049parameters used only for determining options for how to handle the actual
1050logging call (e.g. the ``exc_info`` keyword parameter to indicate that
1051traceback information should be logged, or the ``extra`` keyword parameter
1052to indicate additional contextual information to be added to the log). So
1053you cannot directly make logging calls using :meth:`str.format` or
1054:class:`string.Template` syntax, because internally the logging package
1055uses %-formatting to merge the format string and the variable arguments.
1056There would no changing this while preserving backward compatibility, since
1057all logging calls which are out there in existing code will be using %-format
1058strings.
1059
1060There is, however, a way that you can use {}- and $- formatting to construct
1061your individual log messages. Recall that for a message you can use an
1062arbitrary object as a message format string, and that the logging package will
1063call ``str()`` on that object to get the actual format string. Consider the
1064following two classes::
1065
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001066 class BraceMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001067 def __init__(self, fmt, *args, **kwargs):
1068 self.fmt = fmt
1069 self.args = args
1070 self.kwargs = kwargs
1071
1072 def __str__(self):
1073 return self.fmt.format(*self.args, **self.kwargs)
1074
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001075 class DollarMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001076 def __init__(self, fmt, **kwargs):
1077 self.fmt = fmt
1078 self.kwargs = kwargs
1079
1080 def __str__(self):
1081 from string import Template
1082 return Template(self.fmt).substitute(**self.kwargs)
1083
1084Either of these can be used in place of a format string, to allow {}- or
1085$-formatting to be used to build the actual "message" part which appears in the
1086formatted log output in place of "%(message)s" or "{message}" or "$message".
1087It's a little unwieldy to use the class names whenever you want to log
1088something, but it's quite palatable if you use an alias such as __ (double
1089underscore – not to be confused with _, the single underscore used as a
1090synonym/alias for :func:`gettext.gettext` or its brethren).
1091
1092The above classes are not included in Python, though they're easy enough to
1093copy and paste into your own code. They can be used as follows (assuming that
1094they're declared in a module called ``wherever``):
1095
1096.. code-block:: pycon
1097
1098 >>> from wherever import BraceMessage as __
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001099 >>> print(__('Message with {0} {name}', 2, name='placeholders'))
Vinay Sajip6b883a22012-02-27 11:02:45 +00001100 Message with 2 placeholders
1101 >>> class Point: pass
1102 ...
1103 >>> p = Point()
1104 >>> p.x = 0.5
1105 >>> p.y = 0.5
1106 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
1107 ... point=p))
1108 Message with coordinates: (0.50, 0.50)
1109 >>> from wherever import DollarMessage as __
1110 >>> print(__('Message with $num $what', num=2, what='placeholders'))
1111 Message with 2 placeholders
1112 >>>
1113
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001114While the above examples use ``print()`` to show how the formatting works, you
1115would of course use ``logger.debug()`` or similar to actually log using this
1116approach.
1117
Vinay Sajip6b883a22012-02-27 11:02:45 +00001118One thing to note is that you pay no significant performance penalty with this
1119approach: the actual formatting happens not when you make the logging call, but
1120when (and if) the logged message is actually about to be output to a log by a
1121handler. So the only slightly unusual thing which might trip you up is that the
1122parentheses go around the format string and the arguments, not just the format
1123string. That's because the __ notation is just syntax sugar for a constructor
1124call to one of the XXXMessage classes.
1125
Vinay Sajip8028a5c2013-03-30 11:56:18 +00001126If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect
1127to the above, as in the following example::
1128
1129 import logging
1130
1131 class Message(object):
1132 def __init__(self, fmt, args):
1133 self.fmt = fmt
1134 self.args = args
1135
1136 def __str__(self):
1137 return self.fmt.format(*self.args)
1138
1139 class StyleAdapter(logging.LoggerAdapter):
1140 def __init__(self, logger, extra=None):
1141 super(StyleAdapter, self).__init__(logger, extra or {})
1142
1143 def log(self, level, msg, *args, **kwargs):
1144 if self.isEnabledFor(level):
1145 msg, kwargs = self.process(msg, kwargs)
1146 self.logger._log(level, Message(msg, args), (), **kwargs)
1147
1148 logger = StyleAdapter(logging.getLogger(__name__))
1149
1150 def main():
1151 logger.debug('Hello, {}', 'world!')
1152
1153 if __name__ == '__main__':
1154 logging.basicConfig(level=logging.DEBUG)
1155 main()
1156
1157The above script should log the message ``Hello, world!`` when run with
1158Python 3.2 or later.
1159
Vinay Sajip6b883a22012-02-27 11:02:45 +00001160
Vinay Sajip982f5342012-02-27 11:56:29 +00001161.. currentmodule:: logging
1162
Georg Brandle9983862012-02-28 08:21:40 +01001163.. _custom-logrecord:
Vinay Sajip982f5342012-02-27 11:56:29 +00001164
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001165Customizing ``LogRecord``
Vinay Sajip982f5342012-02-27 11:56:29 +00001166-------------------------
1167
1168Every logging event is represented by a :class:`LogRecord` instance.
1169When an event is logged and not filtered out by a logger's level, a
1170:class:`LogRecord` is created, populated with information about the event and
1171then passed to the handlers for that logger (and its ancestors, up to and
1172including the logger where further propagation up the hierarchy is disabled).
1173Before Python 3.2, there were only two places where this creation was done:
1174
1175* :meth:`Logger.makeRecord`, which is called in the normal process of
1176 logging an event. This invoked :class:`LogRecord` directly to create an
1177 instance.
1178* :func:`makeLogRecord`, which is called with a dictionary containing
1179 attributes to be added to the LogRecord. This is typically invoked when a
1180 suitable dictionary has been received over the network (e.g. in pickle form
1181 via a :class:`~handlers.SocketHandler`, or in JSON form via an
1182 :class:`~handlers.HTTPHandler`).
1183
1184This has usually meant that if you need to do anything special with a
1185:class:`LogRecord`, you've had to do one of the following.
1186
1187* Create your own :class:`Logger` subclass, which overrides
1188 :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass`
1189 before any loggers that you care about are instantiated.
1190* Add a :class:`Filter` to a logger or handler, which does the
1191 necessary special manipulation you need when its
1192 :meth:`~Filter.filter` method is called.
1193
1194The first approach would be a little unwieldy in the scenario where (say)
1195several different libraries wanted to do different things. Each would attempt
1196to set its own :class:`Logger` subclass, and the one which did this last would
1197win.
1198
1199The second approach works reasonably well for many cases, but does not allow
1200you to e.g. use a specialized subclass of :class:`LogRecord`. Library
1201developers can set a suitable filter on their loggers, but they would have to
1202remember to do this every time they introduced a new logger (which they would
Georg Brandle9983862012-02-28 08:21:40 +01001203do simply by adding new packages or modules and doing ::
Vinay Sajip982f5342012-02-27 11:56:29 +00001204
1205 logger = logging.getLogger(__name__)
1206
1207at module level). It's probably one too many things to think about. Developers
1208could also add the filter to a :class:`~logging.NullHandler` attached to their
1209top-level logger, but this would not be invoked if an application developer
1210attached a handler to a lower-level library logger – so output from that
1211handler would not reflect the intentions of the library developer.
1212
1213In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a
1214factory, which you can specify. The factory is just a callable you can set with
1215:func:`~logging.setLogRecordFactory`, and interrogate with
1216:func:`~logging.getLogRecordFactory`. The factory is invoked with the same
1217signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord`
1218is the default setting for the factory.
1219
1220This approach allows a custom factory to control all aspects of LogRecord
1221creation. For example, you could return a subclass, or just add some additional
1222attributes to the record once created, using a pattern similar to this::
1223
1224 old_factory = logging.getLogRecordFactory()
1225
1226 def record_factory(*args, **kwargs):
1227 record = old_factory(*args, **kwargs)
1228 record.custom_attribute = 0xdecafbad
1229 return record
1230
1231 logging.setLogRecordFactory(record_factory)
1232
1233This pattern allows different libraries to chain factories together, and as
1234long as they don't overwrite each other's attributes or unintentionally
1235overwrite the attributes provided as standard, there should be no surprises.
1236However, it should be borne in mind that each link in the chain adds run-time
1237overhead to all logging operations, and the technique should only be used when
1238the use of a :class:`Filter` does not provide the desired result.
1239
1240
Vinay Sajipc63619b2010-12-19 12:56:57 +00001241.. _zeromq-handlers:
1242
Vinay Sajip7d101292010-12-26 21:22:33 +00001243Subclassing QueueHandler - a ZeroMQ example
1244-------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001245
1246You can use a :class:`QueueHandler` subclass to send messages to other kinds
1247of queues, for example a ZeroMQ 'publish' socket. In the example below,the
1248socket is created separately and passed to the handler (as its 'queue')::
1249
Serhiy Storchakadba90392016-05-10 12:01:23 +03001250 import zmq # using pyzmq, the Python binding for ZeroMQ
1251 import json # for serializing records portably
Vinay Sajipc63619b2010-12-19 12:56:57 +00001252
1253 ctx = zmq.Context()
Serhiy Storchakadba90392016-05-10 12:01:23 +03001254 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
1255 sock.bind('tcp://*:5556') # or wherever
Vinay Sajipc63619b2010-12-19 12:56:57 +00001256
1257 class ZeroMQSocketHandler(QueueHandler):
1258 def enqueue(self, record):
1259 data = json.dumps(record.__dict__)
1260 self.queue.send(data)
1261
1262 handler = ZeroMQSocketHandler(sock)
1263
1264
1265Of course there are other ways of organizing this, for example passing in the
1266data needed by the handler to create the socket::
1267
1268 class ZeroMQSocketHandler(QueueHandler):
1269 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
1270 self.ctx = ctx or zmq.Context()
1271 socket = zmq.Socket(self.ctx, socktype)
1272 socket.bind(uri)
1273 QueueHandler.__init__(self, socket)
1274
1275 def enqueue(self, record):
1276 data = json.dumps(record.__dict__)
1277 self.queue.send(data)
1278
1279 def close(self):
1280 self.queue.close()
1281
1282
Vinay Sajip7d101292010-12-26 21:22:33 +00001283Subclassing QueueListener - a ZeroMQ example
1284--------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001285
1286You can also subclass :class:`QueueListener` to get messages from other kinds
1287of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
1288
1289 class ZeroMQSocketListener(QueueListener):
1290 def __init__(self, uri, *handlers, **kwargs):
1291 self.ctx = kwargs.get('ctx') or zmq.Context()
1292 socket = zmq.Socket(self.ctx, zmq.SUB)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001293 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
Vinay Sajipc63619b2010-12-19 12:56:57 +00001294 socket.connect(uri)
1295
1296 def dequeue(self):
1297 msg = self.queue.recv()
1298 return logging.makeLogRecord(json.loads(msg))
1299
1300
Vinay Sajip7d101292010-12-26 21:22:33 +00001301.. seealso::
Vinay Sajipc63619b2010-12-19 12:56:57 +00001302
Vinay Sajip7d101292010-12-26 21:22:33 +00001303 Module :mod:`logging`
1304 API reference for the logging module.
1305
1306 Module :mod:`logging.config`
1307 Configuration API for the logging module.
1308
1309 Module :mod:`logging.handlers`
1310 Useful handlers included with the logging module.
1311
1312 :ref:`A basic logging tutorial <logging-basic-tutorial>`
1313
1314 :ref:`A more advanced logging tutorial <logging-advanced-tutorial>`
Vinay Sajip631a7e22011-11-23 14:27:54 +00001315
1316
1317An example dictionary-based configuration
1318-----------------------------------------
1319
1320Below is an example of a logging configuration dictionary - it's taken from
Serhiy Storchaka90be7332016-04-11 12:18:56 +03001321the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_.
Vinay Sajip67f39772013-08-17 00:39:42 +01001322This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::
Vinay Sajip631a7e22011-11-23 14:27:54 +00001323
1324 LOGGING = {
1325 'version': 1,
1326 'disable_existing_loggers': True,
1327 'formatters': {
1328 'verbose': {
1329 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
1330 },
1331 'simple': {
1332 'format': '%(levelname)s %(message)s'
1333 },
1334 },
1335 'filters': {
1336 'special': {
1337 '()': 'project.logging.SpecialFilter',
1338 'foo': 'bar',
1339 }
1340 },
1341 'handlers': {
1342 'null': {
1343 'level':'DEBUG',
1344 'class':'django.utils.log.NullHandler',
1345 },
1346 'console':{
1347 'level':'DEBUG',
1348 'class':'logging.StreamHandler',
1349 'formatter': 'simple'
1350 },
1351 'mail_admins': {
1352 'level': 'ERROR',
1353 'class': 'django.utils.log.AdminEmailHandler',
1354 'filters': ['special']
1355 }
1356 },
1357 'loggers': {
1358 'django': {
1359 'handlers':['null'],
1360 'propagate': True,
1361 'level':'INFO',
1362 },
1363 'django.request': {
1364 'handlers': ['mail_admins'],
1365 'level': 'ERROR',
1366 'propagate': False,
1367 },
1368 'myproject.custom': {
1369 'handlers': ['console', 'mail_admins'],
1370 'level': 'INFO',
1371 'filters': ['special']
1372 }
1373 }
1374 }
1375
1376For more information about this configuration, you can see the `relevant
Serhiy Storchaka90be7332016-04-11 12:18:56 +03001377section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_
Vinay Sajip631a7e22011-11-23 14:27:54 +00001378of the Django documentation.
Vinay Sajip23b94d02012-01-04 12:02:26 +00001379
1380.. _cookbook-rotator-namer:
1381
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001382Using a rotator and namer to customize log rotation processing
Vinay Sajip23b94d02012-01-04 12:02:26 +00001383--------------------------------------------------------------
1384
1385An example of how you can define a namer and rotator is given in the following
1386snippet, which shows zlib-based compression of the log file::
1387
1388 def namer(name):
1389 return name + ".gz"
1390
1391 def rotator(source, dest):
1392 with open(source, "rb") as sf:
1393 data = sf.read()
1394 compressed = zlib.compress(data, 9)
1395 with open(dest, "wb") as df:
1396 df.write(compressed)
1397 os.remove(source)
1398
1399 rh = logging.handlers.RotatingFileHandler(...)
1400 rh.rotator = rotator
1401 rh.namer = namer
1402
Ezio Melotti226231c2012-01-18 05:40:00 +02001403These are not "true" .gz files, as they are bare compressed data, with no
1404"container" such as youd find in an actual gzip file. This snippet is just
Vinay Sajip23b94d02012-01-04 12:02:26 +00001405for illustration purposes.
1406
Vinay Sajip0292fa92012-04-08 01:49:12 +01001407A more elaborate multiprocessing example
1408----------------------------------------
1409
1410The following working example shows how logging can be used with multiprocessing
1411using configuration files. The configurations are fairly simple, but serve to
1412illustrate how more complex ones could be implemented in a real multiprocessing
1413scenario.
1414
1415In the example, the main process spawns a listener process and some worker
1416processes. Each of the main process, the listener and the workers have three
1417separate configurations (the workers all share the same configuration). We can
1418see logging in the main process, how the workers log to a QueueHandler and how
1419the listener implements a QueueListener and a more complex logging
1420configuration, and arranges to dispatch events received via the queue to the
1421handlers specified in the configuration. Note that these configurations are
1422purely illustrative, but you should be able to adapt this example to your own
1423scenario.
1424
1425Here's the script - the docstrings and the comments hopefully explain how it
1426works::
1427
1428 import logging
1429 import logging.config
1430 import logging.handlers
1431 from multiprocessing import Process, Queue, Event, current_process
1432 import os
1433 import random
1434 import time
1435
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001436 class MyHandler:
Vinay Sajip0292fa92012-04-08 01:49:12 +01001437 """
1438 A simple handler for logging events. It runs in the listener process and
1439 dispatches events to loggers based on the name in the received record,
1440 which then get dispatched, by the logging system, to the handlers
Vinay Sajip838e6382012-04-09 19:46:24 +01001441 configured for those loggers.
Vinay Sajip0292fa92012-04-08 01:49:12 +01001442 """
1443 def handle(self, record):
1444 logger = logging.getLogger(record.name)
1445 # The process name is transformed just to show that it's the listener
1446 # doing the logging to files and console
1447 record.processName = '%s (for %s)' % (current_process().name, record.processName)
1448 logger.handle(record)
1449
1450 def listener_process(q, stop_event, config):
1451 """
1452 This could be done in the main process, but is just done in a separate
1453 process for illustrative purposes.
1454
1455 This initialises logging according to the specified configuration,
1456 starts the listener and waits for the main process to signal completion
1457 via the event. The listener is then stopped, and the process exits.
1458 """
1459 logging.config.dictConfig(config)
1460 listener = logging.handlers.QueueListener(q, MyHandler())
1461 listener.start()
1462 if os.name == 'posix':
1463 # On POSIX, the setup logger will have been configured in the
1464 # parent process, but should have been disabled following the
1465 # dictConfig call.
1466 # On Windows, since fork isn't used, the setup logger won't
1467 # exist in the child, so it would be created and the message
1468 # would appear - hence the "if posix" clause.
1469 logger = logging.getLogger('setup')
1470 logger.critical('Should not appear, because of disabled logger ...')
1471 stop_event.wait()
1472 listener.stop()
1473
1474 def worker_process(config):
1475 """
1476 A number of these are spawned for the purpose of illustration. In
Berker Peksag315e1042015-05-19 01:36:55 +03001477 practice, they could be a heterogeneous bunch of processes rather than
Vinay Sajip0292fa92012-04-08 01:49:12 +01001478 ones which are identical to each other.
1479
1480 This initialises logging according to the specified configuration,
1481 and logs a hundred messages with random levels to randomly selected
1482 loggers.
1483
1484 A small sleep is added to allow other processes a chance to run. This
1485 is not strictly needed, but it mixes the output from the different
1486 processes a bit more than if it's left out.
1487 """
1488 logging.config.dictConfig(config)
1489 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
1490 logging.CRITICAL]
1491 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
1492 'spam', 'spam.ham', 'spam.ham.eggs']
1493 if os.name == 'posix':
1494 # On POSIX, the setup logger will have been configured in the
1495 # parent process, but should have been disabled following the
1496 # dictConfig call.
1497 # On Windows, since fork isn't used, the setup logger won't
1498 # exist in the child, so it would be created and the message
1499 # would appear - hence the "if posix" clause.
1500 logger = logging.getLogger('setup')
1501 logger.critical('Should not appear, because of disabled logger ...')
1502 for i in range(100):
1503 lvl = random.choice(levels)
1504 logger = logging.getLogger(random.choice(loggers))
1505 logger.log(lvl, 'Message no. %d', i)
1506 time.sleep(0.01)
1507
1508 def main():
1509 q = Queue()
1510 # The main process gets a simple configuration which prints to the console.
1511 config_initial = {
1512 'version': 1,
1513 'formatters': {
1514 'detailed': {
1515 'class': 'logging.Formatter',
1516 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1517 }
1518 },
1519 'handlers': {
1520 'console': {
1521 'class': 'logging.StreamHandler',
1522 'level': 'INFO',
1523 },
1524 },
1525 'root': {
1526 'level': 'DEBUG',
1527 'handlers': ['console']
1528 },
1529 }
1530 # The worker process configuration is just a QueueHandler attached to the
1531 # root logger, which allows all messages to be sent to the queue.
1532 # We disable existing loggers to disable the "setup" logger used in the
1533 # parent process. This is needed on POSIX because the logger will
1534 # be there in the child following a fork().
1535 config_worker = {
1536 'version': 1,
1537 'disable_existing_loggers': True,
1538 'handlers': {
1539 'queue': {
1540 'class': 'logging.handlers.QueueHandler',
1541 'queue': q,
1542 },
1543 },
1544 'root': {
1545 'level': 'DEBUG',
1546 'handlers': ['queue']
1547 },
1548 }
1549 # The listener process configuration shows that the full flexibility of
1550 # logging configuration is available to dispatch events to handlers however
1551 # you want.
1552 # We disable existing loggers to disable the "setup" logger used in the
1553 # parent process. This is needed on POSIX because the logger will
1554 # be there in the child following a fork().
1555 config_listener = {
1556 'version': 1,
1557 'disable_existing_loggers': True,
1558 'formatters': {
1559 'detailed': {
1560 'class': 'logging.Formatter',
1561 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1562 },
1563 'simple': {
1564 'class': 'logging.Formatter',
1565 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1566 }
1567 },
1568 'handlers': {
1569 'console': {
1570 'class': 'logging.StreamHandler',
1571 'level': 'INFO',
1572 'formatter': 'simple',
1573 },
1574 'file': {
1575 'class': 'logging.FileHandler',
1576 'filename': 'mplog.log',
1577 'mode': 'w',
1578 'formatter': 'detailed',
1579 },
1580 'foofile': {
1581 'class': 'logging.FileHandler',
1582 'filename': 'mplog-foo.log',
1583 'mode': 'w',
1584 'formatter': 'detailed',
1585 },
1586 'errors': {
1587 'class': 'logging.FileHandler',
1588 'filename': 'mplog-errors.log',
1589 'mode': 'w',
1590 'level': 'ERROR',
1591 'formatter': 'detailed',
1592 },
1593 },
1594 'loggers': {
1595 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001596 'handlers': ['foofile']
Vinay Sajip0292fa92012-04-08 01:49:12 +01001597 }
1598 },
1599 'root': {
1600 'level': 'DEBUG',
1601 'handlers': ['console', 'file', 'errors']
1602 },
1603 }
1604 # Log some initial events, just to show that logging in the parent works
1605 # normally.
1606 logging.config.dictConfig(config_initial)
1607 logger = logging.getLogger('setup')
1608 logger.info('About to create workers ...')
1609 workers = []
1610 for i in range(5):
1611 wp = Process(target=worker_process, name='worker %d' % (i + 1),
1612 args=(config_worker,))
1613 workers.append(wp)
1614 wp.start()
1615 logger.info('Started worker: %s', wp.name)
1616 logger.info('About to create listener ...')
1617 stop_event = Event()
1618 lp = Process(target=listener_process, name='listener',
1619 args=(q, stop_event, config_listener))
1620 lp.start()
1621 logger.info('Started listener')
1622 # We now hang around for the workers to finish their work.
1623 for wp in workers:
1624 wp.join()
1625 # Workers all done, listening can now stop.
1626 # Logging in the parent still works normally.
1627 logger.info('Telling listener to stop ...')
1628 stop_event.set()
1629 lp.join()
1630 logger.info('All done.')
1631
1632 if __name__ == '__main__':
1633 main()
1634
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001635
1636Inserting a BOM into messages sent to a SysLogHandler
1637-----------------------------------------------------
1638
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001639`RFC 5424 <https://tools.ietf.org/html/rfc5424>`_ requires that a
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001640Unicode message be sent to a syslog daemon as a set of bytes which have the
1641following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
1642Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001643section of the specification <https://tools.ietf.org/html/rfc5424#section-6>`_.)
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001644
Vinay Sajip62930e12012-04-17 00:40:48 +01001645In Python 3.1, code was added to
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001646:class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
1647unfortunately, it was implemented incorrectly, with the BOM appearing at the
1648beginning of the message and hence not allowing any pure-ASCII component to
1649appear before it.
1650
1651As this behaviour is broken, the incorrect BOM insertion code is being removed
Vinay Sajip62930e12012-04-17 00:40:48 +01001652from Python 3.2.4 and later. However, it is not being replaced, and if you
Vinay Sajipa58d6682012-07-27 10:54:10 +01001653want to produce RFC 5424-compliant messages which include a BOM, an optional
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001654pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
1655UTF-8, then you need to do the following:
1656
1657#. Attach a :class:`~logging.Formatter` instance to your
1658 :class:`~logging.handlers.SysLogHandler` instance, with a format string
1659 such as::
1660
Vinay Sajip59b9a792012-04-16 15:46:18 +01001661 'ASCII section\ufeffUnicode section'
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001662
Georg Brandld50fe722013-03-23 16:00:41 +01001663 The Unicode code point U+FEFF, when encoded using UTF-8, will be
Vinay Sajip59b9a792012-04-16 15:46:18 +01001664 encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001665
1666#. Replace the ASCII section with whatever placeholders you like, but make sure
1667 that the data that appears in there after substitution is always ASCII (that
1668 way, it will remain unchanged after UTF-8 encoding).
1669
1670#. Replace the Unicode section with whatever placeholders you like; if the data
Vinay Sajipa58d6682012-07-27 10:54:10 +01001671 which appears there after substitution contains characters outside the ASCII
1672 range, that's fine -- it will be encoded using UTF-8.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001673
Vinay Sajip59b9a792012-04-16 15:46:18 +01001674The formatted message *will* be encoded using UTF-8 encoding by
1675``SysLogHandler``. If you follow the above rules, you should be able to produce
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001676RFC 5424-compliant messages. If you don't, logging may not complain, but your
1677messages will not be RFC 5424-compliant, and your syslog daemon may complain.
1678
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001679
1680Implementing structured logging
1681-------------------------------
1682
1683Although most logging messages are intended for reading by humans, and thus not
1684readily machine-parseable, there might be cirumstances where you want to output
1685messages in a structured format which *is* capable of being parsed by a program
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001686(without needing complex regular expressions to parse the log message). This is
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001687straightforward to achieve using the logging package. There are a number of
1688ways in which this could be achieved, but the following is a simple approach
1689which uses JSON to serialise the event in a machine-parseable manner::
1690
1691 import json
1692 import logging
1693
1694 class StructuredMessage(object):
1695 def __init__(self, message, **kwargs):
1696 self.message = message
1697 self.kwargs = kwargs
1698
1699 def __str__(self):
1700 return '%s >>> %s' % (self.message, json.dumps(self.kwargs))
1701
1702 _ = StructuredMessage # optional, to improve readability
1703
1704 logging.basicConfig(level=logging.INFO, format='%(message)s')
1705 logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
1706
1707If the above script is run, it prints::
1708
1709 message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}
1710
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001711Note that the order of items might be different according to the version of
1712Python used.
1713
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001714If you need more specialised processing, you can use a custom JSON encoder,
1715as in the following complete example::
1716
1717 from __future__ import unicode_literals
1718
1719 import json
1720 import logging
1721
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001722 # This next bit is to ensure the script runs unchanged on 2.x and 3.x
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001723 try:
1724 unicode
1725 except NameError:
1726 unicode = str
1727
1728 class Encoder(json.JSONEncoder):
1729 def default(self, o):
1730 if isinstance(o, set):
1731 return tuple(o)
1732 elif isinstance(o, unicode):
1733 return o.encode('unicode_escape').decode('ascii')
1734 return super(Encoder, self).default(o)
1735
1736 class StructuredMessage(object):
1737 def __init__(self, message, **kwargs):
1738 self.message = message
1739 self.kwargs = kwargs
1740
1741 def __str__(self):
1742 s = Encoder().encode(self.kwargs)
1743 return '%s >>> %s' % (self.message, s)
1744
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001745 _ = StructuredMessage # optional, to improve readability
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001746
1747 def main():
1748 logging.basicConfig(level=logging.INFO, format='%(message)s')
Raymond Hettingerdf1b6992014-11-09 15:56:33 -08001749 logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001750
1751 if __name__ == '__main__':
1752 main()
1753
1754When the above script is run, it prints::
1755
1756 message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}
1757
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001758Note that the order of items might be different according to the version of
1759Python used.
1760
Vinay Sajip554f22f2014-02-03 11:51:45 +00001761
1762.. _custom-handlers:
1763
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001764.. currentmodule:: logging.config
1765
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001766Customizing handlers with :func:`dictConfig`
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001767--------------------------------------------
1768
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001769There are times when you want to customize logging handlers in particular ways,
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001770and if you use :func:`dictConfig` you may be able to do this without
1771subclassing. As an example, consider that you may want to set the ownership of a
1772log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001773handlers in the stdlib don't offer built-in support. You can customize handler
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001774creation using a plain function such as::
1775
1776 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1777 if owner:
1778 if not os.path.exists(filename):
1779 open(filename, 'a').close()
1780 shutil.chown(filename, *owner)
1781 return logging.FileHandler(filename, mode, encoding)
1782
1783You can then specify, in a logging configuration passed to :func:`dictConfig`,
1784that a logging handler be created by calling this function::
1785
1786 LOGGING = {
1787 'version': 1,
1788 'disable_existing_loggers': False,
1789 'formatters': {
1790 'default': {
1791 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1792 },
1793 },
1794 'handlers': {
1795 'file':{
1796 # The values below are popped from this dictionary and
1797 # used to create the handler, set the handler's level and
1798 # its formatter.
1799 '()': owned_file_handler,
1800 'level':'DEBUG',
1801 'formatter': 'default',
1802 # The values below are passed to the handler creator callable
1803 # as keyword arguments.
1804 'owner': ['pulse', 'pulse'],
1805 'filename': 'chowntest.log',
1806 'mode': 'w',
1807 'encoding': 'utf-8',
1808 },
1809 },
1810 'root': {
1811 'handlers': ['file'],
1812 'level': 'DEBUG',
1813 },
1814 }
1815
1816In this example I am setting the ownership using the ``pulse`` user and group,
1817just for the purposes of illustration. Putting it together into a working
1818script, ``chowntest.py``::
1819
1820 import logging, logging.config, os, shutil
1821
1822 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1823 if owner:
1824 if not os.path.exists(filename):
1825 open(filename, 'a').close()
1826 shutil.chown(filename, *owner)
1827 return logging.FileHandler(filename, mode, encoding)
1828
1829 LOGGING = {
1830 'version': 1,
1831 'disable_existing_loggers': False,
1832 'formatters': {
1833 'default': {
1834 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1835 },
1836 },
1837 'handlers': {
1838 'file':{
1839 # The values below are popped from this dictionary and
1840 # used to create the handler, set the handler's level and
1841 # its formatter.
1842 '()': owned_file_handler,
1843 'level':'DEBUG',
1844 'formatter': 'default',
1845 # The values below are passed to the handler creator callable
1846 # as keyword arguments.
1847 'owner': ['pulse', 'pulse'],
1848 'filename': 'chowntest.log',
1849 'mode': 'w',
1850 'encoding': 'utf-8',
1851 },
1852 },
1853 'root': {
1854 'handlers': ['file'],
1855 'level': 'DEBUG',
1856 },
1857 }
1858
1859 logging.config.dictConfig(LOGGING)
1860 logger = logging.getLogger('mylogger')
1861 logger.debug('A debug message')
1862
1863To run this, you will probably need to run as ``root``::
1864
1865 $ sudo python3.3 chowntest.py
1866 $ cat chowntest.log
1867 2013-11-05 09:34:51,128 DEBUG mylogger A debug message
1868 $ ls -l chowntest.log
1869 -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
1870
1871Note that this example uses Python 3.3 because that's where :func:`shutil.chown`
1872makes an appearance. This approach should work with any Python version that
1873supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3
1874versions, you would need to implement the actual ownership change using e.g.
1875:func:`os.chown`.
1876
1877In practice, the handler-creating function may be in a utility module somewhere
1878in your project. Instead of the line in the configuration::
1879
1880 '()': owned_file_handler,
1881
1882you could use e.g.::
1883
1884 '()': 'ext://project.util.owned_file_handler',
1885
1886where ``project.util`` can be replaced with the actual name of the package
1887where the function resides. In the above working script, using
1888``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable
1889is resolved by :func:`dictConfig` from the ``ext://`` specification.
1890
1891This example hopefully also points the way to how you could implement other
1892types of file change - e.g. setting specific POSIX permission bits - in the
1893same way, using :func:`os.chmod`.
1894
1895Of course, the approach could also be extended to types of handler other than a
1896:class:`~logging.FileHandler` - for example, one of the rotating file handlers,
1897or a different type of handler altogether.
1898
Vinay Sajipcbefe3b2014-01-15 15:09:05 +00001899
1900.. currentmodule:: logging
1901
1902.. _formatting-styles:
1903
1904Using particular formatting styles throughout your application
1905--------------------------------------------------------------
1906
1907In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword
1908parameter which, while defaulting to ``%`` for backward compatibility, allowed
1909the specification of ``{`` or ``$`` to support the formatting approaches
1910supported by :meth:`str.format` and :class:`string.Template`. Note that this
1911governs the formatting of logging messages for final output to logs, and is
1912completely orthogonal to how an individual logging message is constructed.
1913
1914Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take
1915positional parameters for the actual logging message itself, with keyword
1916parameters used only for determining options for how to handle the logging call
1917(e.g. the ``exc_info`` keyword parameter to indicate that traceback information
1918should be logged, or the ``extra`` keyword parameter to indicate additional
1919contextual information to be added to the log). So you cannot directly make
1920logging calls using :meth:`str.format` or :class:`string.Template` syntax,
1921because internally the logging package uses %-formatting to merge the format
1922string and the variable arguments. There would no changing this while preserving
1923backward compatibility, since all logging calls which are out there in existing
1924code will be using %-format strings.
1925
1926There have been suggestions to associate format styles with specific loggers,
1927but that approach also runs into backward compatibility problems because any
1928existing code could be using a given logger name and using %-formatting.
1929
1930For logging to work interoperably between any third-party libraries and your
1931code, decisions about formatting need to be made at the level of the
1932individual logging call. This opens up a couple of ways in which alternative
1933formatting styles can be accommodated.
1934
1935
1936Using LogRecord factories
1937^^^^^^^^^^^^^^^^^^^^^^^^^
1938
1939In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned
1940above, the logging package gained the ability to allow users to set their own
1941:class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function.
1942You can use this to set your own subclass of :class:`LogRecord`, which does the
1943Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base
1944class implementation of this method is where the ``msg % args`` formatting
1945happens, and where you can substitute your alternate formatting; however, you
1946should be careful to support all formatting styles and allow %-formatting as
1947the default, to ensure interoperability with other code. Care should also be
1948taken to call ``str(self.msg)``, just as the base implementation does.
1949
1950Refer to the reference documentation on :func:`setLogRecordFactory` and
1951:class:`LogRecord` for more information.
1952
1953
1954Using custom message objects
1955^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1956
1957There is another, perhaps simpler way that you can use {}- and $- formatting to
1958construct your individual log messages. You may recall (from
1959:ref:`arbitrary-object-messages`) that when logging you can use an arbitrary
1960object as a message format string, and that the logging package will call
1961:func:`str` on that object to get the actual format string. Consider the
1962following two classes::
1963
1964 class BraceMessage(object):
1965 def __init__(self, fmt, *args, **kwargs):
1966 self.fmt = fmt
1967 self.args = args
1968 self.kwargs = kwargs
1969
1970 def __str__(self):
1971 return self.fmt.format(*self.args, **self.kwargs)
1972
1973 class DollarMessage(object):
1974 def __init__(self, fmt, **kwargs):
1975 self.fmt = fmt
1976 self.kwargs = kwargs
1977
1978 def __str__(self):
1979 from string import Template
1980 return Template(self.fmt).substitute(**self.kwargs)
1981
1982Either of these can be used in place of a format string, to allow {}- or
1983$-formatting to be used to build the actual "message" part which appears in the
1984formatted log output in place of “%(message)s or “{message}” or $message”.
1985If you find it a little unwieldy to use the class names whenever you want to log
1986something, you can make it more palatable if you use an alias such as ``M`` or
1987``_`` for the message (or perhaps ``__``, if you are using ``_`` for
1988localization).
1989
Vinay Sajipeb14dec2014-01-17 18:36:02 +00001990Examples of this approach are given below. Firstly, formatting with
1991:meth:`str.format`::
1992
1993 >>> __ = BraceMessage
1994 >>> print(__('Message with {0} {1}', 2, 'placeholders'))
1995 Message with 2 placeholders
1996 >>> class Point: pass
1997 ...
1998 >>> p = Point()
1999 >>> p.x = 0.5
2000 >>> p.y = 0.5
2001 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
2002 Message with coordinates: (0.50, 0.50)
2003
2004Secondly, formatting with :class:`string.Template`::
2005
2006 >>> __ = DollarMessage
2007 >>> print(__('Message with $num $what', num=2, what='placeholders'))
2008 Message with 2 placeholders
2009 >>>
2010
2011One thing to note is that you pay no significant performance penalty with this
2012approach: the actual formatting happens not when you make the logging call, but
2013when (and if) the logged message is actually about to be output to a log by a
2014handler. So the only slightly unusual thing which might trip you up is that the
2015parentheses go around the format string and the arguments, not just the format
2016string. Thats because the __ notation is just syntax sugar for a constructor
2017call to one of the ``XXXMessage`` classes shown above.
Vinay Sajip554f22f2014-02-03 11:51:45 +00002018
2019
2020.. _filters-dictconfig:
2021
2022.. currentmodule:: logging.config
2023
2024Configuring filters with :func:`dictConfig`
2025-------------------------------------------
2026
2027You *can* configure filters using :func:`~logging.config.dictConfig`, though it
2028might not be obvious at first glance how to do it (hence this recipe). Since
2029:class:`~logging.Filter` is the only filter class included in the standard
2030library, and it is unlikely to cater to many requirements (it's only there as a
2031base class), you will typically need to define your own :class:`~logging.Filter`
2032subclass with an overridden :meth:`~logging.Filter.filter` method. To do this,
2033specify the ``()`` key in the configuration dictionary for the filter,
2034specifying a callable which will be used to create the filter (a class is the
2035most obvious, but you can provide any callable which returns a
2036:class:`~logging.Filter` instance). Here is a complete example::
2037
2038 import logging
2039 import logging.config
2040 import sys
2041
2042 class MyFilter(logging.Filter):
2043 def __init__(self, param=None):
2044 self.param = param
2045
2046 def filter(self, record):
2047 if self.param is None:
2048 allow = True
2049 else:
2050 allow = self.param not in record.msg
2051 if allow:
2052 record.msg = 'changed: ' + record.msg
2053 return allow
2054
2055 LOGGING = {
2056 'version': 1,
2057 'filters': {
2058 'myfilter': {
2059 '()': MyFilter,
2060 'param': 'noshow',
2061 }
2062 },
2063 'handlers': {
2064 'console': {
2065 'class': 'logging.StreamHandler',
2066 'filters': ['myfilter']
2067 }
2068 },
2069 'root': {
2070 'level': 'DEBUG',
2071 'handlers': ['console']
2072 },
2073 }
2074
2075 if __name__ == '__main__':
2076 logging.config.dictConfig(LOGGING)
2077 logging.debug('hello')
2078 logging.debug('hello - noshow')
2079
2080This example shows how you can pass configuration data to the callable which
2081constructs the instance, in the form of keyword parameters. When run, the above
2082script will print::
2083
2084 changed: hello
2085
2086which shows that the filter is working as configured.
2087
2088A couple of extra points to note:
2089
2090* If you can't refer to the callable directly in the configuration (e.g. if it
2091 lives in a different module, and you can't import it directly where the
2092 configuration dictionary is), you can use the form ``ext://...`` as described
2093 in :ref:`logging-config-dict-externalobj`. For example, you could have used
2094 the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above
2095 example.
2096
2097* As well as for filters, this technique can also be used to configure custom
2098 handlers and formatters. See :ref:`logging-config-dict-userdef` for more
2099 information on how logging supports using user-defined objects in its
2100 configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
2101
Vinay Sajipdb071642015-01-28 07:32:38 +00002102
2103.. _custom-format-exception:
2104
2105Customized exception formatting
2106-------------------------------
2107
2108There might be times when you want to do customized exception formatting - for
2109argument's sake, let's say you want exactly one line per logged event, even
2110when exception information is present. You can do this with a custom formatter
2111class, as shown in the following example::
2112
2113 import logging
2114
2115 class OneLineExceptionFormatter(logging.Formatter):
2116 def formatException(self, exc_info):
2117 """
2118 Format an exception so that it prints on a single line.
2119 """
2120 result = super(OneLineExceptionFormatter, self).formatException(exc_info)
Serhiy Storchakadba90392016-05-10 12:01:23 +03002121 return repr(result) # or format into one line however you want to
Vinay Sajipdb071642015-01-28 07:32:38 +00002122
2123 def format(self, record):
2124 s = super(OneLineExceptionFormatter, self).format(record)
2125 if record.exc_text:
2126 s = s.replace('\n', '') + '|'
2127 return s
2128
2129 def configure_logging():
2130 fh = logging.FileHandler('output.txt', 'w')
2131 f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
2132 '%d/%m/%Y %H:%M:%S')
2133 fh.setFormatter(f)
2134 root = logging.getLogger()
2135 root.setLevel(logging.DEBUG)
2136 root.addHandler(fh)
2137
2138 def main():
2139 configure_logging()
2140 logging.info('Sample message')
2141 try:
2142 x = 1 / 0
2143 except ZeroDivisionError as e:
2144 logging.exception('ZeroDivisionError: %s', e)
2145
2146 if __name__ == '__main__':
2147 main()
2148
2149When run, this produces a file with exactly two lines::
2150
2151 28/01/2015 07:21:23|INFO|Sample message|
2152 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'|
2153
2154While the above treatment is simplistic, it points the way to how exception
2155information can be formatted to your liking. The :mod:`traceback` module may be
2156helpful for more specialized needs.
Vinay Sajipf046dfe2015-02-01 15:17:34 +00002157
2158.. _spoken-messages:
2159
2160Speaking logging messages
2161-------------------------
2162
2163There might be situations when it is desirable to have logging messages rendered
2164in an audible rather than a visible format. This is easy to do if you have text-
2165to-speech (TTS) functionality available in your system, even if it doesn't have
2166a Python binding. Most TTS systems have a command line program you can run, and
2167this can be invoked from a handler using :mod:`subprocess`. It's assumed here
2168that TTS command line programs won't expect to interact with users or take a
2169long time to complete, and that the frequency of logged messages will be not so
2170high as to swamp the user with messages, and that it's acceptable to have the
2171messages spoken one at a time rather than concurrently, The example implementation
2172below waits for one message to be spoken before the next is processed, and this
2173might cause other handlers to be kept waiting. Here is a short example showing
2174the approach, which assumes that the ``espeak`` TTS package is available::
2175
2176 import logging
2177 import subprocess
2178 import sys
2179
2180 class TTSHandler(logging.Handler):
2181 def emit(self, record):
2182 msg = self.format(record)
2183 # Speak slowly in a female English voice
2184 cmd = ['espeak', '-s150', '-ven+f3', msg]
2185 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
2186 stderr=subprocess.STDOUT)
2187 # wait for the program to finish
2188 p.communicate()
2189
2190 def configure_logging():
2191 h = TTSHandler()
2192 root = logging.getLogger()
2193 root.addHandler(h)
2194 # the default formatter just returns the message
2195 root.setLevel(logging.DEBUG)
2196
2197 def main():
2198 logging.info('Hello')
2199 logging.debug('Goodbye')
2200
2201 if __name__ == '__main__':
2202 configure_logging()
2203 sys.exit(main())
2204
2205When run, this script should say "Hello" and then "Goodbye" in a female voice.
2206
2207The above approach can, of course, be adapted to other TTS systems and even
2208other systems altogether which can process messages via external programs run
2209from a command line.
2210
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002211
2212.. _buffered-logging:
2213
2214Buffering logging messages and outputting them conditionally
2215------------------------------------------------------------
2216
2217There might be situations where you want to log messages in a temporary area
2218and only output them if a certain condition occurs. For example, you may want to
2219start logging debug events in a function, and if the function completes without
2220errors, you don't want to clutter the log with the collected debug information,
2221but if there is an error, you want all the debug information to be output as well
2222as the error.
2223
2224Here is an example which shows how you could do this using a decorator for your
2225functions where you want logging to behave this way. It makes use of the
2226:class:`logging.handlers.MemoryHandler`, which allows buffering of logged events
2227until some condition occurs, at which point the buffered events are ``flushed``
2228- passed to another handler (the ``target`` handler) for processing. By default,
2229the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose
2230level is greater than or equal to a specified threshold is seen. You can use this
2231recipe with a more specialised subclass of ``MemoryHandler`` if you want custom
2232flushing behavior.
2233
2234The example script has a simple function, ``foo``, which just cycles through
2235all the logging levels, writing to ``sys.stderr`` to say what level it's about
Martin Panterf05641642016-05-08 13:48:10 +00002236to log at, and then actually logging a message at that level. You can pass a
Vinay Sajipff1f3d92015-10-10 00:52:35 +01002237parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
2238otherwise, it only logs at DEBUG, INFO and WARNING levels.
2239
2240The script just arranges to decorate ``foo`` with a decorator which will do the
2241conditional logging that's required. The decorator takes a logger as a parameter
2242and attaches a memory handler for the duration of the call to the decorated
2243function. The decorator can be additionally parameterised using a target handler,
2244a level at which flushing should occur, and a capacity for the buffer. These
2245default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``,
2246``logging.ERROR`` and ``100`` respectively.
2247
2248Here's the script::
2249
2250 import logging
2251 from logging.handlers import MemoryHandler
2252 import sys
2253
2254 logger = logging.getLogger(__name__)
2255 logger.addHandler(logging.NullHandler())
2256
2257 def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
2258 if target_handler is None:
2259 target_handler = logging.StreamHandler()
2260 if flush_level is None:
2261 flush_level = logging.ERROR
2262 if capacity is None:
2263 capacity = 100
2264 handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)
2265
2266 def decorator(fn):
2267 def wrapper(*args, **kwargs):
2268 logger.addHandler(handler)
2269 try:
2270 return fn(*args, **kwargs)
2271 except Exception:
2272 logger.exception('call failed')
2273 raise
2274 finally:
2275 super(MemoryHandler, handler).flush()
2276 logger.removeHandler(handler)
2277 return wrapper
2278
2279 return decorator
2280
2281 def write_line(s):
2282 sys.stderr.write('%s\n' % s)
2283
2284 def foo(fail=False):
2285 write_line('about to log at DEBUG ...')
2286 logger.debug('Actually logged at DEBUG')
2287 write_line('about to log at INFO ...')
2288 logger.info('Actually logged at INFO')
2289 write_line('about to log at WARNING ...')
2290 logger.warning('Actually logged at WARNING')
2291 if fail:
2292 write_line('about to log at ERROR ...')
2293 logger.error('Actually logged at ERROR')
2294 write_line('about to log at CRITICAL ...')
2295 logger.critical('Actually logged at CRITICAL')
2296 return fail
2297
2298 decorated_foo = log_if_errors(logger)(foo)
2299
2300 if __name__ == '__main__':
2301 logger.setLevel(logging.DEBUG)
2302 write_line('Calling undecorated foo with False')
2303 assert not foo(False)
2304 write_line('Calling undecorated foo with True')
2305 assert foo(True)
2306 write_line('Calling decorated foo with False')
2307 assert not decorated_foo(False)
2308 write_line('Calling decorated foo with True')
2309 assert decorated_foo(True)
2310
2311When this script is run, the following output should be observed::
2312
2313 Calling undecorated foo with False
2314 about to log at DEBUG ...
2315 about to log at INFO ...
2316 about to log at WARNING ...
2317 Calling undecorated foo with True
2318 about to log at DEBUG ...
2319 about to log at INFO ...
2320 about to log at WARNING ...
2321 about to log at ERROR ...
2322 about to log at CRITICAL ...
2323 Calling decorated foo with False
2324 about to log at DEBUG ...
2325 about to log at INFO ...
2326 about to log at WARNING ...
2327 Calling decorated foo with True
2328 about to log at DEBUG ...
2329 about to log at INFO ...
2330 about to log at WARNING ...
2331 about to log at ERROR ...
2332 Actually logged at DEBUG
2333 Actually logged at INFO
2334 Actually logged at WARNING
2335 Actually logged at ERROR
2336 about to log at CRITICAL ...
2337 Actually logged at CRITICAL
2338
2339As you can see, actual logging output only occurs when an event is logged whose
2340severity is ERROR or greater, but in that case, any previous events at lower
2341severities are also logged.
2342
2343You can of course use the conventional means of decoration::
2344
2345 @log_if_errors(logger)
2346 def foo(fail=False):
2347 ...
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002348
2349
2350.. _utc-formatting:
2351
2352Formatting times using UTC (GMT) via configuration
2353--------------------------------------------------
2354
2355Sometimes you want to format times using UTC, which can be done using a class
2356such as `UTCFormatter`, shown below::
2357
2358 import logging
2359 import time
2360
2361 class UTCFormatter(logging.Formatter):
2362 converter = time.gmtime
2363
Berker Peksagf84499a2015-10-20 03:41:38 +03002364and you can then use the ``UTCFormatter`` in your code instead of
Vinay Sajip4de9dae2015-10-17 13:58:19 +01002365:class:`~logging.Formatter`. If you want to do that via configuration, you can
2366use the :func:`~logging.config.dictConfig` API with an approach illustrated by
2367the following complete example::
2368
2369 import logging
2370 import logging.config
2371 import time
2372
2373 class UTCFormatter(logging.Formatter):
2374 converter = time.gmtime
2375
2376 LOGGING = {
2377 'version': 1,
2378 'disable_existing_loggers': False,
2379 'formatters': {
2380 'utc': {
2381 '()': UTCFormatter,
2382 'format': '%(asctime)s %(message)s',
2383 },
2384 'local': {
2385 'format': '%(asctime)s %(message)s',
2386 }
2387 },
2388 'handlers': {
2389 'console1': {
2390 'class': 'logging.StreamHandler',
2391 'formatter': 'utc',
2392 },
2393 'console2': {
2394 'class': 'logging.StreamHandler',
2395 'formatter': 'local',
2396 },
2397 },
2398 'root': {
2399 'handlers': ['console1', 'console2'],
2400 }
2401 }
2402
2403 if __name__ == '__main__':
2404 logging.config.dictConfig(LOGGING)
2405 logging.warning('The local time is %s', time.asctime())
2406
2407When this script is run, it should print something like::
2408
2409 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2410 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2411
2412showing how the time is formatted both as local time and UTC, one for each
2413handler.
Vinay Sajipd93a6012016-04-01 23:13:01 +01002414
2415
2416.. _context-manager:
2417
2418Using a context manager for selective logging
2419---------------------------------------------
2420
2421There are times when it would be useful to temporarily change the logging
2422configuration and revert it back after doing something. For this, a context
2423manager is the most obvious way of saving and restoring the logging context.
2424Here is a simple example of such a context manager, which allows you to
2425optionally change the logging level and add a logging handler purely in the
2426scope of the context manager::
2427
2428 import logging
2429 import sys
2430
2431 class LoggingContext(object):
2432 def __init__(self, logger, level=None, handler=None, close=True):
2433 self.logger = logger
2434 self.level = level
2435 self.handler = handler
2436 self.close = close
2437
2438 def __enter__(self):
2439 if self.level is not None:
2440 self.old_level = self.logger.level
2441 self.logger.setLevel(self.level)
2442 if self.handler:
2443 self.logger.addHandler(self.handler)
2444
2445 def __exit__(self, et, ev, tb):
2446 if self.level is not None:
2447 self.logger.setLevel(self.old_level)
2448 if self.handler:
2449 self.logger.removeHandler(self.handler)
2450 if self.handler and self.close:
2451 self.handler.close()
2452 # implicit return of None => don't swallow exceptions
2453
2454If you specify a level value, the logger's level is set to that value in the
2455scope of the with block covered by the context manager. If you specify a
2456handler, it is added to the logger on entry to the block and removed on exit
2457from the block. You can also ask the manager to close the handler for you on
2458block exit - you could do this if you don't need the handler any more.
2459
2460To illustrate how it works, we can add the following block of code to the
2461above::
2462
2463 if __name__ == '__main__':
2464 logger = logging.getLogger('foo')
2465 logger.addHandler(logging.StreamHandler())
2466 logger.setLevel(logging.INFO)
2467 logger.info('1. This should appear just once on stderr.')
2468 logger.debug('2. This should not appear.')
2469 with LoggingContext(logger, level=logging.DEBUG):
2470 logger.debug('3. This should appear once on stderr.')
2471 logger.debug('4. This should not appear.')
2472 h = logging.StreamHandler(sys.stdout)
2473 with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
2474 logger.debug('5. This should appear twice - once on stderr and once on stdout.')
2475 logger.info('6. This should appear just once on stderr.')
2476 logger.debug('7. This should not appear.')
2477
2478We initially set the logger's level to ``INFO``, so message #1 appears and
2479message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the
2480following ``with`` block, and so message #3 appears. After the block exits, the
2481logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the
2482next ``with`` block, we set the level to ``DEBUG`` again but also add a handler
2483writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once
2484via ``stderr`` and once via ``stdout``). After the ``with`` statement's
2485completion, the status is as it was before so message #6 appears (like message
2486#1) whereas message #7 doesn't (just like message #2).
2487
2488If we run the resulting script, the result is as follows::
2489
2490 $ python logctx.py
2491 1. This should appear just once on stderr.
2492 3. This should appear once on stderr.
2493 5. This should appear twice - once on stderr and once on stdout.
2494 5. This should appear twice - once on stderr and once on stdout.
2495 6. This should appear just once on stderr.
2496
2497If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
2498which is the only message written to ``stdout``::
2499
2500 $ python logctx.py 2>/dev/null
2501 5. This should appear twice - once on stderr and once on stdout.
2502
2503Once again, but piping ``stdout`` to ``/dev/null``, we get::
2504
2505 $ python logctx.py >/dev/null
2506 1. This should appear just once on stderr.
2507 3. This should appear once on stderr.
2508 5. This should appear twice - once on stderr and once on stdout.
2509 6. This should appear just once on stderr.
2510
2511In this case, the message #5 printed to ``stdout`` doesn't appear, as expected.
2512
2513Of course, the approach described here can be generalised, for example to attach
2514logging filters temporarily. Note that the above code works in Python 2 as well
2515as Python 3.