blob: ce574d058e35b2a4590905dc8d2af1b87e39ca8e [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
17Logging is performed by calling methods on instances of the :class:`Logger`
18class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +000019conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +000020separators. For example, a logger named "scan" is the parent of loggers
21"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
22and indicate the area of an application in which a logged message originates.
23
24Logged messages also have levels of importance associated with them. The default
25levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
26:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
27importance of a logged message by calling an appropriate method of
28:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
29:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
30constrained to use these levels: you can specify your own and use a more general
31:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
32
Christian Heimes8b0facf2007-12-04 19:30:01 +000033
34Logging tutorial
35----------------
36
37The key benefit of having the logging API provided by a standard library module
38is that all Python modules can participate in logging, so your application log
39can include messages from third-party modules.
40
41It is, of course, possible to log messages with different verbosity levels or to
42different destinations. Support for writing log messages to files, HTTP
43GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
44mechnisms are all supported by the standard module. You can also create your
45own log destination class if you have special requirements not met by any of the
46built-in classes.
47
48Simple examples
49^^^^^^^^^^^^^^^
50
51.. sectionauthor:: Doug Hellmann
52.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
53
54Most applications are probably going to want to log to a file, so let's start
55with that case. Using the :func:`basicConfig` function, we can set up the
56default handler so that debug messages are written to a file::
57
58 import logging
59 LOG_FILENAME = '/tmp/logging_example.out'
60 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
61
62 logging.debug('This message should go to the log file')
63
64And now if we open the file and look at what we have, we should find the log
65message::
66
67 DEBUG:root:This message should go to the log file
68
69If you run the script repeatedly, the additional log messages are appended to
70the file. To create a new file each time, you can pass a filemode argument to
71:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
72yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
73
74 import glob
75 import logging
76 import logging.handlers
77
78 LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
79
80 # Set up a specific logger with our desired output level
81 my_logger = logging.getLogger('MyLogger')
82 my_logger.setLevel(logging.DEBUG)
83
84 # Add the log message handler to the logger
85 handler = logging.handlers.RotatingFileHandler(
86 LOG_FILENAME, maxBytes=20, backupCount=5)
87
88 my_logger.addHandler(handler)
89
90 # Log some messages
91 for i in range(20):
92 my_logger.debug('i = %d' % i)
93
94 # See what files are created
95 logfiles = glob.glob('%s*' % LOG_FILENAME)
96
97 for filename in logfiles:
98 print filename
99
100The result should be 6 separate files, each with part of the log history for the
101application::
102
103 /tmp/logging_rotatingfile_example.out
104 /tmp/logging_rotatingfile_example.out.1
105 /tmp/logging_rotatingfile_example.out.2
106 /tmp/logging_rotatingfile_example.out.3
107 /tmp/logging_rotatingfile_example.out.4
108 /tmp/logging_rotatingfile_example.out.5
109
110The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
111and each time it reaches the size limit it is renamed with the suffix
112``.1``. Each of the existing backup files is renamed to increment the suffix
113(``.1`` becomes ``.2``, etc.) and the ``.5`` file is erased.
114
115Obviously this example sets the log length much much too small as an extreme
116example. You would want to set *maxBytes* to an appropriate value.
117
118Another useful feature of the logging API is the ability to produce different
119messages at different log levels. This allows you to instrument your code with
120debug messages, for example, but turning the log level down so that those debug
121messages are not written for your production system. The default levels are
122``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``UNSET``.
123
124The logger, handler, and log message call each specify a level. The log message
125is only emitted if the handler and logger are configured to emit messages of
126that level or lower. For example, if a message is ``CRITICAL``, and the logger
127is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
128the logger is set to produce only ``ERROR``\s, the message is not emitted::
129
130 import logging
131 import sys
132
133 LEVELS = {'debug': logging.DEBUG,
134 'info': logging.INFO,
135 'warning': logging.WARNING,
136 'error': logging.ERROR,
137 'critical': logging.CRITICAL}
138
139 if len(sys.argv) > 1:
140 level_name = sys.argv[1]
141 level = LEVELS.get(level_name, logging.NOTSET)
142 logging.basicConfig(level=level)
143
144 logging.debug('This is a debug message')
145 logging.info('This is an info message')
146 logging.warning('This is a warning message')
147 logging.error('This is an error message')
148 logging.critical('This is a critical error message')
149
150Run the script with an argument like 'debug' or 'warning' to see which messages
151show up at different levels::
152
153 $ python logging_level_example.py debug
154 DEBUG:root:This is a debug message
155 INFO:root:This is an info message
156 WARNING:root:This is a warning message
157 ERROR:root:This is an error message
158 CRITICAL:root:This is a critical error message
159
160 $ python logging_level_example.py info
161 INFO:root:This is an info message
162 WARNING:root:This is a warning message
163 ERROR:root:This is an error message
164 CRITICAL:root:This is a critical error message
165
166You will notice that these log messages all have ``root`` embedded in them. The
167logging module supports a hierarchy of loggers with different names. An easy
168way to tell where a specific log message comes from is to use a separate logger
169object for each of your modules. Each new logger "inherits" the configuration
170of its parent, and log messages sent to a logger include the name of that
171logger. Optionally, each logger can be configured differently, so that messages
172from different modules are handled in different ways. Let's look at a simple
173example of how to log from different modules so it is easy to trace the source
174of the message::
175
176 import logging
177
178 logging.basicConfig(level=logging.WARNING)
179
180 logger1 = logging.getLogger('package1.module1')
181 logger2 = logging.getLogger('package2.module2')
182
183 logger1.warning('This message comes from one module')
184 logger2.warning('And this message comes from another module')
185
186And the output::
187
188 $ python logging_modules_example.py
189 WARNING:package1.module1:This message comes from one module
190 WARNING:package2.module2:And this message comes from another module
191
192There are many more options for configuring logging, including different log
193message formatting options, having messages delivered to multiple destinations,
194and changing the configuration of a long-running application on the fly using a
195socket interface. All of these options are covered in depth in the library
196module documentation.
197
198Loggers
199^^^^^^^
200
201The logging library takes a modular approach and offers the several categories
202of components: loggers, handlers, filters, and formatters. Loggers expose the
203interface that application code directly uses. Handlers send the log records to
204the appropriate destination. Filters provide a finer grained facility for
205determining which log records to send on to a handler. Formatters specify the
206layout of the resultant log record.
207
208:class:`Logger` objects have a threefold job. First, they expose several
209methods to application code so that applications can log messages at runtime.
210Second, logger objects determine which log messages to act upon based upon
211severity (the default filtering facility) or filter objects. Third, logger
212objects pass along relevant log messages to all interested log handlers.
213
214The most widely used methods on logger objects fall into two categories:
215configuration and message sending.
216
217* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
218 will handle, where debug is the lowest built-in severity level and critical is
219 the highest built-in severity. For example, if the severity level is info,
220 the logger will handle only info, warning, error, and critical messages and
221 will ignore debug messages.
222
223* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
224 objects from the logger object. This tutorial does not address filters.
225
226With the logger object configured, the following methods create log messages:
227
228* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
229 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
230 a message and a level that corresponds to their respective method names. The
231 message is actually a format string, which may contain the standard string
232 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
233 rest of their arguments is a list of objects that correspond with the
234 substitution fields in the message. With regard to :const:`**kwargs`, the
235 logging methods care only about a keyword of :const:`exc_info` and use it to
236 determine whether to log exception information.
237
238* :meth:`Logger.exception` creates a log message similar to
239 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
240 stack trace along with it. Call this method only from an exception handler.
241
242* :meth:`Logger.log` takes a log level as an explicit argument. This is a
243 little more verbose for logging messages than using the log level convenience
244 methods listed above, but this is how to log at custom log levels.
245
246:func:`getLogger` returns a reference to a logger instance with a name of name
247if a name is provided, or root if not. The names are period-separated
248hierarchical structures. Multiple calls to :func:`getLogger` with the same name
249will return a reference to the same logger object. Loggers that are further
250down in the hierarchical list are children of loggers higher up in the list.
251For example, given a logger with a name of ``foo``, loggers with names of
252``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all children of ``foo``.
253Child loggers propagate messages up to their parent loggers. Because of this,
254it is unnecessary to define and configure all the loggers an application uses.
255It is sufficient to configure a top-level logger and create child loggers as
256needed.
257
258
259Handlers
260^^^^^^^^
261
262:class:`Handler` objects are responsible for dispatching the appropriate log
263messages (based on the log messages' severity) to the handler's specified
264destination. Logger objects can add zero or more handler objects to themselves
265with an :func:`addHandler` method. As an example scenario, an application may
266want to send all log messages to a log file, all log messages of error or higher
267to stdout, and all messages of critical to an email address. This scenario
268requires three individual handlers where each hander is responsible for sending
269messages of a specific severity to a specific location.
270
271The standard library includes quite a few handler types; this tutorial uses only
272:class:`StreamHandler` and :class:`FileHandler` in its examples.
273
274There are very few methods in a handler for application developers to concern
275themselves with. The only handler methods that seem relevant for application
276developers who are using the built-in handler objects (that is, not creating
277custom handlers) are the following configuration methods:
278
279* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
280 lowest severity that will be dispatched to the appropriate destination. Why
281 are there two :func:`setLevel` methods? The level set in the logger
282 determines which severity of messages it will pass to its handlers. The level
283 set in each handler determines which messages that handler will send on.
284 :func:`setFormatter` selects a Formatter object for this handler to use.
285
286* :func:`addFilter` and :func:`removeFilter` respectively configure and
287 deconfigure filter objects on handlers.
288
289Application code should not directly instantiate and use handlers. Instead, the
290:class:`Handler` class is a base class that defines the interface that all
291Handlers should have and establishes some default behavior that child classes
292can use (or override).
293
294
295Formatters
296^^^^^^^^^^
297
298Formatter objects configure the final order, structure, and contents of the log
299message. Unlike the base logging.Handler class, application code may
300instantiate formatter classes, although you could likely subclass the formatter
301if your application needs special behavior. The constructor takes two optional
302arguments: a message format string and a date format string. If there is no
303message format string, the default is to use the raw message. If there is no
304date format string, the default date format is::
305
306 %Y-%m-%d %H:%M:%S
307
308with the milliseconds tacked on at the end.
309
310The message format string uses ``%(<dictionary key>)s`` styled string
311substitution; the possible keys are documented in :ref:`formatter-objects`.
312
313The following message format string will log the time in a human-readable
314format, the severity of the message, and the contents of the message, in that
315order::
316
317 "%(asctime)s - %(levelname)s - %(message)s"
318
319
320Configuring Logging
321^^^^^^^^^^^^^^^^^^^
322
323Programmers can configure logging either by creating loggers, handlers, and
324formatters explicitly in a main module with the configuration methods listed
325above (using Python code), or by creating a logging config file. The following
326code is an example of configuring a very simple logger, a console handler, and a
327simple formatter in a Python module::
328
329 import logging
330
331 # create logger
332 logger = logging.getLogger("simple_example")
333 logger.setLevel(logging.DEBUG)
334 # create console handler and set level to debug
335 ch = logging.StreamHandler()
336 ch.setLevel(logging.DEBUG)
337 # create formatter
338 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
339 # add formatter to ch
340 ch.setFormatter(formatter)
341 # add ch to logger
342 logger.addHandler(ch)
343
344 # "application" code
345 logger.debug("debug message")
346 logger.info("info message")
347 logger.warn("warn message")
348 logger.error("error message")
349 logger.critical("critical message")
350
351Running this module from the command line produces the following output::
352
353 $ python simple_logging_module.py
354 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
355 2005-03-19 15:10:26,620 - simple_example - INFO - info message
356 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
357 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
358 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
359
360The following Python module creates a logger, handler, and formatter nearly
361identical to those in the example listed above, with the only difference being
362the names of the objects::
363
364 import logging
365 import logging.config
366
367 logging.config.fileConfig("logging.conf")
368
369 # create logger
370 logger = logging.getLogger("simpleExample")
371
372 # "application" code
373 logger.debug("debug message")
374 logger.info("info message")
375 logger.warn("warn message")
376 logger.error("error message")
377 logger.critical("critical message")
378
379Here is the logging.conf file::
380
381 [loggers]
382 keys=root,simpleExample
383
384 [handlers]
385 keys=consoleHandler
386
387 [formatters]
388 keys=simpleFormatter
389
390 [logger_root]
391 level=DEBUG
392 handlers=consoleHandler
393
394 [logger_simpleExample]
395 level=DEBUG
396 handlers=consoleHandler
397 qualname=simpleExample
398 propagate=0
399
400 [handler_consoleHandler]
401 class=StreamHandler
402 level=DEBUG
403 formatter=simpleFormatter
404 args=(sys.stdout,)
405
406 [formatter_simpleFormatter]
407 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
408 datefmt=
409
410The output is nearly identical to that of the non-config-file-based example::
411
412 $ python simple_logging_config.py
413 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
414 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
415 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
416 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
417 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
418
419You can see that the config file approach has a few advantages over the Python
420code approach, mainly separation of configuration and code and the ability of
421noncoders to easily modify the logging properties.
422
423
424Logging Levels
425--------------
426
Georg Brandl116aa622007-08-15 14:28:22 +0000427The numeric values of logging levels are given in the following table. These are
428primarily of interest if you want to define your own levels, and need them to
429have specific values relative to the predefined levels. If you define a level
430with the same numeric value, it overwrites the predefined value; the predefined
431name is lost.
432
433+--------------+---------------+
434| Level | Numeric value |
435+==============+===============+
436| ``CRITICAL`` | 50 |
437+--------------+---------------+
438| ``ERROR`` | 40 |
439+--------------+---------------+
440| ``WARNING`` | 30 |
441+--------------+---------------+
442| ``INFO`` | 20 |
443+--------------+---------------+
444| ``DEBUG`` | 10 |
445+--------------+---------------+
446| ``NOTSET`` | 0 |
447+--------------+---------------+
448
449Levels can also be associated with loggers, being set either by the developer or
450through loading a saved logging configuration. When a logging method is called
451on a logger, the logger compares its own level with the level associated with
452the method call. If the logger's level is higher than the method call's, no
453logging message is actually generated. This is the basic mechanism controlling
454the verbosity of logging output.
455
456Logging messages are encoded as instances of the :class:`LogRecord` class. When
457a logger decides to actually log an event, a :class:`LogRecord` instance is
458created from the logging message.
459
460Logging messages are subjected to a dispatch mechanism through the use of
461:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
462class. Handlers are responsible for ensuring that a logged message (in the form
463of a :class:`LogRecord`) ends up in a particular location (or set of locations)
464which is useful for the target audience for that message (such as end users,
465support desk staff, system administrators, developers). Handlers are passed
466:class:`LogRecord` instances intended for particular destinations. Each logger
467can have zero, one or more handlers associated with it (via the
468:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
469directly associated with a logger, *all handlers associated with all ancestors
470of the logger* are called to dispatch the message.
471
472Just as for loggers, handlers can have levels associated with them. A handler's
473level acts as a filter in the same way as a logger's level does. If a handler
474decides to actually dispatch an event, the :meth:`emit` method is used to send
475the message to its destination. Most user-defined subclasses of :class:`Handler`
476will need to override this :meth:`emit`.
477
478In addition to the base :class:`Handler` class, many useful subclasses are
479provided:
480
481#. :class:`StreamHandler` instances send error messages to streams (file-like
482 objects).
483
484#. :class:`FileHandler` instances send error messages to disk files.
485
486#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log
487 files at a certain point. It is not meant to be instantiated directly. Instead,
488 use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`.
489
490#. :class:`RotatingFileHandler` instances send error messages to disk files,
491 with support for maximum log file sizes and log file rotation.
492
493#. :class:`TimedRotatingFileHandler` instances send error messages to disk files
494 rotating the log file at certain timed intervals.
495
496#. :class:`SocketHandler` instances send error messages to TCP/IP sockets.
497
498#. :class:`DatagramHandler` instances send error messages to UDP sockets.
499
500#. :class:`SMTPHandler` instances send error messages to a designated email
501 address.
502
503#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon,
504 possibly on a remote machine.
505
506#. :class:`NTEventLogHandler` instances send error messages to a Windows
507 NT/2000/XP event log.
508
509#. :class:`MemoryHandler` instances send error messages to a buffer in memory,
510 which is flushed whenever specific criteria are met.
511
512#. :class:`HTTPHandler` instances send error messages to an HTTP server using
513 either ``GET`` or ``POST`` semantics.
514
515The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the
516core logging package. The other handlers are defined in a sub- module,
517:mod:`logging.handlers`. (There is also another sub-module,
518:mod:`logging.config`, for configuration functionality.)
519
520Logged messages are formatted for presentation through instances of the
521:class:`Formatter` class. They are initialized with a format string suitable for
522use with the % operator and a dictionary.
523
524For formatting multiple messages in a batch, instances of
525:class:`BufferingFormatter` can be used. In addition to the format string (which
526is applied to each message in the batch), there is provision for header and
527trailer format strings.
528
529When filtering based on logger level and/or handler level is not enough,
530instances of :class:`Filter` can be added to both :class:`Logger` and
531:class:`Handler` instances (through their :meth:`addFilter` method). Before
532deciding to process a message further, both loggers and handlers consult all
533their filters for permission. If any filter returns a false value, the message
534is not processed further.
535
536The basic :class:`Filter` functionality allows filtering by specific logger
537name. If this feature is used, messages sent to the named logger and its
538children are allowed through the filter, and all others dropped.
539
540In addition to the classes described above, there are a number of module- level
541functions.
542
543
544.. function:: getLogger([name])
545
546 Return a logger with the specified name or, if no name is specified, return a
547 logger which is the root logger of the hierarchy. If specified, the name is
548 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
549 Choice of these names is entirely up to the developer who is using logging.
550
551 All calls to this function with a given name return the same logger instance.
552 This means that logger instances never need to be passed between different parts
553 of an application.
554
555
556.. function:: getLoggerClass()
557
558 Return either the standard :class:`Logger` class, or the last class passed to
559 :func:`setLoggerClass`. This function may be called from within a new class
560 definition, to ensure that installing a customised :class:`Logger` class will
561 not undo customisations already applied by other code. For example::
562
563 class MyLogger(logging.getLoggerClass()):
564 # ... override behaviour here
565
566
567.. function:: debug(msg[, *args[, **kwargs]])
568
569 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
570 message format string, and the *args* are the arguments which are merged into
571 *msg* using the string formatting operator. (Note that this means that you can
572 use keywords in the format string, together with a single dictionary argument.)
573
574 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
575 which, if it does not evaluate as false, causes exception information to be
576 added to the logging message. If an exception tuple (in the format returned by
577 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
578 is called to get the exception information.
579
580 The other optional keyword argument is *extra* which can be used to pass a
581 dictionary which is used to populate the __dict__ of the LogRecord created for
582 the logging event with user-defined attributes. These custom attributes can then
583 be used as you like. For example, they could be incorporated into logged
584 messages. For example::
585
586 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
587 logging.basicConfig(format=FORMAT)
588 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
589 logging.warning("Protocol problem: %s", "connection reset", extra=d)
590
591 would print something like ::
592
593 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
594
595 The keys in the dictionary passed in *extra* should not clash with the keys used
596 by the logging system. (See the :class:`Formatter` documentation for more
597 information on which keys are used by the logging system.)
598
599 If you choose to use these attributes in logged messages, you need to exercise
600 some care. In the above example, for instance, the :class:`Formatter` has been
601 set up with a format string which expects 'clientip' and 'user' in the attribute
602 dictionary of the LogRecord. If these are missing, the message will not be
603 logged because a string formatting exception will occur. So in this case, you
604 always need to pass the *extra* dictionary with these keys.
605
606 While this might be annoying, this feature is intended for use in specialized
607 circumstances, such as multi-threaded servers where the same code executes in
608 many contexts, and interesting conditions which arise are dependent on this
609 context (such as remote client IP address and authenticated user name, in the
610 above example). In such circumstances, it is likely that specialized
611 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
612
Georg Brandl116aa622007-08-15 14:28:22 +0000613
614.. function:: info(msg[, *args[, **kwargs]])
615
616 Logs a message with level :const:`INFO` on the root logger. The arguments are
617 interpreted as for :func:`debug`.
618
619
620.. function:: warning(msg[, *args[, **kwargs]])
621
622 Logs a message with level :const:`WARNING` on the root logger. The arguments are
623 interpreted as for :func:`debug`.
624
625
626.. function:: error(msg[, *args[, **kwargs]])
627
628 Logs a message with level :const:`ERROR` on the root logger. The arguments are
629 interpreted as for :func:`debug`.
630
631
632.. function:: critical(msg[, *args[, **kwargs]])
633
634 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
635 are interpreted as for :func:`debug`.
636
637
638.. function:: exception(msg[, *args])
639
640 Logs a message with level :const:`ERROR` on the root logger. The arguments are
641 interpreted as for :func:`debug`. Exception info is added to the logging
642 message. This function should only be called from an exception handler.
643
644
645.. function:: log(level, msg[, *args[, **kwargs]])
646
647 Logs a message with level *level* on the root logger. The other arguments are
648 interpreted as for :func:`debug`.
649
650
651.. function:: disable(lvl)
652
653 Provides an overriding level *lvl* for all loggers which takes precedence over
654 the logger's own level. When the need arises to temporarily throttle logging
655 output down across the whole application, this function can be useful.
656
657
658.. function:: addLevelName(lvl, levelName)
659
660 Associates level *lvl* with text *levelName* in an internal dictionary, which is
661 used to map numeric levels to a textual representation, for example when a
662 :class:`Formatter` formats a message. This function can also be used to define
663 your own levels. The only constraints are that all levels used must be
664 registered using this function, levels should be positive integers and they
665 should increase in increasing order of severity.
666
667
668.. function:: getLevelName(lvl)
669
670 Returns the textual representation of logging level *lvl*. If the level is one
671 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
672 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
673 have associated levels with names using :func:`addLevelName` then the name you
674 have associated with *lvl* is returned. If a numeric value corresponding to one
675 of the defined levels is passed in, the corresponding string representation is
676 returned. Otherwise, the string "Level %s" % lvl is returned.
677
678
679.. function:: makeLogRecord(attrdict)
680
681 Creates and returns a new :class:`LogRecord` instance whose attributes are
682 defined by *attrdict*. This function is useful for taking a pickled
683 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
684 it as a :class:`LogRecord` instance at the receiving end.
685
686
687.. function:: basicConfig([**kwargs])
688
689 Does basic configuration for the logging system by creating a
690 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Christian Heimes043d6f62008-01-07 17:19:16 +0000691 root logger. The function does nothing if any handlers have been defined for
692 the root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000693 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
694 if no handlers are defined for the root logger.
695
Georg Brandl116aa622007-08-15 14:28:22 +0000696 The following keyword arguments are supported.
697
698 +--------------+---------------------------------------------+
699 | Format | Description |
700 +==============+=============================================+
701 | ``filename`` | Specifies that a FileHandler be created, |
702 | | using the specified filename, rather than a |
703 | | StreamHandler. |
704 +--------------+---------------------------------------------+
705 | ``filemode`` | Specifies the mode to open the file, if |
706 | | filename is specified (if filemode is |
707 | | unspecified, it defaults to 'a'). |
708 +--------------+---------------------------------------------+
709 | ``format`` | Use the specified format string for the |
710 | | handler. |
711 +--------------+---------------------------------------------+
712 | ``datefmt`` | Use the specified date/time format. |
713 +--------------+---------------------------------------------+
714 | ``level`` | Set the root logger level to the specified |
715 | | level. |
716 +--------------+---------------------------------------------+
717 | ``stream`` | Use the specified stream to initialize the |
718 | | StreamHandler. Note that this argument is |
719 | | incompatible with 'filename' - if both are |
720 | | present, 'stream' is ignored. |
721 +--------------+---------------------------------------------+
722
723
724.. function:: shutdown()
725
726 Informs the logging system to perform an orderly shutdown by flushing and
727 closing all handlers.
728
729
730.. function:: setLoggerClass(klass)
731
732 Tells the logging system to use the class *klass* when instantiating a logger.
733 The class should define :meth:`__init__` such that only a name argument is
734 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
735 function is typically called before any loggers are instantiated by applications
736 which need to use custom logger behavior.
737
738
739.. seealso::
740
741 :pep:`282` - A Logging System
742 The proposal which described this feature for inclusion in the Python standard
743 library.
744
Christian Heimes255f53b2007-12-08 15:33:56 +0000745 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000746 This is the original source for the :mod:`logging` package. The version of the
747 package available from this site is suitable for use with Python 1.5.2, 2.1.x
748 and 2.2.x, which do not include the :mod:`logging` package in the standard
749 library.
750
751
752Logger Objects
753--------------
754
755Loggers have the following attributes and methods. Note that Loggers are never
756instantiated directly, but always through the module-level function
757``logging.getLogger(name)``.
758
759
760.. attribute:: Logger.propagate
761
762 If this evaluates to false, logging messages are not passed by this logger or by
763 child loggers to higher level (ancestor) loggers. The constructor sets this
764 attribute to 1.
765
766
767.. method:: Logger.setLevel(lvl)
768
769 Sets the threshold for this logger to *lvl*. Logging messages which are less
770 severe than *lvl* will be ignored. When a logger is created, the level is set to
771 :const:`NOTSET` (which causes all messages to be processed when the logger is
772 the root logger, or delegation to the parent when the logger is a non-root
773 logger). Note that the root logger is created with level :const:`WARNING`.
774
775 The term "delegation to the parent" means that if a logger has a level of
776 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
777 a level other than NOTSET is found, or the root is reached.
778
779 If an ancestor is found with a level other than NOTSET, then that ancestor's
780 level is treated as the effective level of the logger where the ancestor search
781 began, and is used to determine how a logging event is handled.
782
783 If the root is reached, and it has a level of NOTSET, then all messages will be
784 processed. Otherwise, the root's level will be used as the effective level.
785
786
787.. method:: Logger.isEnabledFor(lvl)
788
789 Indicates if a message of severity *lvl* would be processed by this logger.
790 This method checks first the module-level level set by
791 ``logging.disable(lvl)`` and then the logger's effective level as determined
792 by :meth:`getEffectiveLevel`.
793
794
795.. method:: Logger.getEffectiveLevel()
796
797 Indicates the effective level for this logger. If a value other than
798 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
799 the hierarchy is traversed towards the root until a value other than
800 :const:`NOTSET` is found, and that value is returned.
801
802
803.. method:: Logger.debug(msg[, *args[, **kwargs]])
804
805 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
806 message format string, and the *args* are the arguments which are merged into
807 *msg* using the string formatting operator. (Note that this means that you can
808 use keywords in the format string, together with a single dictionary argument.)
809
810 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
811 which, if it does not evaluate as false, causes exception information to be
812 added to the logging message. If an exception tuple (in the format returned by
813 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
814 is called to get the exception information.
815
816 The other optional keyword argument is *extra* which can be used to pass a
817 dictionary which is used to populate the __dict__ of the LogRecord created for
818 the logging event with user-defined attributes. These custom attributes can then
819 be used as you like. For example, they could be incorporated into logged
820 messages. For example::
821
822 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
823 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000824 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +0000825 logger = logging.getLogger("tcpserver")
826 logger.warning("Protocol problem: %s", "connection reset", extra=d)
827
828 would print something like ::
829
830 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
831
832 The keys in the dictionary passed in *extra* should not clash with the keys used
833 by the logging system. (See the :class:`Formatter` documentation for more
834 information on which keys are used by the logging system.)
835
836 If you choose to use these attributes in logged messages, you need to exercise
837 some care. In the above example, for instance, the :class:`Formatter` has been
838 set up with a format string which expects 'clientip' and 'user' in the attribute
839 dictionary of the LogRecord. If these are missing, the message will not be
840 logged because a string formatting exception will occur. So in this case, you
841 always need to pass the *extra* dictionary with these keys.
842
843 While this might be annoying, this feature is intended for use in specialized
844 circumstances, such as multi-threaded servers where the same code executes in
845 many contexts, and interesting conditions which arise are dependent on this
846 context (such as remote client IP address and authenticated user name, in the
847 above example). In such circumstances, it is likely that specialized
848 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
849
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851.. method:: Logger.info(msg[, *args[, **kwargs]])
852
853 Logs a message with level :const:`INFO` on this logger. The arguments are
854 interpreted as for :meth:`debug`.
855
856
857.. method:: Logger.warning(msg[, *args[, **kwargs]])
858
859 Logs a message with level :const:`WARNING` on this logger. The arguments are
860 interpreted as for :meth:`debug`.
861
862
863.. method:: Logger.error(msg[, *args[, **kwargs]])
864
865 Logs a message with level :const:`ERROR` on this logger. The arguments are
866 interpreted as for :meth:`debug`.
867
868
869.. method:: Logger.critical(msg[, *args[, **kwargs]])
870
871 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
872 interpreted as for :meth:`debug`.
873
874
875.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
876
877 Logs a message with integer level *lvl* on this logger. The other arguments are
878 interpreted as for :meth:`debug`.
879
880
881.. method:: Logger.exception(msg[, *args])
882
883 Logs a message with level :const:`ERROR` on this logger. The arguments are
884 interpreted as for :meth:`debug`. Exception info is added to the logging
885 message. This method should only be called from an exception handler.
886
887
888.. method:: Logger.addFilter(filt)
889
890 Adds the specified filter *filt* to this logger.
891
892
893.. method:: Logger.removeFilter(filt)
894
895 Removes the specified filter *filt* from this logger.
896
897
898.. method:: Logger.filter(record)
899
900 Applies this logger's filters to the record and returns a true value if the
901 record is to be processed.
902
903
904.. method:: Logger.addHandler(hdlr)
905
906 Adds the specified handler *hdlr* to this logger.
907
908
909.. method:: Logger.removeHandler(hdlr)
910
911 Removes the specified handler *hdlr* from this logger.
912
913
914.. method:: Logger.findCaller()
915
916 Finds the caller's source filename and line number. Returns the filename, line
917 number and function name as a 3-element tuple.
918
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920.. method:: Logger.handle(record)
921
922 Handles a record by passing it to all handlers associated with this logger and
923 its ancestors (until a false value of *propagate* is found). This method is used
924 for unpickled records received from a socket, as well as those created locally.
925 Logger-level filtering is applied using :meth:`filter`.
926
927
928.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
929
930 This is a factory method which can be overridden in subclasses to create
931 specialized :class:`LogRecord` instances.
932
Georg Brandl116aa622007-08-15 14:28:22 +0000933
934.. _minimal-example:
935
936Basic example
937-------------
938
Georg Brandl116aa622007-08-15 14:28:22 +0000939The :mod:`logging` package provides a lot of flexibility, and its configuration
940can appear daunting. This section demonstrates that simple use of the logging
941package is possible.
942
943The simplest example shows logging to the console::
944
945 import logging
946
947 logging.debug('A debug message')
948 logging.info('Some information')
949 logging.warning('A shot across the bows')
950
951If you run the above script, you'll see this::
952
953 WARNING:root:A shot across the bows
954
955Because no particular logger was specified, the system used the root logger. The
956debug and info messages didn't appear because by default, the root logger is
957configured to only handle messages with a severity of WARNING or above. The
958message format is also a configuration default, as is the output destination of
959the messages - ``sys.stderr``. The severity level, the message format and
960destination can be easily changed, as shown in the example below::
961
962 import logging
963
964 logging.basicConfig(level=logging.DEBUG,
965 format='%(asctime)s %(levelname)s %(message)s',
966 filename='/tmp/myapp.log',
967 filemode='w')
968 logging.debug('A debug message')
969 logging.info('Some information')
970 logging.warning('A shot across the bows')
971
972The :meth:`basicConfig` method is used to change the configuration defaults,
973which results in output (written to ``/tmp/myapp.log``) which should look
974something like the following::
975
976 2004-07-02 13:00:08,743 DEBUG A debug message
977 2004-07-02 13:00:08,743 INFO Some information
978 2004-07-02 13:00:08,743 WARNING A shot across the bows
979
980This time, all messages with a severity of DEBUG or above were handled, and the
981format of the messages was also changed, and output went to the specified file
982rather than the console.
983
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000984.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +0000985
986Formatting uses the old Python string formatting - see section
987:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +0000988specifiers. For a complete list of specifiers, consult the :class:`Formatter`
989documentation.
990
991+-------------------+-----------------------------------------------+
992| Format | Description |
993+===================+===============================================+
994| ``%(name)s`` | Name of the logger (logging channel). |
995+-------------------+-----------------------------------------------+
996| ``%(levelname)s`` | Text logging level for the message |
997| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
998| | ``'ERROR'``, ``'CRITICAL'``). |
999+-------------------+-----------------------------------------------+
1000| ``%(asctime)s`` | Human-readable time when the |
1001| | :class:`LogRecord` was created. By default |
1002| | this is of the form "2003-07-08 16:49:45,896" |
1003| | (the numbers after the comma are millisecond |
1004| | portion of the time). |
1005+-------------------+-----------------------------------------------+
1006| ``%(message)s`` | The logged message. |
1007+-------------------+-----------------------------------------------+
1008
1009To change the date/time format, you can pass an additional keyword parameter,
1010*datefmt*, as in the following::
1011
1012 import logging
1013
1014 logging.basicConfig(level=logging.DEBUG,
1015 format='%(asctime)s %(levelname)-8s %(message)s',
1016 datefmt='%a, %d %b %Y %H:%M:%S',
1017 filename='/temp/myapp.log',
1018 filemode='w')
1019 logging.debug('A debug message')
1020 logging.info('Some information')
1021 logging.warning('A shot across the bows')
1022
1023which would result in output like ::
1024
1025 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1026 Fri, 02 Jul 2004 13:06:18 INFO Some information
1027 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1028
1029The date format string follows the requirements of :func:`strftime` - see the
1030documentation for the :mod:`time` module.
1031
1032If, instead of sending logging output to the console or a file, you'd rather use
1033a file-like object which you have created separately, you can pass it to
1034:func:`basicConfig` using the *stream* keyword argument. Note that if both
1035*stream* and *filename* keyword arguments are passed, the *stream* argument is
1036ignored.
1037
1038Of course, you can put variable information in your output. To do this, simply
1039have the message be a format string and pass in additional arguments containing
1040the variable information, as in the following example::
1041
1042 import logging
1043
1044 logging.basicConfig(level=logging.DEBUG,
1045 format='%(asctime)s %(levelname)-8s %(message)s',
1046 datefmt='%a, %d %b %Y %H:%M:%S',
1047 filename='/temp/myapp.log',
1048 filemode='w')
1049 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1050
1051which would result in ::
1052
1053 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1054
1055
1056.. _multiple-destinations:
1057
1058Logging to multiple destinations
1059--------------------------------
1060
1061Let's say you want to log to console and file with different message formats and
1062in differing circumstances. Say you want to log messages with levels of DEBUG
1063and higher to file, and those messages at level INFO and higher to the console.
1064Let's also assume that the file should contain timestamps, but the console
1065messages should not. Here's how you can achieve this::
1066
1067 import logging
1068
1069 # set up logging to file - see previous section for more details
1070 logging.basicConfig(level=logging.DEBUG,
1071 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1072 datefmt='%m-%d %H:%M',
1073 filename='/temp/myapp.log',
1074 filemode='w')
1075 # define a Handler which writes INFO messages or higher to the sys.stderr
1076 console = logging.StreamHandler()
1077 console.setLevel(logging.INFO)
1078 # set a format which is simpler for console use
1079 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1080 # tell the handler to use this format
1081 console.setFormatter(formatter)
1082 # add the handler to the root logger
1083 logging.getLogger('').addHandler(console)
1084
1085 # Now, we can log to the root logger, or any other logger. First the root...
1086 logging.info('Jackdaws love my big sphinx of quartz.')
1087
1088 # Now, define a couple of other loggers which might represent areas in your
1089 # application:
1090
1091 logger1 = logging.getLogger('myapp.area1')
1092 logger2 = logging.getLogger('myapp.area2')
1093
1094 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1095 logger1.info('How quickly daft jumping zebras vex.')
1096 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1097 logger2.error('The five boxing wizards jump quickly.')
1098
1099When you run this, on the console you will see ::
1100
1101 root : INFO Jackdaws love my big sphinx of quartz.
1102 myapp.area1 : INFO How quickly daft jumping zebras vex.
1103 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1104 myapp.area2 : ERROR The five boxing wizards jump quickly.
1105
1106and in the file you will see something like ::
1107
1108 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1109 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1110 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1111 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1112 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1113
1114As you can see, the DEBUG message only shows up in the file. The other messages
1115are sent to both destinations.
1116
1117This example uses console and file handlers, but you can use any number and
1118combination of handlers you choose.
1119
1120
Christian Heimes790c8232008-01-07 21:14:23 +00001121.. _context-info:
1122
1123Adding contextual information to your logging output
1124----------------------------------------------------
1125
1126Sometimes you want logging output to contain contextual information in
1127addition to the parameters passed to the logging call. For example, in a
1128networked application, it may be desirable to log client-specific information
1129in the log (e.g. remote client's username, or IP address). Although you could
1130use the *extra* parameter to achieve this, it's not always convenient to pass
1131the information in this way. While it might be tempting to create
1132:class:`Logger` instances on a per-connection basis, this is not a good idea
1133because these instances are not garbage collected. While this is not a problem
1134in practice, when the number of :class:`Logger` instances is dependent on the
1135level of granularity you want to use in logging an application, it could
1136be hard to manage if the number of :class:`Logger` instances becomes
1137effectively unbounded.
1138
Christian Heimes04c420f2008-01-18 18:40:46 +00001139An easy way in which you can pass contextual information to be output along
1140with logging event information is to use the :class:`LoggerAdapter` class.
1141This class is designed to look like a :class:`Logger`, so that you can call
1142:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1143:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1144same signatures as their counterparts in :class:`Logger`, so you can use the
1145two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001146
Christian Heimes04c420f2008-01-18 18:40:46 +00001147When you create an instance of :class:`LoggerAdapter`, you pass it a
1148:class:`Logger` instance and a dict-like object which contains your contextual
1149information. When you call one of the logging methods on an instance of
1150:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1151:class:`Logger` passed to its constructor, and arranges to pass the contextual
1152information in the delegated call. Here's a snippet from the code of
1153:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001154
Christian Heimes04c420f2008-01-18 18:40:46 +00001155 def debug(self, msg, *args, **kwargs):
1156 """
1157 Delegate a debug call to the underlying logger, after adding
1158 contextual information from this adapter instance.
1159 """
1160 msg, kwargs = self.process(msg, kwargs)
1161 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001162
Christian Heimes04c420f2008-01-18 18:40:46 +00001163The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1164information is added to the logging output. It's passed the message and
1165keyword arguments of the logging call, and it passes back (potentially)
1166modified versions of these to use in the call to the underlying logger. The
1167default implementation of this method leaves the message alone, but inserts
1168an "extra" key in the keyword argument whose value is the dict-like object
1169passed to the constructor. Of course, if you had passed an "extra" keyword
1170argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001171
Christian Heimes04c420f2008-01-18 18:40:46 +00001172The advantage of using "extra" is that the values in the dict-like object are
1173merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1174customized strings with your :class:`Formatter` instances which know about
1175the keys of the dict-like object. If you need a different method, e.g. if you
1176want to prepend or append the contextual information to the message string,
1177you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1178to do what you need. Here's an example script which uses this class, which
1179also illustrates what dict-like behaviour is needed from an arbitrary
1180"dict-like" object for use in the constructor::
1181
Christian Heimes587c2bf2008-01-19 16:21:02 +00001182 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001183
Christian Heimes587c2bf2008-01-19 16:21:02 +00001184 class ConnInfo:
1185 """
1186 An example class which shows how an arbitrary class can be used as
1187 the 'extra' context information repository passed to a LoggerAdapter.
1188 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001189
Christian Heimes587c2bf2008-01-19 16:21:02 +00001190 def __getitem__(self, name):
1191 """
1192 To allow this instance to look like a dict.
1193 """
1194 from random import choice
1195 if name == "ip":
1196 result = choice(["127.0.0.1", "192.168.0.1"])
1197 elif name == "user":
1198 result = choice(["jim", "fred", "sheila"])
1199 else:
1200 result = self.__dict__.get(name, "?")
1201 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001202
Christian Heimes587c2bf2008-01-19 16:21:02 +00001203 def __iter__(self):
1204 """
1205 To allow iteration over keys, which will be merged into
1206 the LogRecord dict before formatting and output.
1207 """
1208 keys = ["ip", "user"]
1209 keys.extend(self.__dict__.keys())
1210 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001211
Christian Heimes587c2bf2008-01-19 16:21:02 +00001212 if __name__ == "__main__":
1213 from random import choice
1214 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1215 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1216 { "ip" : "123.231.231.123", "user" : "sheila" })
1217 logging.basicConfig(level=logging.DEBUG,
1218 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1219 a1.debug("A debug message")
1220 a1.info("An info message with %s", "some parameters")
1221 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1222 for x in range(10):
1223 lvl = choice(levels)
1224 lvlname = logging.getLevelName(lvl)
1225 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001226
1227When this script is run, the output should look something like this::
1228
Christian Heimes587c2bf2008-01-19 16:21:02 +00001229 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1230 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1231 2008-01-18 14:49:54,023 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
1232 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: jim A message at INFO level with 2 parameters
1233 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1234 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: fred A message at ERROR level with 2 parameters
1235 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
1236 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1237 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: jim A message at WARNING level with 2 parameters
1238 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: fred A message at INFO level with 2 parameters
1239 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1240 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Christian Heimes04c420f2008-01-18 18:40:46 +00001241
1242.. versionadded:: 2.6
1243
1244The :class:`LoggerAdapter` class was not present in previous versions.
1245
Christian Heimes790c8232008-01-07 21:14:23 +00001246
Georg Brandl116aa622007-08-15 14:28:22 +00001247.. _network-logging:
1248
1249Sending and receiving logging events across a network
1250-----------------------------------------------------
1251
1252Let's say you want to send logging events across a network, and handle them at
1253the receiving end. A simple way of doing this is attaching a
1254:class:`SocketHandler` instance to the root logger at the sending end::
1255
1256 import logging, logging.handlers
1257
1258 rootLogger = logging.getLogger('')
1259 rootLogger.setLevel(logging.DEBUG)
1260 socketHandler = logging.handlers.SocketHandler('localhost',
1261 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1262 # don't bother with a formatter, since a socket handler sends the event as
1263 # an unformatted pickle
1264 rootLogger.addHandler(socketHandler)
1265
1266 # Now, we can log to the root logger, or any other logger. First the root...
1267 logging.info('Jackdaws love my big sphinx of quartz.')
1268
1269 # Now, define a couple of other loggers which might represent areas in your
1270 # application:
1271
1272 logger1 = logging.getLogger('myapp.area1')
1273 logger2 = logging.getLogger('myapp.area2')
1274
1275 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1276 logger1.info('How quickly daft jumping zebras vex.')
1277 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1278 logger2.error('The five boxing wizards jump quickly.')
1279
1280At the receiving end, you can set up a receiver using the :mod:`SocketServer`
1281module. Here is a basic working example::
1282
1283 import cPickle
1284 import logging
1285 import logging.handlers
1286 import SocketServer
1287 import struct
1288
1289
1290 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
1291 """Handler for a streaming logging request.
1292
1293 This basically logs the record using whatever logging policy is
1294 configured locally.
1295 """
1296
1297 def handle(self):
1298 """
1299 Handle multiple requests - each expected to be a 4-byte length,
1300 followed by the LogRecord in pickle format. Logs the record
1301 according to whatever policy is configured locally.
1302 """
Collin Winter46334482007-09-10 00:49:57 +00001303 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001304 chunk = self.connection.recv(4)
1305 if len(chunk) < 4:
1306 break
1307 slen = struct.unpack(">L", chunk)[0]
1308 chunk = self.connection.recv(slen)
1309 while len(chunk) < slen:
1310 chunk = chunk + self.connection.recv(slen - len(chunk))
1311 obj = self.unPickle(chunk)
1312 record = logging.makeLogRecord(obj)
1313 self.handleLogRecord(record)
1314
1315 def unPickle(self, data):
1316 return cPickle.loads(data)
1317
1318 def handleLogRecord(self, record):
1319 # if a name is specified, we use the named logger rather than the one
1320 # implied by the record.
1321 if self.server.logname is not None:
1322 name = self.server.logname
1323 else:
1324 name = record.name
1325 logger = logging.getLogger(name)
1326 # N.B. EVERY record gets logged. This is because Logger.handle
1327 # is normally called AFTER logger-level filtering. If you want
1328 # to do filtering, do it at the client end to save wasting
1329 # cycles and network bandwidth!
1330 logger.handle(record)
1331
1332 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
1333 """simple TCP socket-based logging receiver suitable for testing.
1334 """
1335
1336 allow_reuse_address = 1
1337
1338 def __init__(self, host='localhost',
1339 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1340 handler=LogRecordStreamHandler):
1341 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
1342 self.abort = 0
1343 self.timeout = 1
1344 self.logname = None
1345
1346 def serve_until_stopped(self):
1347 import select
1348 abort = 0
1349 while not abort:
1350 rd, wr, ex = select.select([self.socket.fileno()],
1351 [], [],
1352 self.timeout)
1353 if rd:
1354 self.handle_request()
1355 abort = self.abort
1356
1357 def main():
1358 logging.basicConfig(
1359 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1360 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001361 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001362 tcpserver.serve_until_stopped()
1363
1364 if __name__ == "__main__":
1365 main()
1366
1367First run the server, and then the client. On the client side, nothing is
1368printed on the console; on the server side, you should see something like::
1369
1370 About to start TCP server...
1371 59 root INFO Jackdaws love my big sphinx of quartz.
1372 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1373 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1374 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1375 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1376
1377
1378Handler Objects
1379---------------
1380
1381Handlers have the following attributes and methods. Note that :class:`Handler`
1382is never instantiated directly; this class acts as a base for more useful
1383subclasses. However, the :meth:`__init__` method in subclasses needs to call
1384:meth:`Handler.__init__`.
1385
1386
1387.. method:: Handler.__init__(level=NOTSET)
1388
1389 Initializes the :class:`Handler` instance by setting its level, setting the list
1390 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1391 serializing access to an I/O mechanism.
1392
1393
1394.. method:: Handler.createLock()
1395
1396 Initializes a thread lock which can be used to serialize access to underlying
1397 I/O functionality which may not be threadsafe.
1398
1399
1400.. method:: Handler.acquire()
1401
1402 Acquires the thread lock created with :meth:`createLock`.
1403
1404
1405.. method:: Handler.release()
1406
1407 Releases the thread lock acquired with :meth:`acquire`.
1408
1409
1410.. method:: Handler.setLevel(lvl)
1411
1412 Sets the threshold for this handler to *lvl*. Logging messages which are less
1413 severe than *lvl* will be ignored. When a handler is created, the level is set
1414 to :const:`NOTSET` (which causes all messages to be processed).
1415
1416
1417.. method:: Handler.setFormatter(form)
1418
1419 Sets the :class:`Formatter` for this handler to *form*.
1420
1421
1422.. method:: Handler.addFilter(filt)
1423
1424 Adds the specified filter *filt* to this handler.
1425
1426
1427.. method:: Handler.removeFilter(filt)
1428
1429 Removes the specified filter *filt* from this handler.
1430
1431
1432.. method:: Handler.filter(record)
1433
1434 Applies this handler's filters to the record and returns a true value if the
1435 record is to be processed.
1436
1437
1438.. method:: Handler.flush()
1439
1440 Ensure all logging output has been flushed. This version does nothing and is
1441 intended to be implemented by subclasses.
1442
1443
1444.. method:: Handler.close()
1445
1446 Tidy up any resources used by the handler. This version does nothing and is
1447 intended to be implemented by subclasses.
1448
1449
1450.. method:: Handler.handle(record)
1451
1452 Conditionally emits the specified logging record, depending on filters which may
1453 have been added to the handler. Wraps the actual emission of the record with
1454 acquisition/release of the I/O thread lock.
1455
1456
1457.. method:: Handler.handleError(record)
1458
1459 This method should be called from handlers when an exception is encountered
1460 during an :meth:`emit` call. By default it does nothing, which means that
1461 exceptions get silently ignored. This is what is mostly wanted for a logging
1462 system - most users will not care about errors in the logging system, they are
1463 more interested in application errors. You could, however, replace this with a
1464 custom handler if you wish. The specified record is the one which was being
1465 processed when the exception occurred.
1466
1467
1468.. method:: Handler.format(record)
1469
1470 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1471 default formatter for the module.
1472
1473
1474.. method:: Handler.emit(record)
1475
1476 Do whatever it takes to actually log the specified logging record. This version
1477 is intended to be implemented by subclasses and so raises a
1478 :exc:`NotImplementedError`.
1479
1480
1481StreamHandler
1482^^^^^^^^^^^^^
1483
1484The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1485sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1486file-like object (or, more precisely, any object which supports :meth:`write`
1487and :meth:`flush` methods).
1488
1489
1490.. class:: StreamHandler([strm])
1491
1492 Returns a new instance of the :class:`StreamHandler` class. If *strm* is
1493 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1494 will be used.
1495
1496
1497.. method:: StreamHandler.emit(record)
1498
1499 If a formatter is specified, it is used to format the record. The record is then
1500 written to the stream with a trailing newline. If exception information is
1501 present, it is formatted using :func:`traceback.print_exception` and appended to
1502 the stream.
1503
1504
1505.. method:: StreamHandler.flush()
1506
1507 Flushes the stream by calling its :meth:`flush` method. Note that the
1508 :meth:`close` method is inherited from :class:`Handler` and so does nothing, so
1509 an explicit :meth:`flush` call may be needed at times.
1510
1511
1512FileHandler
1513^^^^^^^^^^^
1514
1515The :class:`FileHandler` class, located in the core :mod:`logging` package,
1516sends logging output to a disk file. It inherits the output functionality from
1517:class:`StreamHandler`.
1518
1519
1520.. class:: FileHandler(filename[, mode[, encoding]])
1521
1522 Returns a new instance of the :class:`FileHandler` class. The specified file is
1523 opened and used as the stream for logging. If *mode* is not specified,
1524 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
1525 with that encoding. By default, the file grows indefinitely.
1526
1527
1528.. method:: FileHandler.close()
1529
1530 Closes the file.
1531
1532
1533.. method:: FileHandler.emit(record)
1534
1535 Outputs the record to the file.
1536
1537
1538WatchedFileHandler
1539^^^^^^^^^^^^^^^^^^
1540
Georg Brandl116aa622007-08-15 14:28:22 +00001541The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1542module, is a :class:`FileHandler` which watches the file it is logging to. If
1543the file changes, it is closed and reopened using the file name.
1544
1545A file change can happen because of usage of programs such as *newsyslog* and
1546*logrotate* which perform log file rotation. This handler, intended for use
1547under Unix/Linux, watches the file to see if it has changed since the last emit.
1548(A file is deemed to have changed if its device or inode have changed.) If the
1549file has changed, the old file stream is closed, and the file opened to get a
1550new stream.
1551
1552This handler is not appropriate for use under Windows, because under Windows
1553open log files cannot be moved or renamed - logging opens the files with
1554exclusive locks - and so there is no need for such a handler. Furthermore,
1555*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1556this value.
1557
1558
1559.. class:: WatchedFileHandler(filename[,mode[, encoding]])
1560
1561 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1562 file is opened and used as the stream for logging. If *mode* is not specified,
1563 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
1564 with that encoding. By default, the file grows indefinitely.
1565
1566
1567.. method:: WatchedFileHandler.emit(record)
1568
1569 Outputs the record to the file, but first checks to see if the file has changed.
1570 If it has, the existing stream is flushed and closed and the file opened again,
1571 before outputting the record to the file.
1572
1573
1574RotatingFileHandler
1575^^^^^^^^^^^^^^^^^^^
1576
1577The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1578module, supports rotation of disk log files.
1579
1580
1581.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount]]])
1582
1583 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1584 file is opened and used as the stream for logging. If *mode* is not specified,
1585 ``'a'`` is used. By default, the file grows indefinitely.
1586
1587 You can use the *maxBytes* and *backupCount* values to allow the file to
1588 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1589 the file is closed and a new file is silently opened for output. Rollover occurs
1590 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1591 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1592 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1593 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1594 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1595 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1596 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1597 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1598 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1599
1600
1601.. method:: RotatingFileHandler.doRollover()
1602
1603 Does a rollover, as described above.
1604
1605
1606.. method:: RotatingFileHandler.emit(record)
1607
1608 Outputs the record to the file, catering for rollover as described previously.
1609
1610
1611TimedRotatingFileHandler
1612^^^^^^^^^^^^^^^^^^^^^^^^
1613
1614The :class:`TimedRotatingFileHandler` class, located in the
1615:mod:`logging.handlers` module, supports rotation of disk log files at certain
1616timed intervals.
1617
1618
1619.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])
1620
1621 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1622 specified file is opened and used as the stream for logging. On rotating it also
1623 sets the filename suffix. Rotating happens based on the product of *when* and
1624 *interval*.
1625
1626 You can use the *when* to specify the type of *interval*. The list of possible
1627 values is, note that they are not case sensitive:
1628
1629 +----------+-----------------------+
1630 | Value | Type of interval |
1631 +==========+=======================+
1632 | S | Seconds |
1633 +----------+-----------------------+
1634 | M | Minutes |
1635 +----------+-----------------------+
1636 | H | Hours |
1637 +----------+-----------------------+
1638 | D | Days |
1639 +----------+-----------------------+
1640 | W | Week day (0=Monday) |
1641 +----------+-----------------------+
1642 | midnight | Roll over at midnight |
1643 +----------+-----------------------+
1644
1645 If *backupCount* is non-zero, the system will save old log files by appending
1646 extensions to the filename. The extensions are date-and-time based, using the
1647 strftime format ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on
1648 the rollover interval. At most *backupCount* files will be kept, and if more
1649 would be created when rollover occurs, the oldest one is deleted.
1650
1651
1652.. method:: TimedRotatingFileHandler.doRollover()
1653
1654 Does a rollover, as described above.
1655
1656
1657.. method:: TimedRotatingFileHandler.emit(record)
1658
1659 Outputs the record to the file, catering for rollover as described above.
1660
1661
1662SocketHandler
1663^^^^^^^^^^^^^
1664
1665The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
1666sends logging output to a network socket. The base class uses a TCP socket.
1667
1668
1669.. class:: SocketHandler(host, port)
1670
1671 Returns a new instance of the :class:`SocketHandler` class intended to
1672 communicate with a remote machine whose address is given by *host* and *port*.
1673
1674
1675.. method:: SocketHandler.close()
1676
1677 Closes the socket.
1678
1679
1680.. method:: SocketHandler.emit()
1681
1682 Pickles the record's attribute dictionary and writes it to the socket in binary
1683 format. If there is an error with the socket, silently drops the packet. If the
1684 connection was previously lost, re-establishes the connection. To unpickle the
1685 record at the receiving end into a :class:`LogRecord`, use the
1686 :func:`makeLogRecord` function.
1687
1688
1689.. method:: SocketHandler.handleError()
1690
1691 Handles an error which has occurred during :meth:`emit`. The most likely cause
1692 is a lost connection. Closes the socket so that we can retry on the next event.
1693
1694
1695.. method:: SocketHandler.makeSocket()
1696
1697 This is a factory method which allows subclasses to define the precise type of
1698 socket they want. The default implementation creates a TCP socket
1699 (:const:`socket.SOCK_STREAM`).
1700
1701
1702.. method:: SocketHandler.makePickle(record)
1703
1704 Pickles the record's attribute dictionary in binary format with a length prefix,
1705 and returns it ready for transmission across the socket.
1706
1707
1708.. method:: SocketHandler.send(packet)
1709
1710 Send a pickled string *packet* to the socket. This function allows for partial
1711 sends which can happen when the network is busy.
1712
1713
1714DatagramHandler
1715^^^^^^^^^^^^^^^
1716
1717The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
1718module, inherits from :class:`SocketHandler` to support sending logging messages
1719over UDP sockets.
1720
1721
1722.. class:: DatagramHandler(host, port)
1723
1724 Returns a new instance of the :class:`DatagramHandler` class intended to
1725 communicate with a remote machine whose address is given by *host* and *port*.
1726
1727
1728.. method:: DatagramHandler.emit()
1729
1730 Pickles the record's attribute dictionary and writes it to the socket in binary
1731 format. If there is an error with the socket, silently drops the packet. To
1732 unpickle the record at the receiving end into a :class:`LogRecord`, use the
1733 :func:`makeLogRecord` function.
1734
1735
1736.. method:: DatagramHandler.makeSocket()
1737
1738 The factory method of :class:`SocketHandler` is here overridden to create a UDP
1739 socket (:const:`socket.SOCK_DGRAM`).
1740
1741
1742.. method:: DatagramHandler.send(s)
1743
1744 Send a pickled string to a socket.
1745
1746
1747SysLogHandler
1748^^^^^^^^^^^^^
1749
1750The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
1751supports sending logging messages to a remote or local Unix syslog.
1752
1753
1754.. class:: SysLogHandler([address[, facility]])
1755
1756 Returns a new instance of the :class:`SysLogHandler` class intended to
1757 communicate with a remote Unix machine whose address is given by *address* in
1758 the form of a ``(host, port)`` tuple. If *address* is not specified,
1759 ``('localhost', 514)`` is used. The address is used to open a UDP socket. An
1760 alternative to providing a ``(host, port)`` tuple is providing an address as a
1761 string, for example "/dev/log". In this case, a Unix domain socket is used to
1762 send the message to the syslog. If *facility* is not specified,
1763 :const:`LOG_USER` is used.
1764
1765
1766.. method:: SysLogHandler.close()
1767
1768 Closes the socket to the remote host.
1769
1770
1771.. method:: SysLogHandler.emit(record)
1772
1773 The record is formatted, and then sent to the syslog server. If exception
1774 information is present, it is *not* sent to the server.
1775
1776
1777.. method:: SysLogHandler.encodePriority(facility, priority)
1778
1779 Encodes the facility and priority into an integer. You can pass in strings or
1780 integers - if strings are passed, internal mapping dictionaries are used to
1781 convert them to integers.
1782
1783
1784NTEventLogHandler
1785^^^^^^^^^^^^^^^^^
1786
1787The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
1788module, supports sending logging messages to a local Windows NT, Windows 2000 or
1789Windows XP event log. Before you can use it, you need Mark Hammond's Win32
1790extensions for Python installed.
1791
1792
1793.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
1794
1795 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
1796 used to define the application name as it appears in the event log. An
1797 appropriate registry entry is created using this name. The *dllname* should give
1798 the fully qualified pathname of a .dll or .exe which contains message
1799 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
1800 - this is installed with the Win32 extensions and contains some basic
1801 placeholder message definitions. Note that use of these placeholders will make
1802 your event logs big, as the entire message source is held in the log. If you
1803 want slimmer logs, you have to pass in the name of your own .dll or .exe which
1804 contains the message definitions you want to use in the event log). The
1805 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
1806 defaults to ``'Application'``.
1807
1808
1809.. method:: NTEventLogHandler.close()
1810
1811 At this point, you can remove the application name from the registry as a source
1812 of event log entries. However, if you do this, you will not be able to see the
1813 events as you intended in the Event Log Viewer - it needs to be able to access
1814 the registry to get the .dll name. The current version does not do this (in fact
1815 it doesn't do anything).
1816
1817
1818.. method:: NTEventLogHandler.emit(record)
1819
1820 Determines the message ID, event category and event type, and then logs the
1821 message in the NT event log.
1822
1823
1824.. method:: NTEventLogHandler.getEventCategory(record)
1825
1826 Returns the event category for the record. Override this if you want to specify
1827 your own categories. This version returns 0.
1828
1829
1830.. method:: NTEventLogHandler.getEventType(record)
1831
1832 Returns the event type for the record. Override this if you want to specify your
1833 own types. This version does a mapping using the handler's typemap attribute,
1834 which is set up in :meth:`__init__` to a dictionary which contains mappings for
1835 :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and
1836 :const:`CRITICAL`. If you are using your own levels, you will either need to
1837 override this method or place a suitable dictionary in the handler's *typemap*
1838 attribute.
1839
1840
1841.. method:: NTEventLogHandler.getMessageID(record)
1842
1843 Returns the message ID for the record. If you are using your own messages, you
1844 could do this by having the *msg* passed to the logger being an ID rather than a
1845 format string. Then, in here, you could use a dictionary lookup to get the
1846 message ID. This version returns 1, which is the base message ID in
1847 :file:`win32service.pyd`.
1848
1849
1850SMTPHandler
1851^^^^^^^^^^^
1852
1853The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
1854supports sending logging messages to an email address via SMTP.
1855
1856
1857.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
1858
1859 Returns a new instance of the :class:`SMTPHandler` class. The instance is
1860 initialized with the from and to addresses and subject line of the email. The
1861 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
1862 the (host, port) tuple format for the *mailhost* argument. If you use a string,
1863 the standard SMTP port is used. If your SMTP server requires authentication, you
1864 can specify a (username, password) tuple for the *credentials* argument.
1865
Georg Brandl116aa622007-08-15 14:28:22 +00001866
1867.. method:: SMTPHandler.emit(record)
1868
1869 Formats the record and sends it to the specified addressees.
1870
1871
1872.. method:: SMTPHandler.getSubject(record)
1873
1874 If you want to specify a subject line which is record-dependent, override this
1875 method.
1876
1877
1878MemoryHandler
1879^^^^^^^^^^^^^
1880
1881The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
1882supports buffering of logging records in memory, periodically flushing them to a
1883:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
1884event of a certain severity or greater is seen.
1885
1886:class:`MemoryHandler` is a subclass of the more general
1887:class:`BufferingHandler`, which is an abstract class. This buffers logging
1888records in memory. Whenever each record is added to the buffer, a check is made
1889by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
1890should, then :meth:`flush` is expected to do the needful.
1891
1892
1893.. class:: BufferingHandler(capacity)
1894
1895 Initializes the handler with a buffer of the specified capacity.
1896
1897
1898.. method:: BufferingHandler.emit(record)
1899
1900 Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls
1901 :meth:`flush` to process the buffer.
1902
1903
1904.. method:: BufferingHandler.flush()
1905
1906 You can override this to implement custom flushing behavior. This version just
1907 zaps the buffer to empty.
1908
1909
1910.. method:: BufferingHandler.shouldFlush(record)
1911
1912 Returns true if the buffer is up to capacity. This method can be overridden to
1913 implement custom flushing strategies.
1914
1915
1916.. class:: MemoryHandler(capacity[, flushLevel [, target]])
1917
1918 Returns a new instance of the :class:`MemoryHandler` class. The instance is
1919 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
1920 :const:`ERROR` is used. If no *target* is specified, the target will need to be
1921 set using :meth:`setTarget` before this handler does anything useful.
1922
1923
1924.. method:: MemoryHandler.close()
1925
1926 Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer.
1927
1928
1929.. method:: MemoryHandler.flush()
1930
1931 For a :class:`MemoryHandler`, flushing means just sending the buffered records
1932 to the target, if there is one. Override if you want different behavior.
1933
1934
1935.. method:: MemoryHandler.setTarget(target)
1936
1937 Sets the target handler for this handler.
1938
1939
1940.. method:: MemoryHandler.shouldFlush(record)
1941
1942 Checks for buffer full or a record at the *flushLevel* or higher.
1943
1944
1945HTTPHandler
1946^^^^^^^^^^^
1947
1948The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
1949supports sending logging messages to a Web server, using either ``GET`` or
1950``POST`` semantics.
1951
1952
1953.. class:: HTTPHandler(host, url[, method])
1954
1955 Returns a new instance of the :class:`HTTPHandler` class. The instance is
1956 initialized with a host address, url and HTTP method. The *host* can be of the
1957 form ``host:port``, should you need to use a specific port number. If no
1958 *method* is specified, ``GET`` is used.
1959
1960
1961.. method:: HTTPHandler.emit(record)
1962
1963 Sends the record to the Web server as an URL-encoded dictionary.
1964
1965
Christian Heimes8b0facf2007-12-04 19:30:01 +00001966.. _formatter-objects:
1967
Georg Brandl116aa622007-08-15 14:28:22 +00001968Formatter Objects
1969-----------------
1970
1971:class:`Formatter`\ s have the following attributes and methods. They are
1972responsible for converting a :class:`LogRecord` to (usually) a string which can
1973be interpreted by either a human or an external system. The base
1974:class:`Formatter` allows a formatting string to be specified. If none is
1975supplied, the default value of ``'%(message)s'`` is used.
1976
1977A Formatter can be initialized with a format string which makes use of knowledge
1978of the :class:`LogRecord` attributes - such as the default value mentioned above
1979making use of the fact that the user's message and arguments are pre-formatted
1980into a :class:`LogRecord`'s *message* attribute. This format string contains
Georg Brandl4b491312007-08-31 09:22:56 +00001981standard python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00001982for more information on string formatting.
1983
1984Currently, the useful mapping keys in a :class:`LogRecord` are:
1985
1986+-------------------------+-----------------------------------------------+
1987| Format | Description |
1988+=========================+===============================================+
1989| ``%(name)s`` | Name of the logger (logging channel). |
1990+-------------------------+-----------------------------------------------+
1991| ``%(levelno)s`` | Numeric logging level for the message |
1992| | (:const:`DEBUG`, :const:`INFO`, |
1993| | :const:`WARNING`, :const:`ERROR`, |
1994| | :const:`CRITICAL`). |
1995+-------------------------+-----------------------------------------------+
1996| ``%(levelname)s`` | Text logging level for the message |
1997| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1998| | ``'ERROR'``, ``'CRITICAL'``). |
1999+-------------------------+-----------------------------------------------+
2000| ``%(pathname)s`` | Full pathname of the source file where the |
2001| | logging call was issued (if available). |
2002+-------------------------+-----------------------------------------------+
2003| ``%(filename)s`` | Filename portion of pathname. |
2004+-------------------------+-----------------------------------------------+
2005| ``%(module)s`` | Module (name portion of filename). |
2006+-------------------------+-----------------------------------------------+
2007| ``%(funcName)s`` | Name of function containing the logging call. |
2008+-------------------------+-----------------------------------------------+
2009| ``%(lineno)d`` | Source line number where the logging call was |
2010| | issued (if available). |
2011+-------------------------+-----------------------------------------------+
2012| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2013| | (as returned by :func:`time.time`). |
2014+-------------------------+-----------------------------------------------+
2015| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2016| | created, relative to the time the logging |
2017| | module was loaded. |
2018+-------------------------+-----------------------------------------------+
2019| ``%(asctime)s`` | Human-readable time when the |
2020| | :class:`LogRecord` was created. By default |
2021| | this is of the form "2003-07-08 16:49:45,896" |
2022| | (the numbers after the comma are millisecond |
2023| | portion of the time). |
2024+-------------------------+-----------------------------------------------+
2025| ``%(msecs)d`` | Millisecond portion of the time when the |
2026| | :class:`LogRecord` was created. |
2027+-------------------------+-----------------------------------------------+
2028| ``%(thread)d`` | Thread ID (if available). |
2029+-------------------------+-----------------------------------------------+
2030| ``%(threadName)s`` | Thread name (if available). |
2031+-------------------------+-----------------------------------------------+
2032| ``%(process)d`` | Process ID (if available). |
2033+-------------------------+-----------------------------------------------+
2034| ``%(message)s`` | The logged message, computed as ``msg % |
2035| | args``. |
2036+-------------------------+-----------------------------------------------+
2037
Georg Brandl116aa622007-08-15 14:28:22 +00002038
2039.. class:: Formatter([fmt[, datefmt]])
2040
2041 Returns a new instance of the :class:`Formatter` class. The instance is
2042 initialized with a format string for the message as a whole, as well as a format
2043 string for the date/time portion of a message. If no *fmt* is specified,
2044 ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
2045 is used.
2046
2047
2048.. method:: Formatter.format(record)
2049
2050 The record's attribute dictionary is used as the operand to a string formatting
2051 operation. Returns the resulting string. Before formatting the dictionary, a
2052 couple of preparatory steps are carried out. The *message* attribute of the
2053 record is computed using *msg* % *args*. If the formatting string contains
2054 ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there
2055 is exception information, it is formatted using :meth:`formatException` and
2056 appended to the message.
2057
2058
2059.. method:: Formatter.formatTime(record[, datefmt])
2060
2061 This method should be called from :meth:`format` by a formatter which wants to
2062 make use of a formatted time. This method can be overridden in formatters to
2063 provide for any specific requirement, but the basic behavior is as follows: if
2064 *datefmt* (a string) is specified, it is used with :func:`time.strftime` to
2065 format the creation time of the record. Otherwise, the ISO8601 format is used.
2066 The resulting string is returned.
2067
2068
2069.. method:: Formatter.formatException(exc_info)
2070
2071 Formats the specified exception information (a standard exception tuple as
2072 returned by :func:`sys.exc_info`) as a string. This default implementation just
2073 uses :func:`traceback.print_exception`. The resulting string is returned.
2074
2075
2076Filter Objects
2077--------------
2078
2079:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
2080more sophisticated filtering than is provided by levels. The base filter class
2081only allows events which are below a certain point in the logger hierarchy. For
2082example, a filter initialized with "A.B" will allow events logged by loggers
2083"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2084initialized with the empty string, all events are passed.
2085
2086
2087.. class:: Filter([name])
2088
2089 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2090 names a logger which, together with its children, will have its events allowed
2091 through the filter. If no name is specified, allows every event.
2092
2093
2094.. method:: Filter.filter(record)
2095
2096 Is the specified record to be logged? Returns zero for no, nonzero for yes. If
2097 deemed appropriate, the record may be modified in-place by this method.
2098
2099
2100LogRecord Objects
2101-----------------
2102
2103:class:`LogRecord` instances are created every time something is logged. They
2104contain all the information pertinent to the event being logged. The main
2105information passed in is in msg and args, which are combined using msg % args to
2106create the message field of the record. The record also includes information
2107such as when the record was created, the source line where the logging call was
2108made, and any exception information to be logged.
2109
2110
2111.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
2112
2113 Returns an instance of :class:`LogRecord` initialized with interesting
2114 information. The *name* is the logger name; *lvl* is the numeric level;
2115 *pathname* is the absolute pathname of the source file in which the logging
2116 call was made; *lineno* is the line number in that file where the logging
2117 call is found; *msg* is the user-supplied message (a format string); *args*
2118 is the tuple which, together with *msg*, makes up the user message; and
2119 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2120 (or :const:`None`, if no exception information is available). The *func* is
2121 the name of the function from which the logging call was made. If not
2122 specified, it defaults to ``None``.
2123
Georg Brandl116aa622007-08-15 14:28:22 +00002124
2125.. method:: LogRecord.getMessage()
2126
2127 Returns the message for this :class:`LogRecord` instance after merging any
2128 user-supplied arguments with the message.
2129
Christian Heimes04c420f2008-01-18 18:40:46 +00002130LoggerAdapter Objects
2131---------------------
2132
2133.. versionadded:: 2.6
2134
2135:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00002136information into logging calls. For a usage example , see the section on
2137`adding contextual information to your logging output`__.
2138
2139__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00002140
2141.. class:: LoggerAdapter(logger, extra)
2142
2143 Returns an instance of :class:`LoggerAdapter` initialized with an
2144 underlying :class:`Logger` instance and a dict-like object.
2145
2146.. method:: LoggerAdapter.process(msg, kwargs)
2147
2148 Modifies the message and/or keyword arguments passed to a logging call in
2149 order to insert contextual information. This implementation takes the
2150 object passed as *extra* to the constructor and adds it to *kwargs* using
2151 key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2152 (possibly modified) versions of the arguments passed in.
2153
2154In addition to the above, :class:`LoggerAdapter` supports all the logging
2155methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2156:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2157methods have the same signatures as their counterparts in :class:`Logger`, so
2158you can use the two types of instances interchangeably.
2159
Georg Brandl116aa622007-08-15 14:28:22 +00002160
2161Thread Safety
2162-------------
2163
2164The logging module is intended to be thread-safe without any special work
2165needing to be done by its clients. It achieves this though using threading
2166locks; there is one lock to serialize access to the module's shared data, and
2167each handler also creates a lock to serialize access to its underlying I/O.
2168
2169
2170Configuration
2171-------------
2172
2173
2174.. _logging-config-api:
2175
2176Configuration functions
2177^^^^^^^^^^^^^^^^^^^^^^^
2178
Georg Brandl116aa622007-08-15 14:28:22 +00002179The following functions configure the logging module. They are located in the
2180:mod:`logging.config` module. Their use is optional --- you can configure the
2181logging module using these functions or by making calls to the main API (defined
2182in :mod:`logging` itself) and defining handlers which are declared either in
2183:mod:`logging` or :mod:`logging.handlers`.
2184
2185
2186.. function:: fileConfig(fname[, defaults])
2187
2188 Reads the logging configuration from a ConfigParser-format file named *fname*.
2189 This function can be called several times from an application, allowing an end
2190 user the ability to select from various pre-canned configurations (if the
2191 developer provides a mechanism to present the choices and load the chosen
2192 configuration). Defaults to be passed to ConfigParser can be specified in the
2193 *defaults* argument.
2194
2195
2196.. function:: listen([port])
2197
2198 Starts up a socket server on the specified port, and listens for new
2199 configurations. If no port is specified, the module's default
2200 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2201 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2202 :class:`Thread` instance on which you can call :meth:`start` to start the
2203 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00002204 call :func:`stopListening`.
2205
2206 To send a configuration to the socket, read in the configuration file and
2207 send it to the socket as a string of bytes preceded by a four-byte length
2208 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002209
2210
2211.. function:: stopListening()
2212
Christian Heimes8b0facf2007-12-04 19:30:01 +00002213 Stops the listening server which was created with a call to :func:`listen`.
2214 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00002215 :func:`listen`.
2216
2217
2218.. _logging-config-fileformat:
2219
2220Configuration file format
2221^^^^^^^^^^^^^^^^^^^^^^^^^
2222
Georg Brandl116aa622007-08-15 14:28:22 +00002223The configuration file format understood by :func:`fileConfig` is based on
2224ConfigParser functionality. The file must contain sections called ``[loggers]``,
2225``[handlers]`` and ``[formatters]`` which identify by name the entities of each
2226type which are defined in the file. For each such entity, there is a separate
2227section which identified how that entity is configured. Thus, for a logger named
2228``log01`` in the ``[loggers]`` section, the relevant configuration details are
2229held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
2230the ``[handlers]`` section will have its configuration held in a section called
2231``[handler_hand01]``, while a formatter called ``form01`` in the
2232``[formatters]`` section will have its configuration specified in a section
2233called ``[formatter_form01]``. The root logger configuration must be specified
2234in a section called ``[logger_root]``.
2235
2236Examples of these sections in the file are given below. ::
2237
2238 [loggers]
2239 keys=root,log02,log03,log04,log05,log06,log07
2240
2241 [handlers]
2242 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
2243
2244 [formatters]
2245 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
2246
2247The root logger must specify a level and a list of handlers. An example of a
2248root logger section is given below. ::
2249
2250 [logger_root]
2251 level=NOTSET
2252 handlers=hand01
2253
2254The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
2255``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
2256logged. Level values are :func:`eval`\ uated in the context of the ``logging``
2257package's namespace.
2258
2259The ``handlers`` entry is a comma-separated list of handler names, which must
2260appear in the ``[handlers]`` section. These names must appear in the
2261``[handlers]`` section and have corresponding sections in the configuration
2262file.
2263
2264For loggers other than the root logger, some additional information is required.
2265This is illustrated by the following example. ::
2266
2267 [logger_parser]
2268 level=DEBUG
2269 handlers=hand01
2270 propagate=1
2271 qualname=compiler.parser
2272
2273The ``level`` and ``handlers`` entries are interpreted as for the root logger,
2274except that if a non-root logger's level is specified as ``NOTSET``, the system
2275consults loggers higher up the hierarchy to determine the effective level of the
2276logger. The ``propagate`` entry is set to 1 to indicate that messages must
2277propagate to handlers higher up the logger hierarchy from this logger, or 0 to
2278indicate that messages are **not** propagated to handlers up the hierarchy. The
2279``qualname`` entry is the hierarchical channel name of the logger, that is to
2280say the name used by the application to get the logger.
2281
2282Sections which specify handler configuration are exemplified by the following.
2283::
2284
2285 [handler_hand01]
2286 class=StreamHandler
2287 level=NOTSET
2288 formatter=form01
2289 args=(sys.stdout,)
2290
2291The ``class`` entry indicates the handler's class (as determined by :func:`eval`
2292in the ``logging`` package's namespace). The ``level`` is interpreted as for
2293loggers, and ``NOTSET`` is taken to mean "log everything".
2294
2295The ``formatter`` entry indicates the key name of the formatter for this
2296handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
2297If a name is specified, it must appear in the ``[formatters]`` section and have
2298a corresponding section in the configuration file.
2299
2300The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
2301package's namespace, is the list of arguments to the constructor for the handler
2302class. Refer to the constructors for the relevant handlers, or to the examples
2303below, to see how typical entries are constructed. ::
2304
2305 [handler_hand02]
2306 class=FileHandler
2307 level=DEBUG
2308 formatter=form02
2309 args=('python.log', 'w')
2310
2311 [handler_hand03]
2312 class=handlers.SocketHandler
2313 level=INFO
2314 formatter=form03
2315 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
2316
2317 [handler_hand04]
2318 class=handlers.DatagramHandler
2319 level=WARN
2320 formatter=form04
2321 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
2322
2323 [handler_hand05]
2324 class=handlers.SysLogHandler
2325 level=ERROR
2326 formatter=form05
2327 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
2328
2329 [handler_hand06]
2330 class=handlers.NTEventLogHandler
2331 level=CRITICAL
2332 formatter=form06
2333 args=('Python Application', '', 'Application')
2334
2335 [handler_hand07]
2336 class=handlers.SMTPHandler
2337 level=WARN
2338 formatter=form07
2339 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
2340
2341 [handler_hand08]
2342 class=handlers.MemoryHandler
2343 level=NOTSET
2344 formatter=form08
2345 target=
2346 args=(10, ERROR)
2347
2348 [handler_hand09]
2349 class=handlers.HTTPHandler
2350 level=NOTSET
2351 formatter=form09
2352 args=('localhost:9022', '/log', 'GET')
2353
2354Sections which specify formatter configuration are typified by the following. ::
2355
2356 [formatter_form01]
2357 format=F1 %(asctime)s %(levelname)s %(message)s
2358 datefmt=
2359 class=logging.Formatter
2360
2361The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00002362the :func:`strftime`\ -compatible date/time format string. If empty, the
2363package substitutes ISO8601 format date/times, which is almost equivalent to
2364specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
2365also specifies milliseconds, which are appended to the result of using the above
2366format string, with a comma separator. An example time in ISO8601 format is
2367``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00002368
2369The ``class`` entry is optional. It indicates the name of the formatter's class
2370(as a dotted module and class name.) This option is useful for instantiating a
2371:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
2372exception tracebacks in an expanded or condensed format.
2373
Christian Heimes8b0facf2007-12-04 19:30:01 +00002374
2375Configuration server example
2376^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2377
2378Here is an example of a module using the logging configuration server::
2379
2380 import logging
2381 import logging.config
2382 import time
2383 import os
2384
2385 # read initial config file
2386 logging.config.fileConfig("logging.conf")
2387
2388 # create and start listener on port 9999
2389 t = logging.config.listen(9999)
2390 t.start()
2391
2392 logger = logging.getLogger("simpleExample")
2393
2394 try:
2395 # loop through logging calls to see the difference
2396 # new configurations make, until Ctrl+C is pressed
2397 while True:
2398 logger.debug("debug message")
2399 logger.info("info message")
2400 logger.warn("warn message")
2401 logger.error("error message")
2402 logger.critical("critical message")
2403 time.sleep(5)
2404 except KeyboardInterrupt:
2405 # cleanup
2406 logging.config.stopListening()
2407 t.join()
2408
2409And here is a script that takes a filename and sends that file to the server,
2410properly preceded with the binary-encoded length, as the new logging
2411configuration::
2412
2413 #!/usr/bin/env python
2414 import socket, sys, struct
2415
2416 data_to_send = open(sys.argv[1], "r").read()
2417
2418 HOST = 'localhost'
2419 PORT = 9999
2420 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2421 print "connecting..."
2422 s.connect((HOST, PORT))
2423 print "sending config..."
2424 s.send(struct.pack(">L", len(data_to_send)))
2425 s.send(data_to_send)
2426 s.close()
2427 print "complete"
2428
2429
2430More examples
2431-------------
2432
2433Multiple handlers and formatters
2434^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2435
2436Loggers are plain Python objects. The :func:`addHandler` method has no minimum
2437or maximum quota for the number of handlers you may add. Sometimes it will be
2438beneficial for an application to log all messages of all severities to a text
2439file while simultaneously logging errors or above to the console. To set this
2440up, simply configure the appropriate handlers. The logging calls in the
2441application code will remain unchanged. Here is a slight modification to the
2442previous simple module-based configuration example::
2443
2444 import logging
2445
2446 logger = logging.getLogger("simple_example")
2447 logger.setLevel(logging.DEBUG)
2448 # create file handler which logs even debug messages
2449 fh = logging.FileHandler("spam.log")
2450 fh.setLevel(logging.DEBUG)
2451 # create console handler with a higher log level
2452 ch = logging.StreamHandler()
2453 ch.setLevel(logging.ERROR)
2454 # create formatter and add it to the handlers
2455 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
2456 ch.setFormatter(formatter)
2457 fh.setFormatter(formatter)
2458 # add the handlers to logger
2459 logger.addHandler(ch)
2460 logger.addHandler(fh)
2461
2462 # "application" code
2463 logger.debug("debug message")
2464 logger.info("info message")
2465 logger.warn("warn message")
2466 logger.error("error message")
2467 logger.critical("critical message")
2468
2469Notice that the "application" code does not care about multiple handlers. All
2470that changed was the addition and configuration of a new handler named *fh*.
2471
2472The ability to create new handlers with higher- or lower-severity filters can be
2473very helpful when writing and testing an application. Instead of using many
2474``print`` statements for debugging, use ``logger.debug``: Unlike the print
2475statements, which you will have to delete or comment out later, the logger.debug
2476statements can remain intact in the source code and remain dormant until you
2477need them again. At that time, the only change that needs to happen is to
2478modify the severity level of the logger and/or handler to debug.
2479
2480
2481Using logging in multiple modules
2482^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2483
2484It was mentioned above that multiple calls to
2485``logging.getLogger('someLogger')`` return a reference to the same logger
2486object. This is true not only within the same module, but also across modules
2487as long as it is in the same Python interpreter process. It is true for
2488references to the same object; additionally, application code can define and
2489configure a parent logger in one module and create (but not configure) a child
2490logger in a separate module, and all logger calls to the child will pass up to
2491the parent. Here is a main module::
2492
2493 import logging
2494 import auxiliary_module
2495
2496 # create logger with "spam_application"
2497 logger = logging.getLogger("spam_application")
2498 logger.setLevel(logging.DEBUG)
2499 # create file handler which logs even debug messages
2500 fh = logging.FileHandler("spam.log")
2501 fh.setLevel(logging.DEBUG)
2502 # create console handler with a higher log level
2503 ch = logging.StreamHandler()
2504 ch.setLevel(logging.ERROR)
2505 # create formatter and add it to the handlers
2506 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
2507 fh.setFormatter(formatter)
2508 ch.setFormatter(formatter)
2509 # add the handlers to the logger
2510 logger.addHandler(fh)
2511 logger.addHandler(ch)
2512
2513 logger.info("creating an instance of auxiliary_module.Auxiliary")
2514 a = auxiliary_module.Auxiliary()
2515 logger.info("created an instance of auxiliary_module.Auxiliary")
2516 logger.info("calling auxiliary_module.Auxiliary.do_something")
2517 a.do_something()
2518 logger.info("finished auxiliary_module.Auxiliary.do_something")
2519 logger.info("calling auxiliary_module.some_function()")
2520 auxiliary_module.some_function()
2521 logger.info("done with auxiliary_module.some_function()")
2522
2523Here is the auxiliary module::
2524
2525 import logging
2526
2527 # create logger
2528 module_logger = logging.getLogger("spam_application.auxiliary")
2529
2530 class Auxiliary:
2531 def __init__(self):
2532 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
2533 self.logger.info("creating an instance of Auxiliary")
2534 def do_something(self):
2535 self.logger.info("doing something")
2536 a = 1 + 1
2537 self.logger.info("done doing something")
2538
2539 def some_function():
2540 module_logger.info("received a call to \"some_function\"")
2541
2542The output looks like this::
2543
Christian Heimes043d6f62008-01-07 17:19:16 +00002544 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002545 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00002546 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002547 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00002548 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002549 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00002550 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002551 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00002552 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002553 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00002554 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002555 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00002556 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002557 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00002558 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002559 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00002560 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002561 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00002562 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00002563 done with auxiliary_module.some_function()
2564