blob: 82c8f51382b841714a72af20961f771dcaf55b4f [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')
66 def do_something(self):
67 self.logger.info('doing something')
68 a = 1 + 1
69 self.logger.info('done doing something')
70
71 def some_function():
72 module_logger.info('received a call to "some_function"')
73
74The output looks like this::
75
76 2005-03-23 23:47:11,663 - spam_application - INFO -
77 creating an instance of auxiliary_module.Auxiliary
78 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
79 creating an instance of Auxiliary
80 2005-03-23 23:47:11,665 - spam_application - INFO -
81 created an instance of auxiliary_module.Auxiliary
82 2005-03-23 23:47:11,668 - spam_application - INFO -
83 calling auxiliary_module.Auxiliary.do_something
84 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
85 doing something
86 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
87 done doing something
88 2005-03-23 23:47:11,670 - spam_application - INFO -
89 finished auxiliary_module.Auxiliary.do_something
90 2005-03-23 23:47:11,671 - spam_application - INFO -
91 calling auxiliary_module.some_function()
92 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
93 received a call to 'some_function'
94 2005-03-23 23:47:11,673 - spam_application - INFO -
95 done with auxiliary_module.some_function()
96
97Multiple handlers and formatters
98--------------------------------
99
Vinay Sajip67f39772013-08-17 00:39:42 +0100100Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has no
101minimum or maximum quota for the number of handlers you may add. Sometimes it
102will be beneficial for an application to log all messages of all severities to a
103text file while simultaneously logging errors or above to the console. To set
104this up, simply configure the appropriate handlers. The logging calls in the
Vinay Sajipc63619b2010-12-19 12:56:57 +0000105application code will remain unchanged. Here is a slight modification to the
106previous simple module-based configuration example::
107
108 import logging
109
110 logger = logging.getLogger('simple_example')
111 logger.setLevel(logging.DEBUG)
112 # create file handler which logs even debug messages
113 fh = logging.FileHandler('spam.log')
114 fh.setLevel(logging.DEBUG)
115 # create console handler with a higher log level
116 ch = logging.StreamHandler()
117 ch.setLevel(logging.ERROR)
118 # create formatter and add it to the handlers
119 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
120 ch.setFormatter(formatter)
121 fh.setFormatter(formatter)
122 # add the handlers to logger
123 logger.addHandler(ch)
124 logger.addHandler(fh)
125
126 # 'application' code
127 logger.debug('debug message')
128 logger.info('info message')
129 logger.warn('warn message')
130 logger.error('error message')
131 logger.critical('critical message')
132
133Notice that the 'application' code does not care about multiple handlers. All
134that changed was the addition and configuration of a new handler named *fh*.
135
136The ability to create new handlers with higher- or lower-severity filters can be
137very helpful when writing and testing an application. Instead of using many
138``print`` statements for debugging, use ``logger.debug``: Unlike the print
139statements, which you will have to delete or comment out later, the logger.debug
140statements can remain intact in the source code and remain dormant until you
141need them again. At that time, the only change that needs to happen is to
142modify the severity level of the logger and/or handler to debug.
143
144.. _multiple-destinations:
145
146Logging to multiple destinations
147--------------------------------
148
149Let's say you want to log to console and file with different message formats and
150in differing circumstances. Say you want to log messages with levels of DEBUG
151and higher to file, and those messages at level INFO and higher to the console.
152Let's also assume that the file should contain timestamps, but the console
153messages should not. Here's how you can achieve this::
154
155 import logging
156
157 # set up logging to file - see previous section for more details
158 logging.basicConfig(level=logging.DEBUG,
159 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
160 datefmt='%m-%d %H:%M',
161 filename='/temp/myapp.log',
162 filemode='w')
163 # define a Handler which writes INFO messages or higher to the sys.stderr
164 console = logging.StreamHandler()
165 console.setLevel(logging.INFO)
166 # set a format which is simpler for console use
167 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
168 # tell the handler to use this format
169 console.setFormatter(formatter)
170 # add the handler to the root logger
171 logging.getLogger('').addHandler(console)
172
173 # Now, we can log to the root logger, or any other logger. First the root...
174 logging.info('Jackdaws love my big sphinx of quartz.')
175
176 # Now, define a couple of other loggers which might represent areas in your
177 # application:
178
179 logger1 = logging.getLogger('myapp.area1')
180 logger2 = logging.getLogger('myapp.area2')
181
182 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
183 logger1.info('How quickly daft jumping zebras vex.')
184 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
185 logger2.error('The five boxing wizards jump quickly.')
186
187When you run this, on the console you will see ::
188
189 root : INFO Jackdaws love my big sphinx of quartz.
190 myapp.area1 : INFO How quickly daft jumping zebras vex.
191 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
192 myapp.area2 : ERROR The five boxing wizards jump quickly.
193
194and in the file you will see something like ::
195
196 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
197 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
198 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
199 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
200 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
201
202As you can see, the DEBUG message only shows up in the file. The other messages
203are sent to both destinations.
204
205This example uses console and file handlers, but you can use any number and
206combination of handlers you choose.
207
208
209Configuration server example
210----------------------------
211
212Here is an example of a module using the logging configuration server::
213
214 import logging
215 import logging.config
216 import time
217 import os
218
219 # read initial config file
220 logging.config.fileConfig('logging.conf')
221
222 # create and start listener on port 9999
223 t = logging.config.listen(9999)
224 t.start()
225
226 logger = logging.getLogger('simpleExample')
227
228 try:
229 # loop through logging calls to see the difference
230 # new configurations make, until Ctrl+C is pressed
231 while True:
232 logger.debug('debug message')
233 logger.info('info message')
234 logger.warn('warn message')
235 logger.error('error message')
236 logger.critical('critical message')
237 time.sleep(5)
238 except KeyboardInterrupt:
239 # cleanup
240 logging.config.stopListening()
241 t.join()
242
243And here is a script that takes a filename and sends that file to the server,
244properly preceded with the binary-encoded length, as the new logging
245configuration::
246
247 #!/usr/bin/env python
248 import socket, sys, struct
249
Vinay Sajip689b68a2010-12-22 15:04:15 +0000250 with open(sys.argv[1], 'rb') as f:
251 data_to_send = f.read()
Vinay Sajipc63619b2010-12-19 12:56:57 +0000252
253 HOST = 'localhost'
254 PORT = 9999
255 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
256 print('connecting...')
257 s.connect((HOST, PORT))
258 print('sending config...')
259 s.send(struct.pack('>L', len(data_to_send)))
260 s.send(data_to_send)
261 s.close()
262 print('complete')
263
264
265Dealing with handlers that block
266--------------------------------
267
268.. currentmodule:: logging.handlers
269
270Sometimes you have to get your logging handlers to do their work without
Vinay Sajip6b883a22012-02-27 11:02:45 +0000271blocking the thread you're logging from. This is common in Web applications,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000272though of course it also occurs in other scenarios.
273
274A common culprit which demonstrates sluggish behaviour is the
275:class:`SMTPHandler`: sending emails can take a long time, for a
Vinay Sajip6b883a22012-02-27 11:02:45 +0000276number of reasons outside the developer's control (for example, a poorly
Vinay Sajipc63619b2010-12-19 12:56:57 +0000277performing mail or network infrastructure). But almost any network-based
278handler can block: Even a :class:`SocketHandler` operation may do a
279DNS query under the hood which is too slow (and this query can be deep in the
280socket library code, below the Python layer, and outside your control).
281
282One solution is to use a two-part approach. For the first part, attach only a
283:class:`QueueHandler` to those loggers which are accessed from
284performance-critical threads. They simply write to their queue, which can be
285sized to a large enough capacity or initialized with no upper bound to their
286size. The write to the queue will typically be accepted quickly, though you
Georg Brandl375aec22011-01-15 17:03:02 +0000287will probably need to catch the :exc:`queue.Full` exception as a precaution
Vinay Sajipc63619b2010-12-19 12:56:57 +0000288in your code. If you are a library developer who has performance-critical
289threads in their code, be sure to document this (together with a suggestion to
290attach only ``QueueHandlers`` to your loggers) for the benefit of other
291developers who will use your code.
292
293The second part of the solution is :class:`QueueListener`, which has been
294designed as the counterpart to :class:`QueueHandler`. A
Vinay Sajip6b883a22012-02-27 11:02:45 +0000295:class:`QueueListener` is very simple: it's passed a queue and some handlers,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000296and it fires up an internal thread which listens to its queue for LogRecords
297sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
298matter). The ``LogRecords`` are removed from the queue and passed to the
299handlers for processing.
300
301The advantage of having a separate :class:`QueueListener` class is that you
302can use the same instance to service multiple ``QueueHandlers``. This is more
303resource-friendly than, say, having threaded versions of the existing handler
304classes, which would eat up one thread per handler for no particular benefit.
305
306An example of using these two classes follows (imports omitted)::
307
308 que = queue.Queue(-1) # no limit on size
309 queue_handler = QueueHandler(que)
310 handler = logging.StreamHandler()
311 listener = QueueListener(que, handler)
312 root = logging.getLogger()
313 root.addHandler(queue_handler)
314 formatter = logging.Formatter('%(threadName)s: %(message)s')
315 handler.setFormatter(formatter)
316 listener.start()
317 # The log output will display the thread which generated
318 # the event (the main thread) rather than the internal
319 # thread which monitors the internal queue. This is what
320 # you want to happen.
321 root.warning('Look out!')
322 listener.stop()
323
324which, when run, will produce::
325
326 MainThread: Look out!
327
328
329.. _network-logging:
330
331Sending and receiving logging events across a network
332-----------------------------------------------------
333
334Let's say you want to send logging events across a network, and handle them at
335the receiving end. A simple way of doing this is attaching a
336:class:`SocketHandler` instance to the root logger at the sending end::
337
338 import logging, logging.handlers
339
340 rootLogger = logging.getLogger('')
341 rootLogger.setLevel(logging.DEBUG)
342 socketHandler = logging.handlers.SocketHandler('localhost',
343 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
344 # don't bother with a formatter, since a socket handler sends the event as
345 # an unformatted pickle
346 rootLogger.addHandler(socketHandler)
347
348 # Now, we can log to the root logger, or any other logger. First the root...
349 logging.info('Jackdaws love my big sphinx of quartz.')
350
351 # Now, define a couple of other loggers which might represent areas in your
352 # application:
353
354 logger1 = logging.getLogger('myapp.area1')
355 logger2 = logging.getLogger('myapp.area2')
356
357 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
358 logger1.info('How quickly daft jumping zebras vex.')
359 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
360 logger2.error('The five boxing wizards jump quickly.')
361
362At the receiving end, you can set up a receiver using the :mod:`socketserver`
363module. Here is a basic working example::
364
365 import pickle
366 import logging
367 import logging.handlers
368 import socketserver
369 import struct
370
371
372 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
373 """Handler for a streaming logging request.
374
375 This basically logs the record using whatever logging policy is
376 configured locally.
377 """
378
379 def handle(self):
380 """
381 Handle multiple requests - each expected to be a 4-byte length,
382 followed by the LogRecord in pickle format. Logs the record
383 according to whatever policy is configured locally.
384 """
385 while True:
386 chunk = self.connection.recv(4)
387 if len(chunk) < 4:
388 break
389 slen = struct.unpack('>L', chunk)[0]
390 chunk = self.connection.recv(slen)
391 while len(chunk) < slen:
392 chunk = chunk + self.connection.recv(slen - len(chunk))
393 obj = self.unPickle(chunk)
394 record = logging.makeLogRecord(obj)
395 self.handleLogRecord(record)
396
397 def unPickle(self, data):
398 return pickle.loads(data)
399
400 def handleLogRecord(self, record):
401 # if a name is specified, we use the named logger rather than the one
402 # implied by the record.
403 if self.server.logname is not None:
404 name = self.server.logname
405 else:
406 name = record.name
407 logger = logging.getLogger(name)
408 # N.B. EVERY record gets logged. This is because Logger.handle
409 # is normally called AFTER logger-level filtering. If you want
410 # to do filtering, do it at the client end to save wasting
411 # cycles and network bandwidth!
412 logger.handle(record)
413
414 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
415 """
416 Simple TCP socket-based logging receiver suitable for testing.
417 """
418
Raymond Hettinger4ab532b2014-03-28 16:39:25 -0700419 allow_reuse_address = True
Vinay Sajipc63619b2010-12-19 12:56:57 +0000420
421 def __init__(self, host='localhost',
422 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
423 handler=LogRecordStreamHandler):
424 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
425 self.abort = 0
426 self.timeout = 1
427 self.logname = None
428
429 def serve_until_stopped(self):
430 import select
431 abort = 0
432 while not abort:
433 rd, wr, ex = select.select([self.socket.fileno()],
434 [], [],
435 self.timeout)
436 if rd:
437 self.handle_request()
438 abort = self.abort
439
440 def main():
441 logging.basicConfig(
442 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
443 tcpserver = LogRecordSocketReceiver()
444 print('About to start TCP server...')
445 tcpserver.serve_until_stopped()
446
447 if __name__ == '__main__':
448 main()
449
450First run the server, and then the client. On the client side, nothing is
451printed on the console; on the server side, you should see something like::
452
453 About to start TCP server...
454 59 root INFO Jackdaws love my big sphinx of quartz.
455 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
456 69 myapp.area1 INFO How quickly daft jumping zebras vex.
457 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
458 69 myapp.area2 ERROR The five boxing wizards jump quickly.
459
460Note that there are some security issues with pickle in some scenarios. If
461these affect you, you can use an alternative serialization scheme by overriding
Vinay Sajip67f39772013-08-17 00:39:42 +0100462the :meth:`~handlers.SocketHandler.makePickle` method and implementing your
463alternative there, as well as adapting the above script to use your alternative
464serialization.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000465
466
467.. _context-info:
468
469Adding contextual information to your logging output
470----------------------------------------------------
471
472Sometimes you want logging output to contain contextual information in
473addition to the parameters passed to the logging call. For example, in a
474networked application, it may be desirable to log client-specific information
475in the log (e.g. remote client's username, or IP address). Although you could
476use the *extra* parameter to achieve this, it's not always convenient to pass
477the information in this way. While it might be tempting to create
478:class:`Logger` instances on a per-connection basis, this is not a good idea
479because these instances are not garbage collected. While this is not a problem
480in practice, when the number of :class:`Logger` instances is dependent on the
481level of granularity you want to use in logging an application, it could
482be hard to manage if the number of :class:`Logger` instances becomes
483effectively unbounded.
484
485
486Using LoggerAdapters to impart contextual information
487^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
488
489An easy way in which you can pass contextual information to be output along
490with logging event information is to use the :class:`LoggerAdapter` class.
491This class is designed to look like a :class:`Logger`, so that you can call
492:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
493:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
494same signatures as their counterparts in :class:`Logger`, so you can use the
495two types of instances interchangeably.
496
497When you create an instance of :class:`LoggerAdapter`, you pass it a
498:class:`Logger` instance and a dict-like object which contains your contextual
499information. When you call one of the logging methods on an instance of
500:class:`LoggerAdapter`, it delegates the call to the underlying instance of
501:class:`Logger` passed to its constructor, and arranges to pass the contextual
502information in the delegated call. Here's a snippet from the code of
503:class:`LoggerAdapter`::
504
505 def debug(self, msg, *args, **kwargs):
506 """
507 Delegate a debug call to the underlying logger, after adding
508 contextual information from this adapter instance.
509 """
510 msg, kwargs = self.process(msg, kwargs)
511 self.logger.debug(msg, *args, **kwargs)
512
Vinay Sajip67f39772013-08-17 00:39:42 +0100513The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the
514contextual information is added to the logging output. It's passed the message
515and keyword arguments of the logging call, and it passes back (potentially)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000516modified versions of these to use in the call to the underlying logger. The
517default implementation of this method leaves the message alone, but inserts
518an 'extra' key in the keyword argument whose value is the dict-like object
519passed to the constructor. Of course, if you had passed an 'extra' keyword
520argument in the call to the adapter, it will be silently overwritten.
521
522The advantage of using 'extra' is that the values in the dict-like object are
523merged into the :class:`LogRecord` instance's __dict__, allowing you to use
524customized strings with your :class:`Formatter` instances which know about
525the keys of the dict-like object. If you need a different method, e.g. if you
526want to prepend or append the contextual information to the message string,
Vinay Sajip67f39772013-08-17 00:39:42 +0100527you just need to subclass :class:`LoggerAdapter` and override
528:meth:`~LoggerAdapter.process` to do what you need. Here is a simple example::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000529
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100530 class CustomAdapter(logging.LoggerAdapter):
531 """
532 This example adapter expects the passed in dict-like object to have a
533 'connid' key, whose value in brackets is prepended to the log message.
534 """
535 def process(self, msg, kwargs):
536 return '[%s] %s' % (self.extra['connid'], msg), kwargs
Vinay Sajipc63619b2010-12-19 12:56:57 +0000537
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100538which you can use like this::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000539
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100540 logger = logging.getLogger(__name__)
541 adapter = CustomAdapter(logger, {'connid': some_conn_id})
Vinay Sajipc63619b2010-12-19 12:56:57 +0000542
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100543Then any events that you log to the adapter will have the value of
544``some_conn_id`` prepended to the log messages.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000545
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100546Using objects other than dicts to pass contextual information
547~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vinay Sajipc63619b2010-12-19 12:56:57 +0000548
Vinay Sajipa92fbe62013-07-24 17:52:01 +0100549You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could
550pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so
551that it looks like a dict to logging. This would be useful if you want to
552generate values dynamically (whereas the values in a dict would be constant).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000553
554
555.. _filters-contextual:
556
557Using Filters to impart contextual information
558^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
559
560You can also add contextual information to log output using a user-defined
561:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
562passed to them, including adding additional attributes which can then be output
563using a suitable format string, or if needed a custom :class:`Formatter`.
564
565For example in a web application, the request being processed (or at least,
566the interesting parts of it) can be stored in a threadlocal
567(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
568add, say, information from the request - say, the remote IP address and remote
569user's username - to the ``LogRecord``, using the attribute names 'ip' and
570'user' as in the ``LoggerAdapter`` example above. In that case, the same format
571string can be used to get similar output to that shown above. Here's an example
572script::
573
574 import logging
575 from random import choice
576
577 class ContextFilter(logging.Filter):
578 """
579 This is a filter which injects contextual information into the log.
580
581 Rather than use actual contextual information, we just use random
582 data in this demo.
583 """
584
585 USERS = ['jim', 'fred', 'sheila']
586 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
587
588 def filter(self, record):
589
590 record.ip = choice(ContextFilter.IPS)
591 record.user = choice(ContextFilter.USERS)
592 return True
593
594 if __name__ == '__main__':
595 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000596 logging.basicConfig(level=logging.DEBUG,
597 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
598 a1 = logging.getLogger('a.b.c')
599 a2 = logging.getLogger('d.e.f')
600
601 f = ContextFilter()
602 a1.addFilter(f)
603 a2.addFilter(f)
604 a1.debug('A debug message')
605 a1.info('An info message with %s', 'some parameters')
606 for x in range(10):
607 lvl = choice(levels)
608 lvlname = logging.getLevelName(lvl)
609 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
610
611which, when run, produces something like::
612
613 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
614 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
615 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
616 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
617 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
618 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
619 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
620 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
621 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
622 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
623 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
624 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
625
626
627.. _multiple-processes:
628
629Logging to a single file from multiple processes
630------------------------------------------------
631
632Although logging is thread-safe, and logging to a single file from multiple
633threads in a single process *is* supported, logging to a single file from
634*multiple processes* is *not* supported, because there is no standard way to
635serialize access to a single file across multiple processes in Python. If you
636need to log to a single file from multiple processes, one way of doing this is
Vinay Sajip67f39772013-08-17 00:39:42 +0100637to have all the processes log to a :class:`~handlers.SocketHandler`, and have a
638separate process which implements a socket server which reads from the socket
639and logs to file. (If you prefer, you can dedicate one thread in one of the
640existing processes to perform this function.)
641:ref:`This section <network-logging>` documents this approach in more detail and
642includes a working socket receiver which can be used as a starting point for you
643to adapt in your own applications.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000644
645If you are using a recent version of Python which includes the
646:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip67f39772013-08-17 00:39:42 +0100647:class:`~multiprocessing.Lock` class from this module to serialize access to the
648file from your processes. The existing :class:`FileHandler` and subclasses do
649not make use of :mod:`multiprocessing` at present, though they may do so in the
650future. Note that at present, the :mod:`multiprocessing` module does not provide
Vinay Sajipc63619b2010-12-19 12:56:57 +0000651working lock functionality on all platforms (see
652http://bugs.python.org/issue3770).
653
654.. currentmodule:: logging.handlers
655
656Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
657all logging events to one of the processes in your multi-process application.
658The following example script demonstrates how you can do this; in the example
659a separate listener process listens for events sent by other processes and logs
660them according to its own logging configuration. Although the example only
661demonstrates one way of doing it (for example, you may want to use a listener
Georg Brandl7a0afd32011-02-07 15:44:27 +0000662thread rather than a separate listener process -- the implementation would be
Vinay Sajipc63619b2010-12-19 12:56:57 +0000663analogous) it does allow for completely different logging configurations for
664the listener and the other processes in your application, and can be used as
665the basis for code meeting your own specific requirements::
666
667 # You'll need these imports in your own code
668 import logging
669 import logging.handlers
670 import multiprocessing
671
672 # Next two import lines for this demo only
673 from random import choice, random
674 import time
675
676 #
677 # Because you'll want to define the logging configurations for listener and workers, the
678 # listener and worker process functions take a configurer parameter which is a callable
679 # for configuring logging for that process. These functions are also passed the queue,
680 # which they use for communication.
681 #
682 # In practice, you can configure the listener however you want, but note that in this
683 # simple example, the listener does not apply level or filter logic to received records.
Georg Brandl7a0afd32011-02-07 15:44:27 +0000684 # In practice, you would probably want to do this logic in the worker processes, to avoid
Vinay Sajipc63619b2010-12-19 12:56:57 +0000685 # sending events which would be filtered out between processes.
686 #
687 # The size of the rotated files is made small so you can see the results easily.
688 def listener_configurer():
689 root = logging.getLogger()
Raymond Hettingerb34705f2011-06-26 15:29:06 +0200690 h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000691 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
692 h.setFormatter(f)
693 root.addHandler(h)
694
695 # This is the listener process top-level loop: wait for logging events
696 # (LogRecords)on the queue and handle them, quit when you get a None for a
697 # LogRecord.
698 def listener_process(queue, configurer):
699 configurer()
700 while True:
701 try:
702 record = queue.get()
703 if record is None: # We send this as a sentinel to tell the listener to quit.
704 break
705 logger = logging.getLogger(record.name)
706 logger.handle(record) # No level or filter logic applied - just do it!
Andrew Svetlov47395612012-11-02 22:07:26 +0200707 except Exception:
Vinay Sajipc63619b2010-12-19 12:56:57 +0000708 import sys, traceback
Vinay Sajip6b883a22012-02-27 11:02:45 +0000709 print('Whoops! Problem:', file=sys.stderr)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000710 traceback.print_exc(file=sys.stderr)
711
712 # Arrays used for random selections in this demo
713
714 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
715 logging.ERROR, logging.CRITICAL]
716
717 LOGGERS = ['a.b.c', 'd.e.f']
718
719 MESSAGES = [
720 'Random message #1',
721 'Random message #2',
722 'Random message #3',
723 ]
724
725 # The worker configuration is done at the start of the worker process run.
726 # Note that on Windows you can't rely on fork semantics, so each process
727 # will run the logging configuration code when it starts.
728 def worker_configurer(queue):
729 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
730 root = logging.getLogger()
731 root.addHandler(h)
732 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
733
734 # This is the worker process top-level loop, which just logs ten events with
735 # random intervening delays before terminating.
736 # The print messages are just so you know it's doing something!
737 def worker_process(queue, configurer):
738 configurer(queue)
739 name = multiprocessing.current_process().name
740 print('Worker started: %s' % name)
741 for i in range(10):
742 time.sleep(random())
743 logger = logging.getLogger(choice(LOGGERS))
744 level = choice(LEVELS)
745 message = choice(MESSAGES)
746 logger.log(level, message)
747 print('Worker finished: %s' % name)
748
749 # Here's where the demo gets orchestrated. Create the queue, create and start
750 # the listener, create ten workers and start them, wait for them to finish,
751 # then send a None to the queue to tell the listener to finish.
752 def main():
753 queue = multiprocessing.Queue(-1)
754 listener = multiprocessing.Process(target=listener_process,
755 args=(queue, listener_configurer))
756 listener.start()
757 workers = []
758 for i in range(10):
759 worker = multiprocessing.Process(target=worker_process,
760 args=(queue, worker_configurer))
761 workers.append(worker)
762 worker.start()
763 for w in workers:
764 w.join()
765 queue.put_nowait(None)
766 listener.join()
767
768 if __name__ == '__main__':
769 main()
770
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000771A variant of the above script keeps the logging in the main process, in a
772separate thread::
773
774 import logging
775 import logging.config
776 import logging.handlers
777 from multiprocessing import Process, Queue
778 import random
779 import threading
780 import time
781
782 def logger_thread(q):
783 while True:
784 record = q.get()
785 if record is None:
786 break
787 logger = logging.getLogger(record.name)
788 logger.handle(record)
789
790
791 def worker_process(q):
792 qh = logging.handlers.QueueHandler(q)
793 root = logging.getLogger()
794 root.setLevel(logging.DEBUG)
795 root.addHandler(qh)
796 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
797 logging.CRITICAL]
798 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
799 'spam', 'spam.ham', 'spam.ham.eggs']
800 for i in range(100):
801 lvl = random.choice(levels)
802 logger = logging.getLogger(random.choice(loggers))
803 logger.log(lvl, 'Message no. %d', i)
804
805 if __name__ == '__main__':
806 q = Queue()
807 d = {
808 'version': 1,
809 'formatters': {
810 'detailed': {
811 'class': 'logging.Formatter',
812 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
813 }
814 },
815 'handlers': {
816 'console': {
817 'class': 'logging.StreamHandler',
818 'level': 'INFO',
819 },
820 'file': {
821 'class': 'logging.FileHandler',
822 'filename': 'mplog.log',
823 'mode': 'w',
824 'formatter': 'detailed',
825 },
826 'foofile': {
827 'class': 'logging.FileHandler',
828 'filename': 'mplog-foo.log',
829 'mode': 'w',
830 'formatter': 'detailed',
831 },
832 'errors': {
833 'class': 'logging.FileHandler',
834 'filename': 'mplog-errors.log',
835 'mode': 'w',
836 'level': 'ERROR',
837 'formatter': 'detailed',
838 },
839 },
840 'loggers': {
841 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200842 'handlers': ['foofile']
Vinay Sajipe6f1e432010-12-26 18:47:51 +0000843 }
844 },
845 'root': {
846 'level': 'DEBUG',
847 'handlers': ['console', 'file', 'errors']
848 },
849 }
850 workers = []
851 for i in range(5):
852 wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
853 workers.append(wp)
854 wp.start()
855 logging.config.dictConfig(d)
856 lp = threading.Thread(target=logger_thread, args=(q,))
857 lp.start()
858 # At this point, the main process could do some useful work of its own
859 # Once it's done that, it can wait for the workers to terminate...
860 for wp in workers:
861 wp.join()
862 # And now tell the logging thread to finish up, too
863 q.put(None)
864 lp.join()
865
866This variant shows how you can e.g. apply configuration for particular loggers
867- e.g. the ``foo`` logger has a special handler which stores all events in the
868``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging
869machinery in the main process (even though the logging events are generated in
870the worker processes) to direct the messages to the appropriate destinations.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000871
872Using file rotation
873-------------------
874
875.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
876.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
877
878Sometimes you want to let a log file grow to a certain size, then open a new
879file and log to that. You may want to keep a certain number of these files, and
880when that many files have been created, rotate the files so that the number of
Georg Brandl7a0afd32011-02-07 15:44:27 +0000881files and the size of the files both remain bounded. For this usage pattern, the
Vinay Sajip67f39772013-08-17 00:39:42 +0100882logging package provides a :class:`~handlers.RotatingFileHandler`::
Vinay Sajipc63619b2010-12-19 12:56:57 +0000883
884 import glob
885 import logging
886 import logging.handlers
887
888 LOG_FILENAME = 'logging_rotatingfile_example.out'
889
890 # Set up a specific logger with our desired output level
891 my_logger = logging.getLogger('MyLogger')
892 my_logger.setLevel(logging.DEBUG)
893
894 # Add the log message handler to the logger
895 handler = logging.handlers.RotatingFileHandler(
896 LOG_FILENAME, maxBytes=20, backupCount=5)
897
898 my_logger.addHandler(handler)
899
900 # Log some messages
901 for i in range(20):
902 my_logger.debug('i = %d' % i)
903
904 # See what files are created
905 logfiles = glob.glob('%s*' % LOG_FILENAME)
906
907 for filename in logfiles:
908 print(filename)
909
910The result should be 6 separate files, each with part of the log history for the
911application::
912
913 logging_rotatingfile_example.out
914 logging_rotatingfile_example.out.1
915 logging_rotatingfile_example.out.2
916 logging_rotatingfile_example.out.3
917 logging_rotatingfile_example.out.4
918 logging_rotatingfile_example.out.5
919
920The most current file is always :file:`logging_rotatingfile_example.out`,
921and each time it reaches the size limit it is renamed with the suffix
922``.1``. Each of the existing backup files is renamed to increment the suffix
923(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
924
Ezio Melottie130a522011-10-19 10:58:56 +0300925Obviously this example sets the log length much too small as an extreme
Vinay Sajipc63619b2010-12-19 12:56:57 +0000926example. You would want to set *maxBytes* to an appropriate value.
927
Vinay Sajip6b883a22012-02-27 11:02:45 +0000928.. _format-styles:
929
930Use of alternative formatting styles
931------------------------------------
932
933When logging was added to the Python standard library, the only way of
934formatting messages with variable content was to use the %-formatting
935method. Since then, Python has gained two new formatting approaches:
Vinay Sajip39b83ac2012-02-28 08:05:23 +0000936:class:`string.Template` (added in Python 2.4) and :meth:`str.format`
937(added in Python 2.6).
Vinay Sajip6b883a22012-02-27 11:02:45 +0000938
Vinay Sajip39b83ac2012-02-28 08:05:23 +0000939Logging (as of 3.2) provides improved support for these two additional
940formatting styles. The :class:`Formatter` class been enhanced to take an
941additional, optional keyword parameter named ``style``. This defaults to
942``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond
Vinay Sajip6b883a22012-02-27 11:02:45 +0000943to the other two formatting styles. Backwards compatibility is maintained by
944default (as you would expect), but by explicitly specifying a style parameter,
945you get the ability to specify format strings which work with
946:meth:`str.format` or :class:`string.Template`. Here's an example console
947session to show the possibilities:
948
949.. code-block:: pycon
950
951 >>> import logging
952 >>> root = logging.getLogger()
953 >>> root.setLevel(logging.DEBUG)
954 >>> handler = logging.StreamHandler()
955 >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
956 ... style='{')
957 >>> handler.setFormatter(bf)
958 >>> root.addHandler(handler)
959 >>> logger = logging.getLogger('foo.bar')
960 >>> logger.debug('This is a DEBUG message')
961 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message
962 >>> logger.critical('This is a CRITICAL message')
963 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
964 >>> df = logging.Formatter('$asctime $name ${levelname} $message',
965 ... style='$')
966 >>> handler.setFormatter(df)
967 >>> logger.debug('This is a DEBUG message')
968 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
969 >>> logger.critical('This is a CRITICAL message')
970 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
971 >>>
972
973Note that the formatting of logging messages for final output to logs is
974completely independent of how an individual logging message is constructed.
975That can still use %-formatting, as shown here::
976
977 >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
978 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
979 >>>
980
981Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take
982positional parameters for the actual logging message itself, with keyword
983parameters used only for determining options for how to handle the actual
984logging call (e.g. the ``exc_info`` keyword parameter to indicate that
985traceback information should be logged, or the ``extra`` keyword parameter
986to indicate additional contextual information to be added to the log). So
987you cannot directly make logging calls using :meth:`str.format` or
988:class:`string.Template` syntax, because internally the logging package
989uses %-formatting to merge the format string and the variable arguments.
990There would no changing this while preserving backward compatibility, since
991all logging calls which are out there in existing code will be using %-format
992strings.
993
994There is, however, a way that you can use {}- and $- formatting to construct
995your individual log messages. Recall that for a message you can use an
996arbitrary object as a message format string, and that the logging package will
997call ``str()`` on that object to get the actual format string. Consider the
998following two classes::
999
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001000 class BraceMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001001 def __init__(self, fmt, *args, **kwargs):
1002 self.fmt = fmt
1003 self.args = args
1004 self.kwargs = kwargs
1005
1006 def __str__(self):
1007 return self.fmt.format(*self.args, **self.kwargs)
1008
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001009 class DollarMessage:
Vinay Sajip6b883a22012-02-27 11:02:45 +00001010 def __init__(self, fmt, **kwargs):
1011 self.fmt = fmt
1012 self.kwargs = kwargs
1013
1014 def __str__(self):
1015 from string import Template
1016 return Template(self.fmt).substitute(**self.kwargs)
1017
1018Either of these can be used in place of a format string, to allow {}- or
1019$-formatting to be used to build the actual "message" part which appears in the
1020formatted log output in place of "%(message)s" or "{message}" or "$message".
1021It's a little unwieldy to use the class names whenever you want to log
1022something, but it's quite palatable if you use an alias such as __ (double
1023underscore – not to be confused with _, the single underscore used as a
1024synonym/alias for :func:`gettext.gettext` or its brethren).
1025
1026The above classes are not included in Python, though they're easy enough to
1027copy and paste into your own code. They can be used as follows (assuming that
1028they're declared in a module called ``wherever``):
1029
1030.. code-block:: pycon
1031
1032 >>> from wherever import BraceMessage as __
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001033 >>> print(__('Message with {0} {name}', 2, name='placeholders'))
Vinay Sajip6b883a22012-02-27 11:02:45 +00001034 Message with 2 placeholders
1035 >>> class Point: pass
1036 ...
1037 >>> p = Point()
1038 >>> p.x = 0.5
1039 >>> p.y = 0.5
1040 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
1041 ... point=p))
1042 Message with coordinates: (0.50, 0.50)
1043 >>> from wherever import DollarMessage as __
1044 >>> print(__('Message with $num $what', num=2, what='placeholders'))
1045 Message with 2 placeholders
1046 >>>
1047
Vinay Sajip39b83ac2012-02-28 08:05:23 +00001048While the above examples use ``print()`` to show how the formatting works, you
1049would of course use ``logger.debug()`` or similar to actually log using this
1050approach.
1051
Vinay Sajip6b883a22012-02-27 11:02:45 +00001052One thing to note is that you pay no significant performance penalty with this
1053approach: the actual formatting happens not when you make the logging call, but
1054when (and if) the logged message is actually about to be output to a log by a
1055handler. So the only slightly unusual thing which might trip you up is that the
1056parentheses go around the format string and the arguments, not just the format
1057string. That's because the __ notation is just syntax sugar for a constructor
1058call to one of the XXXMessage classes.
1059
Vinay Sajip8028a5c2013-03-30 11:56:18 +00001060If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect
1061to the above, as in the following example::
1062
1063 import logging
1064
1065 class Message(object):
1066 def __init__(self, fmt, args):
1067 self.fmt = fmt
1068 self.args = args
1069
1070 def __str__(self):
1071 return self.fmt.format(*self.args)
1072
1073 class StyleAdapter(logging.LoggerAdapter):
1074 def __init__(self, logger, extra=None):
1075 super(StyleAdapter, self).__init__(logger, extra or {})
1076
1077 def log(self, level, msg, *args, **kwargs):
1078 if self.isEnabledFor(level):
1079 msg, kwargs = self.process(msg, kwargs)
1080 self.logger._log(level, Message(msg, args), (), **kwargs)
1081
1082 logger = StyleAdapter(logging.getLogger(__name__))
1083
1084 def main():
1085 logger.debug('Hello, {}', 'world!')
1086
1087 if __name__ == '__main__':
1088 logging.basicConfig(level=logging.DEBUG)
1089 main()
1090
1091The above script should log the message ``Hello, world!`` when run with
1092Python 3.2 or later.
1093
Vinay Sajip6b883a22012-02-27 11:02:45 +00001094
Vinay Sajip982f5342012-02-27 11:56:29 +00001095.. currentmodule:: logging
1096
Georg Brandle9983862012-02-28 08:21:40 +01001097.. _custom-logrecord:
Vinay Sajip982f5342012-02-27 11:56:29 +00001098
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001099Customizing ``LogRecord``
Vinay Sajip982f5342012-02-27 11:56:29 +00001100-------------------------
1101
1102Every logging event is represented by a :class:`LogRecord` instance.
1103When an event is logged and not filtered out by a logger's level, a
1104:class:`LogRecord` is created, populated with information about the event and
1105then passed to the handlers for that logger (and its ancestors, up to and
1106including the logger where further propagation up the hierarchy is disabled).
1107Before Python 3.2, there were only two places where this creation was done:
1108
1109* :meth:`Logger.makeRecord`, which is called in the normal process of
1110 logging an event. This invoked :class:`LogRecord` directly to create an
1111 instance.
1112* :func:`makeLogRecord`, which is called with a dictionary containing
1113 attributes to be added to the LogRecord. This is typically invoked when a
1114 suitable dictionary has been received over the network (e.g. in pickle form
1115 via a :class:`~handlers.SocketHandler`, or in JSON form via an
1116 :class:`~handlers.HTTPHandler`).
1117
1118This has usually meant that if you need to do anything special with a
1119:class:`LogRecord`, you've had to do one of the following.
1120
1121* Create your own :class:`Logger` subclass, which overrides
1122 :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass`
1123 before any loggers that you care about are instantiated.
1124* Add a :class:`Filter` to a logger or handler, which does the
1125 necessary special manipulation you need when its
1126 :meth:`~Filter.filter` method is called.
1127
1128The first approach would be a little unwieldy in the scenario where (say)
1129several different libraries wanted to do different things. Each would attempt
1130to set its own :class:`Logger` subclass, and the one which did this last would
1131win.
1132
1133The second approach works reasonably well for many cases, but does not allow
1134you to e.g. use a specialized subclass of :class:`LogRecord`. Library
1135developers can set a suitable filter on their loggers, but they would have to
1136remember to do this every time they introduced a new logger (which they would
Georg Brandle9983862012-02-28 08:21:40 +01001137do simply by adding new packages or modules and doing ::
Vinay Sajip982f5342012-02-27 11:56:29 +00001138
1139 logger = logging.getLogger(__name__)
1140
1141at module level). It's probably one too many things to think about. Developers
1142could also add the filter to a :class:`~logging.NullHandler` attached to their
1143top-level logger, but this would not be invoked if an application developer
1144attached a handler to a lower-level library logger – so output from that
1145handler would not reflect the intentions of the library developer.
1146
1147In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a
1148factory, which you can specify. The factory is just a callable you can set with
1149:func:`~logging.setLogRecordFactory`, and interrogate with
1150:func:`~logging.getLogRecordFactory`. The factory is invoked with the same
1151signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord`
1152is the default setting for the factory.
1153
1154This approach allows a custom factory to control all aspects of LogRecord
1155creation. For example, you could return a subclass, or just add some additional
1156attributes to the record once created, using a pattern similar to this::
1157
1158 old_factory = logging.getLogRecordFactory()
1159
1160 def record_factory(*args, **kwargs):
1161 record = old_factory(*args, **kwargs)
1162 record.custom_attribute = 0xdecafbad
1163 return record
1164
1165 logging.setLogRecordFactory(record_factory)
1166
1167This pattern allows different libraries to chain factories together, and as
1168long as they don't overwrite each other's attributes or unintentionally
1169overwrite the attributes provided as standard, there should be no surprises.
1170However, it should be borne in mind that each link in the chain adds run-time
1171overhead to all logging operations, and the technique should only be used when
1172the use of a :class:`Filter` does not provide the desired result.
1173
1174
Vinay Sajipc63619b2010-12-19 12:56:57 +00001175.. _zeromq-handlers:
1176
Vinay Sajip7d101292010-12-26 21:22:33 +00001177Subclassing QueueHandler - a ZeroMQ example
1178-------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001179
1180You can use a :class:`QueueHandler` subclass to send messages to other kinds
1181of queues, for example a ZeroMQ 'publish' socket. In the example below,the
1182socket is created separately and passed to the handler (as its 'queue')::
1183
1184 import zmq # using pyzmq, the Python binding for ZeroMQ
1185 import json # for serializing records portably
1186
1187 ctx = zmq.Context()
1188 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
1189 sock.bind('tcp://*:5556') # or wherever
1190
1191 class ZeroMQSocketHandler(QueueHandler):
1192 def enqueue(self, record):
1193 data = json.dumps(record.__dict__)
1194 self.queue.send(data)
1195
1196 handler = ZeroMQSocketHandler(sock)
1197
1198
1199Of course there are other ways of organizing this, for example passing in the
1200data needed by the handler to create the socket::
1201
1202 class ZeroMQSocketHandler(QueueHandler):
1203 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
1204 self.ctx = ctx or zmq.Context()
1205 socket = zmq.Socket(self.ctx, socktype)
1206 socket.bind(uri)
1207 QueueHandler.__init__(self, socket)
1208
1209 def enqueue(self, record):
1210 data = json.dumps(record.__dict__)
1211 self.queue.send(data)
1212
1213 def close(self):
1214 self.queue.close()
1215
1216
Vinay Sajip7d101292010-12-26 21:22:33 +00001217Subclassing QueueListener - a ZeroMQ example
1218--------------------------------------------
Vinay Sajipc63619b2010-12-19 12:56:57 +00001219
1220You can also subclass :class:`QueueListener` to get messages from other kinds
1221of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
1222
1223 class ZeroMQSocketListener(QueueListener):
1224 def __init__(self, uri, *handlers, **kwargs):
1225 self.ctx = kwargs.get('ctx') or zmq.Context()
1226 socket = zmq.Socket(self.ctx, zmq.SUB)
1227 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
1228 socket.connect(uri)
1229
1230 def dequeue(self):
1231 msg = self.queue.recv()
1232 return logging.makeLogRecord(json.loads(msg))
1233
1234
Vinay Sajip7d101292010-12-26 21:22:33 +00001235.. seealso::
Vinay Sajipc63619b2010-12-19 12:56:57 +00001236
Vinay Sajip7d101292010-12-26 21:22:33 +00001237 Module :mod:`logging`
1238 API reference for the logging module.
1239
1240 Module :mod:`logging.config`
1241 Configuration API for the logging module.
1242
1243 Module :mod:`logging.handlers`
1244 Useful handlers included with the logging module.
1245
1246 :ref:`A basic logging tutorial <logging-basic-tutorial>`
1247
1248 :ref:`A more advanced logging tutorial <logging-advanced-tutorial>`
Vinay Sajip631a7e22011-11-23 14:27:54 +00001249
1250
1251An example dictionary-based configuration
1252-----------------------------------------
1253
1254Below is an example of a logging configuration dictionary - it's taken from
1255the `documentation on the Django project <https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging>`_.
Vinay Sajip67f39772013-08-17 00:39:42 +01001256This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::
Vinay Sajip631a7e22011-11-23 14:27:54 +00001257
1258 LOGGING = {
1259 'version': 1,
1260 'disable_existing_loggers': True,
1261 'formatters': {
1262 'verbose': {
1263 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
1264 },
1265 'simple': {
1266 'format': '%(levelname)s %(message)s'
1267 },
1268 },
1269 'filters': {
1270 'special': {
1271 '()': 'project.logging.SpecialFilter',
1272 'foo': 'bar',
1273 }
1274 },
1275 'handlers': {
1276 'null': {
1277 'level':'DEBUG',
1278 'class':'django.utils.log.NullHandler',
1279 },
1280 'console':{
1281 'level':'DEBUG',
1282 'class':'logging.StreamHandler',
1283 'formatter': 'simple'
1284 },
1285 'mail_admins': {
1286 'level': 'ERROR',
1287 'class': 'django.utils.log.AdminEmailHandler',
1288 'filters': ['special']
1289 }
1290 },
1291 'loggers': {
1292 'django': {
1293 'handlers':['null'],
1294 'propagate': True,
1295 'level':'INFO',
1296 },
1297 'django.request': {
1298 'handlers': ['mail_admins'],
1299 'level': 'ERROR',
1300 'propagate': False,
1301 },
1302 'myproject.custom': {
1303 'handlers': ['console', 'mail_admins'],
1304 'level': 'INFO',
1305 'filters': ['special']
1306 }
1307 }
1308 }
1309
1310For more information about this configuration, you can see the `relevant
Vinay Sajip49089102014-03-25 11:21:41 +00001311section <https://docs.djangoproject.com/en/1.6/topics/logging/#configuring-logging>`_
Vinay Sajip631a7e22011-11-23 14:27:54 +00001312of the Django documentation.
Vinay Sajip23b94d02012-01-04 12:02:26 +00001313
1314.. _cookbook-rotator-namer:
1315
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001316Using a rotator and namer to customize log rotation processing
Vinay Sajip23b94d02012-01-04 12:02:26 +00001317--------------------------------------------------------------
1318
1319An example of how you can define a namer and rotator is given in the following
1320snippet, which shows zlib-based compression of the log file::
1321
1322 def namer(name):
1323 return name + ".gz"
1324
1325 def rotator(source, dest):
1326 with open(source, "rb") as sf:
1327 data = sf.read()
1328 compressed = zlib.compress(data, 9)
1329 with open(dest, "wb") as df:
1330 df.write(compressed)
1331 os.remove(source)
1332
1333 rh = logging.handlers.RotatingFileHandler(...)
1334 rh.rotator = rotator
1335 rh.namer = namer
1336
Ezio Melotti226231c2012-01-18 05:40:00 +02001337These are not "true" .gz files, as they are bare compressed data, with no
1338"container" such as youd find in an actual gzip file. This snippet is just
Vinay Sajip23b94d02012-01-04 12:02:26 +00001339for illustration purposes.
1340
Vinay Sajip0292fa92012-04-08 01:49:12 +01001341A more elaborate multiprocessing example
1342----------------------------------------
1343
1344The following working example shows how logging can be used with multiprocessing
1345using configuration files. The configurations are fairly simple, but serve to
1346illustrate how more complex ones could be implemented in a real multiprocessing
1347scenario.
1348
1349In the example, the main process spawns a listener process and some worker
1350processes. Each of the main process, the listener and the workers have three
1351separate configurations (the workers all share the same configuration). We can
1352see logging in the main process, how the workers log to a QueueHandler and how
1353the listener implements a QueueListener and a more complex logging
1354configuration, and arranges to dispatch events received via the queue to the
1355handlers specified in the configuration. Note that these configurations are
1356purely illustrative, but you should be able to adapt this example to your own
1357scenario.
1358
1359Here's the script - the docstrings and the comments hopefully explain how it
1360works::
1361
1362 import logging
1363 import logging.config
1364 import logging.handlers
1365 from multiprocessing import Process, Queue, Event, current_process
1366 import os
1367 import random
1368 import time
1369
Ezio Melottiaf8838f2013-03-11 09:30:21 +02001370 class MyHandler:
Vinay Sajip0292fa92012-04-08 01:49:12 +01001371 """
1372 A simple handler for logging events. It runs in the listener process and
1373 dispatches events to loggers based on the name in the received record,
1374 which then get dispatched, by the logging system, to the handlers
Vinay Sajip838e6382012-04-09 19:46:24 +01001375 configured for those loggers.
Vinay Sajip0292fa92012-04-08 01:49:12 +01001376 """
1377 def handle(self, record):
1378 logger = logging.getLogger(record.name)
1379 # The process name is transformed just to show that it's the listener
1380 # doing the logging to files and console
1381 record.processName = '%s (for %s)' % (current_process().name, record.processName)
1382 logger.handle(record)
1383
1384 def listener_process(q, stop_event, config):
1385 """
1386 This could be done in the main process, but is just done in a separate
1387 process for illustrative purposes.
1388
1389 This initialises logging according to the specified configuration,
1390 starts the listener and waits for the main process to signal completion
1391 via the event. The listener is then stopped, and the process exits.
1392 """
1393 logging.config.dictConfig(config)
1394 listener = logging.handlers.QueueListener(q, MyHandler())
1395 listener.start()
1396 if os.name == 'posix':
1397 # On POSIX, the setup logger will have been configured in the
1398 # parent process, but should have been disabled following the
1399 # dictConfig call.
1400 # On Windows, since fork isn't used, the setup logger won't
1401 # exist in the child, so it would be created and the message
1402 # would appear - hence the "if posix" clause.
1403 logger = logging.getLogger('setup')
1404 logger.critical('Should not appear, because of disabled logger ...')
1405 stop_event.wait()
1406 listener.stop()
1407
1408 def worker_process(config):
1409 """
1410 A number of these are spawned for the purpose of illustration. In
1411 practice, they could be a heterogenous bunch of processes rather than
1412 ones which are identical to each other.
1413
1414 This initialises logging according to the specified configuration,
1415 and logs a hundred messages with random levels to randomly selected
1416 loggers.
1417
1418 A small sleep is added to allow other processes a chance to run. This
1419 is not strictly needed, but it mixes the output from the different
1420 processes a bit more than if it's left out.
1421 """
1422 logging.config.dictConfig(config)
1423 levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
1424 logging.CRITICAL]
1425 loggers = ['foo', 'foo.bar', 'foo.bar.baz',
1426 'spam', 'spam.ham', 'spam.ham.eggs']
1427 if os.name == 'posix':
1428 # On POSIX, the setup logger will have been configured in the
1429 # parent process, but should have been disabled following the
1430 # dictConfig call.
1431 # On Windows, since fork isn't used, the setup logger won't
1432 # exist in the child, so it would be created and the message
1433 # would appear - hence the "if posix" clause.
1434 logger = logging.getLogger('setup')
1435 logger.critical('Should not appear, because of disabled logger ...')
1436 for i in range(100):
1437 lvl = random.choice(levels)
1438 logger = logging.getLogger(random.choice(loggers))
1439 logger.log(lvl, 'Message no. %d', i)
1440 time.sleep(0.01)
1441
1442 def main():
1443 q = Queue()
1444 # The main process gets a simple configuration which prints to the console.
1445 config_initial = {
1446 'version': 1,
1447 'formatters': {
1448 'detailed': {
1449 'class': 'logging.Formatter',
1450 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1451 }
1452 },
1453 'handlers': {
1454 'console': {
1455 'class': 'logging.StreamHandler',
1456 'level': 'INFO',
1457 },
1458 },
1459 'root': {
1460 'level': 'DEBUG',
1461 'handlers': ['console']
1462 },
1463 }
1464 # The worker process configuration is just a QueueHandler attached to the
1465 # root logger, which allows all messages to be sent to the queue.
1466 # We disable existing loggers to disable the "setup" logger used in the
1467 # parent process. This is needed on POSIX because the logger will
1468 # be there in the child following a fork().
1469 config_worker = {
1470 'version': 1,
1471 'disable_existing_loggers': True,
1472 'handlers': {
1473 'queue': {
1474 'class': 'logging.handlers.QueueHandler',
1475 'queue': q,
1476 },
1477 },
1478 'root': {
1479 'level': 'DEBUG',
1480 'handlers': ['queue']
1481 },
1482 }
1483 # The listener process configuration shows that the full flexibility of
1484 # logging configuration is available to dispatch events to handlers however
1485 # you want.
1486 # We disable existing loggers to disable the "setup" logger used in the
1487 # parent process. This is needed on POSIX because the logger will
1488 # be there in the child following a fork().
1489 config_listener = {
1490 'version': 1,
1491 'disable_existing_loggers': True,
1492 'formatters': {
1493 'detailed': {
1494 'class': 'logging.Formatter',
1495 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1496 },
1497 'simple': {
1498 'class': 'logging.Formatter',
1499 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
1500 }
1501 },
1502 'handlers': {
1503 'console': {
1504 'class': 'logging.StreamHandler',
1505 'level': 'INFO',
1506 'formatter': 'simple',
1507 },
1508 'file': {
1509 'class': 'logging.FileHandler',
1510 'filename': 'mplog.log',
1511 'mode': 'w',
1512 'formatter': 'detailed',
1513 },
1514 'foofile': {
1515 'class': 'logging.FileHandler',
1516 'filename': 'mplog-foo.log',
1517 'mode': 'w',
1518 'formatter': 'detailed',
1519 },
1520 'errors': {
1521 'class': 'logging.FileHandler',
1522 'filename': 'mplog-errors.log',
1523 'mode': 'w',
1524 'level': 'ERROR',
1525 'formatter': 'detailed',
1526 },
1527 },
1528 'loggers': {
1529 'foo': {
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001530 'handlers': ['foofile']
Vinay Sajip0292fa92012-04-08 01:49:12 +01001531 }
1532 },
1533 'root': {
1534 'level': 'DEBUG',
1535 'handlers': ['console', 'file', 'errors']
1536 },
1537 }
1538 # Log some initial events, just to show that logging in the parent works
1539 # normally.
1540 logging.config.dictConfig(config_initial)
1541 logger = logging.getLogger('setup')
1542 logger.info('About to create workers ...')
1543 workers = []
1544 for i in range(5):
1545 wp = Process(target=worker_process, name='worker %d' % (i + 1),
1546 args=(config_worker,))
1547 workers.append(wp)
1548 wp.start()
1549 logger.info('Started worker: %s', wp.name)
1550 logger.info('About to create listener ...')
1551 stop_event = Event()
1552 lp = Process(target=listener_process, name='listener',
1553 args=(q, stop_event, config_listener))
1554 lp.start()
1555 logger.info('Started listener')
1556 # We now hang around for the workers to finish their work.
1557 for wp in workers:
1558 wp.join()
1559 # Workers all done, listening can now stop.
1560 # Logging in the parent still works normally.
1561 logger.info('Telling listener to stop ...')
1562 stop_event.set()
1563 lp.join()
1564 logger.info('All done.')
1565
1566 if __name__ == '__main__':
1567 main()
1568
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001569
1570Inserting a BOM into messages sent to a SysLogHandler
1571-----------------------------------------------------
1572
1573`RFC 5424 <http://tools.ietf.org/html/rfc5424>`_ requires that a
1574Unicode message be sent to a syslog daemon as a set of bytes which have the
1575following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
1576Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant
1577section of the specification <http://tools.ietf.org/html/rfc5424#section-6>`_.)
1578
Vinay Sajip62930e12012-04-17 00:40:48 +01001579In Python 3.1, code was added to
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001580:class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
1581unfortunately, it was implemented incorrectly, with the BOM appearing at the
1582beginning of the message and hence not allowing any pure-ASCII component to
1583appear before it.
1584
1585As this behaviour is broken, the incorrect BOM insertion code is being removed
Vinay Sajip62930e12012-04-17 00:40:48 +01001586from Python 3.2.4 and later. However, it is not being replaced, and if you
Vinay Sajipa58d6682012-07-27 10:54:10 +01001587want to produce RFC 5424-compliant messages which include a BOM, an optional
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001588pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
1589UTF-8, then you need to do the following:
1590
1591#. Attach a :class:`~logging.Formatter` instance to your
1592 :class:`~logging.handlers.SysLogHandler` instance, with a format string
1593 such as::
1594
Vinay Sajip59b9a792012-04-16 15:46:18 +01001595 'ASCII section\ufeffUnicode section'
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001596
Georg Brandld50fe722013-03-23 16:00:41 +01001597 The Unicode code point U+FEFF, when encoded using UTF-8, will be
Vinay Sajip59b9a792012-04-16 15:46:18 +01001598 encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001599
1600#. Replace the ASCII section with whatever placeholders you like, but make sure
1601 that the data that appears in there after substitution is always ASCII (that
1602 way, it will remain unchanged after UTF-8 encoding).
1603
1604#. Replace the Unicode section with whatever placeholders you like; if the data
Vinay Sajipa58d6682012-07-27 10:54:10 +01001605 which appears there after substitution contains characters outside the ASCII
1606 range, that's fine -- it will be encoded using UTF-8.
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001607
Vinay Sajip59b9a792012-04-16 15:46:18 +01001608The formatted message *will* be encoded using UTF-8 encoding by
1609``SysLogHandler``. If you follow the above rules, you should be able to produce
Vinay Sajipb00e8f12012-04-16 15:28:50 +01001610RFC 5424-compliant messages. If you don't, logging may not complain, but your
1611messages will not be RFC 5424-compliant, and your syslog daemon may complain.
1612
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001613
1614Implementing structured logging
1615-------------------------------
1616
1617Although most logging messages are intended for reading by humans, and thus not
1618readily machine-parseable, there might be cirumstances where you want to output
1619messages in a structured format which *is* capable of being parsed by a program
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001620(without needing complex regular expressions to parse the log message). This is
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001621straightforward to achieve using the logging package. There are a number of
1622ways in which this could be achieved, but the following is a simple approach
1623which uses JSON to serialise the event in a machine-parseable manner::
1624
1625 import json
1626 import logging
1627
1628 class StructuredMessage(object):
1629 def __init__(self, message, **kwargs):
1630 self.message = message
1631 self.kwargs = kwargs
1632
1633 def __str__(self):
1634 return '%s >>> %s' % (self.message, json.dumps(self.kwargs))
1635
1636 _ = StructuredMessage # optional, to improve readability
1637
1638 logging.basicConfig(level=logging.INFO, format='%(message)s')
1639 logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
1640
1641If the above script is run, it prints::
1642
1643 message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}
1644
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001645Note that the order of items might be different according to the version of
1646Python used.
1647
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001648If you need more specialised processing, you can use a custom JSON encoder,
1649as in the following complete example::
1650
1651 from __future__ import unicode_literals
1652
1653 import json
1654 import logging
1655
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001656 # This next bit is to ensure the script runs unchanged on 2.x and 3.x
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001657 try:
1658 unicode
1659 except NameError:
1660 unicode = str
1661
1662 class Encoder(json.JSONEncoder):
1663 def default(self, o):
1664 if isinstance(o, set):
1665 return tuple(o)
1666 elif isinstance(o, unicode):
1667 return o.encode('unicode_escape').decode('ascii')
1668 return super(Encoder, self).default(o)
1669
1670 class StructuredMessage(object):
1671 def __init__(self, message, **kwargs):
1672 self.message = message
1673 self.kwargs = kwargs
1674
1675 def __str__(self):
1676 s = Encoder().encode(self.kwargs)
1677 return '%s >>> %s' % (self.message, s)
1678
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001679 _ = StructuredMessage # optional, to improve readability
Vinay Sajip4b88d6c2013-01-22 15:57:39 +00001680
1681 def main():
1682 logging.basicConfig(level=logging.INFO, format='%(message)s')
1683 logging.info(_('message 1', set_value=set([1, 2, 3]), snowman='\u2603'))
1684
1685 if __name__ == '__main__':
1686 main()
1687
1688When the above script is run, it prints::
1689
1690 message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}
1691
Vinay Sajip3d9e9722013-01-23 09:31:19 +00001692Note that the order of items might be different according to the version of
1693Python used.
1694
Vinay Sajip554f22f2014-02-03 11:51:45 +00001695
1696.. _custom-handlers:
1697
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001698.. currentmodule:: logging.config
1699
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001700Customizing handlers with :func:`dictConfig`
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001701--------------------------------------------
1702
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001703There are times when you want to customize logging handlers in particular ways,
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001704and if you use :func:`dictConfig` you may be able to do this without
1705subclassing. As an example, consider that you may want to set the ownership of a
1706log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001707handlers in the stdlib don't offer built-in support. You can customize handler
Vinay Sajip2c1adcb2013-11-05 10:02:21 +00001708creation using a plain function such as::
1709
1710 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1711 if owner:
1712 if not os.path.exists(filename):
1713 open(filename, 'a').close()
1714 shutil.chown(filename, *owner)
1715 return logging.FileHandler(filename, mode, encoding)
1716
1717You can then specify, in a logging configuration passed to :func:`dictConfig`,
1718that a logging handler be created by calling this function::
1719
1720 LOGGING = {
1721 'version': 1,
1722 'disable_existing_loggers': False,
1723 'formatters': {
1724 'default': {
1725 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1726 },
1727 },
1728 'handlers': {
1729 'file':{
1730 # The values below are popped from this dictionary and
1731 # used to create the handler, set the handler's level and
1732 # its formatter.
1733 '()': owned_file_handler,
1734 'level':'DEBUG',
1735 'formatter': 'default',
1736 # The values below are passed to the handler creator callable
1737 # as keyword arguments.
1738 'owner': ['pulse', 'pulse'],
1739 'filename': 'chowntest.log',
1740 'mode': 'w',
1741 'encoding': 'utf-8',
1742 },
1743 },
1744 'root': {
1745 'handlers': ['file'],
1746 'level': 'DEBUG',
1747 },
1748 }
1749
1750In this example I am setting the ownership using the ``pulse`` user and group,
1751just for the purposes of illustration. Putting it together into a working
1752script, ``chowntest.py``::
1753
1754 import logging, logging.config, os, shutil
1755
1756 def owned_file_handler(filename, mode='a', encoding=None, owner=None):
1757 if owner:
1758 if not os.path.exists(filename):
1759 open(filename, 'a').close()
1760 shutil.chown(filename, *owner)
1761 return logging.FileHandler(filename, mode, encoding)
1762
1763 LOGGING = {
1764 'version': 1,
1765 'disable_existing_loggers': False,
1766 'formatters': {
1767 'default': {
1768 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
1769 },
1770 },
1771 'handlers': {
1772 'file':{
1773 # The values below are popped from this dictionary and
1774 # used to create the handler, set the handler's level and
1775 # its formatter.
1776 '()': owned_file_handler,
1777 'level':'DEBUG',
1778 'formatter': 'default',
1779 # The values below are passed to the handler creator callable
1780 # as keyword arguments.
1781 'owner': ['pulse', 'pulse'],
1782 'filename': 'chowntest.log',
1783 'mode': 'w',
1784 'encoding': 'utf-8',
1785 },
1786 },
1787 'root': {
1788 'handlers': ['file'],
1789 'level': 'DEBUG',
1790 },
1791 }
1792
1793 logging.config.dictConfig(LOGGING)
1794 logger = logging.getLogger('mylogger')
1795 logger.debug('A debug message')
1796
1797To run this, you will probably need to run as ``root``::
1798
1799 $ sudo python3.3 chowntest.py
1800 $ cat chowntest.log
1801 2013-11-05 09:34:51,128 DEBUG mylogger A debug message
1802 $ ls -l chowntest.log
1803 -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
1804
1805Note that this example uses Python 3.3 because that's where :func:`shutil.chown`
1806makes an appearance. This approach should work with any Python version that
1807supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3
1808versions, you would need to implement the actual ownership change using e.g.
1809:func:`os.chown`.
1810
1811In practice, the handler-creating function may be in a utility module somewhere
1812in your project. Instead of the line in the configuration::
1813
1814 '()': owned_file_handler,
1815
1816you could use e.g.::
1817
1818 '()': 'ext://project.util.owned_file_handler',
1819
1820where ``project.util`` can be replaced with the actual name of the package
1821where the function resides. In the above working script, using
1822``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable
1823is resolved by :func:`dictConfig` from the ``ext://`` specification.
1824
1825This example hopefully also points the way to how you could implement other
1826types of file change - e.g. setting specific POSIX permission bits - in the
1827same way, using :func:`os.chmod`.
1828
1829Of course, the approach could also be extended to types of handler other than a
1830:class:`~logging.FileHandler` - for example, one of the rotating file handlers,
1831or a different type of handler altogether.
1832
Vinay Sajipcbefe3b2014-01-15 15:09:05 +00001833
1834.. currentmodule:: logging
1835
1836.. _formatting-styles:
1837
1838Using particular formatting styles throughout your application
1839--------------------------------------------------------------
1840
1841In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword
1842parameter which, while defaulting to ``%`` for backward compatibility, allowed
1843the specification of ``{`` or ``$`` to support the formatting approaches
1844supported by :meth:`str.format` and :class:`string.Template`. Note that this
1845governs the formatting of logging messages for final output to logs, and is
1846completely orthogonal to how an individual logging message is constructed.
1847
1848Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take
1849positional parameters for the actual logging message itself, with keyword
1850parameters used only for determining options for how to handle the logging call
1851(e.g. the ``exc_info`` keyword parameter to indicate that traceback information
1852should be logged, or the ``extra`` keyword parameter to indicate additional
1853contextual information to be added to the log). So you cannot directly make
1854logging calls using :meth:`str.format` or :class:`string.Template` syntax,
1855because internally the logging package uses %-formatting to merge the format
1856string and the variable arguments. There would no changing this while preserving
1857backward compatibility, since all logging calls which are out there in existing
1858code will be using %-format strings.
1859
1860There have been suggestions to associate format styles with specific loggers,
1861but that approach also runs into backward compatibility problems because any
1862existing code could be using a given logger name and using %-formatting.
1863
1864For logging to work interoperably between any third-party libraries and your
1865code, decisions about formatting need to be made at the level of the
1866individual logging call. This opens up a couple of ways in which alternative
1867formatting styles can be accommodated.
1868
1869
1870Using LogRecord factories
1871^^^^^^^^^^^^^^^^^^^^^^^^^
1872
1873In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned
1874above, the logging package gained the ability to allow users to set their own
1875:class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function.
1876You can use this to set your own subclass of :class:`LogRecord`, which does the
1877Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base
1878class implementation of this method is where the ``msg % args`` formatting
1879happens, and where you can substitute your alternate formatting; however, you
1880should be careful to support all formatting styles and allow %-formatting as
1881the default, to ensure interoperability with other code. Care should also be
1882taken to call ``str(self.msg)``, just as the base implementation does.
1883
1884Refer to the reference documentation on :func:`setLogRecordFactory` and
1885:class:`LogRecord` for more information.
1886
1887
1888Using custom message objects
1889^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1890
1891There is another, perhaps simpler way that you can use {}- and $- formatting to
1892construct your individual log messages. You may recall (from
1893:ref:`arbitrary-object-messages`) that when logging you can use an arbitrary
1894object as a message format string, and that the logging package will call
1895:func:`str` on that object to get the actual format string. Consider the
1896following two classes::
1897
1898 class BraceMessage(object):
1899 def __init__(self, fmt, *args, **kwargs):
1900 self.fmt = fmt
1901 self.args = args
1902 self.kwargs = kwargs
1903
1904 def __str__(self):
1905 return self.fmt.format(*self.args, **self.kwargs)
1906
1907 class DollarMessage(object):
1908 def __init__(self, fmt, **kwargs):
1909 self.fmt = fmt
1910 self.kwargs = kwargs
1911
1912 def __str__(self):
1913 from string import Template
1914 return Template(self.fmt).substitute(**self.kwargs)
1915
1916Either of these can be used in place of a format string, to allow {}- or
1917$-formatting to be used to build the actual "message" part which appears in the
1918formatted log output in place of “%(message)s or “{message}” or $message”.
1919If you find it a little unwieldy to use the class names whenever you want to log
1920something, you can make it more palatable if you use an alias such as ``M`` or
1921``_`` for the message (or perhaps ``__``, if you are using ``_`` for
1922localization).
1923
Vinay Sajipeb14dec2014-01-17 18:36:02 +00001924Examples of this approach are given below. Firstly, formatting with
1925:meth:`str.format`::
1926
1927 >>> __ = BraceMessage
1928 >>> print(__('Message with {0} {1}', 2, 'placeholders'))
1929 Message with 2 placeholders
1930 >>> class Point: pass
1931 ...
1932 >>> p = Point()
1933 >>> p.x = 0.5
1934 >>> p.y = 0.5
1935 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
1936 Message with coordinates: (0.50, 0.50)
1937
1938Secondly, formatting with :class:`string.Template`::
1939
1940 >>> __ = DollarMessage
1941 >>> print(__('Message with $num $what', num=2, what='placeholders'))
1942 Message with 2 placeholders
1943 >>>
1944
1945One thing to note is that you pay no significant performance penalty with this
1946approach: the actual formatting happens not when you make the logging call, but
1947when (and if) the logged message is actually about to be output to a log by a
1948handler. So the only slightly unusual thing which might trip you up is that the
1949parentheses go around the format string and the arguments, not just the format
1950string. Thats because the __ notation is just syntax sugar for a constructor
1951call to one of the ``XXXMessage`` classes shown above.
Vinay Sajip554f22f2014-02-03 11:51:45 +00001952
1953
1954.. _filters-dictconfig:
1955
1956.. currentmodule:: logging.config
1957
1958Configuring filters with :func:`dictConfig`
1959-------------------------------------------
1960
1961You *can* configure filters using :func:`~logging.config.dictConfig`, though it
1962might not be obvious at first glance how to do it (hence this recipe). Since
1963:class:`~logging.Filter` is the only filter class included in the standard
1964library, and it is unlikely to cater to many requirements (it's only there as a
1965base class), you will typically need to define your own :class:`~logging.Filter`
1966subclass with an overridden :meth:`~logging.Filter.filter` method. To do this,
1967specify the ``()`` key in the configuration dictionary for the filter,
1968specifying a callable which will be used to create the filter (a class is the
1969most obvious, but you can provide any callable which returns a
1970:class:`~logging.Filter` instance). Here is a complete example::
1971
1972 import logging
1973 import logging.config
1974 import sys
1975
1976 class MyFilter(logging.Filter):
1977 def __init__(self, param=None):
1978 self.param = param
1979
1980 def filter(self, record):
1981 if self.param is None:
1982 allow = True
1983 else:
1984 allow = self.param not in record.msg
1985 if allow:
1986 record.msg = 'changed: ' + record.msg
1987 return allow
1988
1989 LOGGING = {
1990 'version': 1,
1991 'filters': {
1992 'myfilter': {
1993 '()': MyFilter,
1994 'param': 'noshow',
1995 }
1996 },
1997 'handlers': {
1998 'console': {
1999 'class': 'logging.StreamHandler',
2000 'filters': ['myfilter']
2001 }
2002 },
2003 'root': {
2004 'level': 'DEBUG',
2005 'handlers': ['console']
2006 },
2007 }
2008
2009 if __name__ == '__main__':
2010 logging.config.dictConfig(LOGGING)
2011 logging.debug('hello')
2012 logging.debug('hello - noshow')
2013
2014This example shows how you can pass configuration data to the callable which
2015constructs the instance, in the form of keyword parameters. When run, the above
2016script will print::
2017
2018 changed: hello
2019
2020which shows that the filter is working as configured.
2021
2022A couple of extra points to note:
2023
2024* If you can't refer to the callable directly in the configuration (e.g. if it
2025 lives in a different module, and you can't import it directly where the
2026 configuration dictionary is), you can use the form ``ext://...`` as described
2027 in :ref:`logging-config-dict-externalobj`. For example, you could have used
2028 the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above
2029 example.
2030
2031* As well as for filters, this technique can also be used to configure custom
2032 handlers and formatters. See :ref:`logging-config-dict-userdef` for more
2033 information on how logging supports using user-defined objects in its
2034 configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
2035