blob: feb3e874676359d5ca19eaf37e91c0c2e1a591d1 [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
Christian Heimesc3f30c42008-02-22 16:37:40 +000044mechanisms are all supported by the standard module. You can also create your
Christian Heimes8b0facf2007-12-04 19:30:01 +000045own 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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056default handler so that debug messages are written to a file (in the example,
57we assume that you have the appropriate permissions to create a file called
58*example.log* in the current directory)::
Christian Heimes8b0facf2007-12-04 19:30:01 +000059
60 import logging
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000061 LOG_FILENAME = 'example.log'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Christian Heimes8b0facf2007-12-04 19:30:01 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smith5c01a8d2009-06-04 18:20:51 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Christian Heimes8b0facf2007-12-04 19:30:01 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000080 LOG_FILENAME = 'logging_rotatingfile_example.out'
Christian Heimes8b0facf2007-12-04 19:30:01 +000081
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
Georg Brandlf6945182008-02-01 11:56:49 +0000100 print(filename)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000105 logging_rotatingfile_example.out
106 logging_rotatingfile_example.out.1
107 logging_rotatingfile_example.out.2
108 logging_rotatingfile_example.out.3
109 logging_rotatingfile_example.out.4
110 logging_rotatingfile_example.out.5
Christian Heimes8b0facf2007-12-04 19:30:01 +0000111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112The most current file is always :file:`logging_rotatingfile_example.out`,
Christian Heimes8b0facf2007-12-04 19:30:01 +0000113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smith5c01a8d2009-06-04 18:20:51 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipb6d065f2009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Christian Heimesdcca98d2008-02-25 13:19:43 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000249name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000270requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
294defines the interface that all handlers should have and establishes some
295default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000303instantiate formatter classes, although you could likely subclass the formatter
304if your application needs special behavior. The constructor takes two optional
305arguments: a message format string and a date format string. If there is no
306message format string, the default is to use the raw message. If there is no
307date format string, the default date format is::
308
309 %Y-%m-%d %H:%M:%S
310
311with the milliseconds tacked on at the end.
312
313The message format string uses ``%(<dictionary key>)s`` styled string
314substitution; the possible keys are documented in :ref:`formatter-objects`.
315
316The following message format string will log the time in a human-readable
317format, the severity of the message, and the contents of the message, in that
318order::
319
320 "%(asctime)s - %(levelname)s - %(message)s"
321
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000322Formatters use a user-configurable function to convert the creation time of a
323record to a tuple. By default, :func:`time.localtime` is used; to change this
324for a particular formatter instance, set the ``converter`` attribute of the
325instance to a function with the same signature as :func:`time.localtime` or
326:func:`time.gmtime`. To change it for all formatters, for example if you want
327all logging times to be shown in GMT, set the ``converter`` attribute in the
328Formatter class (to ``time.gmtime`` for GMT display).
329
Christian Heimes8b0facf2007-12-04 19:30:01 +0000330
331Configuring Logging
332^^^^^^^^^^^^^^^^^^^
333
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000334Programmers can configure logging in three ways:
335
3361. Creating loggers, handlers, and formatters explicitly using Python
337 code that calls the configuration methods listed above.
3382. Creating a logging config file and reading it using the :func:`fileConfig`
339 function.
3403. Creating a dictionary of configuration information and passing it
341 to the :func:`dictConfig` function.
342
343The following example configures a very simple logger, a console
344handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000345
346 import logging
347
348 # create logger
349 logger = logging.getLogger("simple_example")
350 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000351
Christian Heimes8b0facf2007-12-04 19:30:01 +0000352 # create console handler and set level to debug
353 ch = logging.StreamHandler()
354 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000355
Christian Heimes8b0facf2007-12-04 19:30:01 +0000356 # create formatter
357 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000358
Christian Heimes8b0facf2007-12-04 19:30:01 +0000359 # add formatter to ch
360 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000361
Christian Heimes8b0facf2007-12-04 19:30:01 +0000362 # add ch to logger
363 logger.addHandler(ch)
364
365 # "application" code
366 logger.debug("debug message")
367 logger.info("info message")
368 logger.warn("warn message")
369 logger.error("error message")
370 logger.critical("critical message")
371
372Running this module from the command line produces the following output::
373
374 $ python simple_logging_module.py
375 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
376 2005-03-19 15:10:26,620 - simple_example - INFO - info message
377 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
378 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
379 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
380
381The following Python module creates a logger, handler, and formatter nearly
382identical to those in the example listed above, with the only difference being
383the names of the objects::
384
385 import logging
386 import logging.config
387
388 logging.config.fileConfig("logging.conf")
389
390 # create logger
391 logger = logging.getLogger("simpleExample")
392
393 # "application" code
394 logger.debug("debug message")
395 logger.info("info message")
396 logger.warn("warn message")
397 logger.error("error message")
398 logger.critical("critical message")
399
400Here is the logging.conf file::
401
402 [loggers]
403 keys=root,simpleExample
404
405 [handlers]
406 keys=consoleHandler
407
408 [formatters]
409 keys=simpleFormatter
410
411 [logger_root]
412 level=DEBUG
413 handlers=consoleHandler
414
415 [logger_simpleExample]
416 level=DEBUG
417 handlers=consoleHandler
418 qualname=simpleExample
419 propagate=0
420
421 [handler_consoleHandler]
422 class=StreamHandler
423 level=DEBUG
424 formatter=simpleFormatter
425 args=(sys.stdout,)
426
427 [formatter_simpleFormatter]
428 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
429 datefmt=
430
431The output is nearly identical to that of the non-config-file-based example::
432
433 $ python simple_logging_config.py
434 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
435 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
436 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
437 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
438 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
439
440You can see that the config file approach has a few advantages over the Python
441code approach, mainly separation of configuration and code and the ability of
442noncoders to easily modify the logging properties.
443
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000444Note that the class names referenced in config files need to be either relative
445to the logging module, or absolute values which can be resolved using normal
446import mechanisms. Thus, you could use either `handlers.WatchedFileHandler`
447(relative to the logging module) or `mypackage.mymodule.MyHandler` (for a
448class defined in package `mypackage` and module `mymodule`, where `mypackage`
449is available on the Python import path).
450
Benjamin Peterson56894b52010-06-28 00:16:12 +0000451In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000452dictionaries to hold configuration information. This provides a superset of the
453functionality of the config-file-based approach outlined above, and is the
454recommended configuration method for new applications and deployments. Because
455a Python dictionary is used to hold configuration information, and since you
456can populate that dictionary using different means, you have more options for
457configuration. For example, you can use a configuration file in JSON format,
458or, if you have access to YAML processing functionality, a file in YAML
459format, to populate the configuration dictionary. Or, of course, you can
460construct the dictionary in Python code, receive it in pickled form over a
461socket, or use whatever approach makes sense for your application.
462
463Here's an example of the same configuration as above, in YAML format for
464the new dictionary-based approach::
465
466 version: 1
467 formatters:
468 simple:
469 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
470 handlers:
471 console:
472 class: logging.StreamHandler
473 level: DEBUG
474 formatter: simple
475 stream: ext://sys.stdout
476 loggers:
477 simpleExample:
478 level: DEBUG
479 handlers: [console]
480 propagate: no
481 root:
482 level: DEBUG
483 handlers: [console]
484
485For more information about logging using a dictionary, see
486:ref:`logging-config-api`.
487
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000488.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000489
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000490Configuring Logging for a Library
491^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
492
493When developing a library which uses logging, some consideration needs to be
494given to its configuration. If the using application does not use logging, and
495library code makes logging calls, then a one-off message "No handlers could be
496found for logger X.Y.Z" is printed to the console. This message is intended
497to catch mistakes in logging configuration, but will confuse an application
498developer who is not aware of logging by the library.
499
500In addition to documenting how a library uses logging, a good way to configure
501library logging so that it does not cause a spurious message is to add a
502handler which does nothing. This avoids the message being printed, since a
503handler will be found: it just doesn't produce any output. If the library user
504configures logging for application use, presumably that configuration will add
505some handlers, and if levels are suitably configured then logging calls made
506in library code will send output to those handlers, as normal.
507
508A do-nothing handler can be simply defined as follows::
509
510 import logging
511
512 class NullHandler(logging.Handler):
513 def emit(self, record):
514 pass
515
516An instance of this handler should be added to the top-level logger of the
517logging namespace used by the library. If all logging by a library *foo* is
518done using loggers with names matching "foo.x.y", then the code::
519
520 import logging
521
522 h = NullHandler()
523 logging.getLogger("foo").addHandler(h)
524
525should have the desired effect. If an organisation produces a number of
526libraries, then the logger name specified can be "orgname.foo" rather than
527just "foo".
528
Georg Brandlf9734072008-12-07 15:30:06 +0000529.. versionadded:: 3.1
Vinay Sajip4039aff2010-09-11 10:25:28 +0000530
Georg Brandl67b21b72010-08-17 15:07:14 +0000531 The :class:`NullHandler` class was not present in previous versions, but is
532 now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000533
534
Christian Heimes8b0facf2007-12-04 19:30:01 +0000535
536Logging Levels
537--------------
538
Georg Brandl116aa622007-08-15 14:28:22 +0000539The numeric values of logging levels are given in the following table. These are
540primarily of interest if you want to define your own levels, and need them to
541have specific values relative to the predefined levels. If you define a level
542with the same numeric value, it overwrites the predefined value; the predefined
543name is lost.
544
545+--------------+---------------+
546| Level | Numeric value |
547+==============+===============+
548| ``CRITICAL`` | 50 |
549+--------------+---------------+
550| ``ERROR`` | 40 |
551+--------------+---------------+
552| ``WARNING`` | 30 |
553+--------------+---------------+
554| ``INFO`` | 20 |
555+--------------+---------------+
556| ``DEBUG`` | 10 |
557+--------------+---------------+
558| ``NOTSET`` | 0 |
559+--------------+---------------+
560
561Levels can also be associated with loggers, being set either by the developer or
562through loading a saved logging configuration. When a logging method is called
563on a logger, the logger compares its own level with the level associated with
564the method call. If the logger's level is higher than the method call's, no
565logging message is actually generated. This is the basic mechanism controlling
566the verbosity of logging output.
567
568Logging messages are encoded as instances of the :class:`LogRecord` class. When
569a logger decides to actually log an event, a :class:`LogRecord` instance is
570created from the logging message.
571
572Logging messages are subjected to a dispatch mechanism through the use of
573:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
574class. Handlers are responsible for ensuring that a logged message (in the form
575of a :class:`LogRecord`) ends up in a particular location (or set of locations)
576which is useful for the target audience for that message (such as end users,
577support desk staff, system administrators, developers). Handlers are passed
578:class:`LogRecord` instances intended for particular destinations. Each logger
579can have zero, one or more handlers associated with it (via the
580:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
581directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000582of the logger* are called to dispatch the message (unless the *propagate* flag
583for a logger is set to a false value, at which point the passing to ancestor
584handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000585
586Just as for loggers, handlers can have levels associated with them. A handler's
587level acts as a filter in the same way as a logger's level does. If a handler
588decides to actually dispatch an event, the :meth:`emit` method is used to send
589the message to its destination. Most user-defined subclasses of :class:`Handler`
590will need to override this :meth:`emit`.
591
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000592.. _custom-levels:
593
594Custom Levels
595^^^^^^^^^^^^^
596
597Defining your own levels is possible, but should not be necessary, as the
598existing levels have been chosen on the basis of practical experience.
599However, if you are convinced that you need custom levels, great care should
600be exercised when doing this, and it is possibly *a very bad idea to define
601custom levels if you are developing a library*. That's because if multiple
602library authors all define their own custom levels, there is a chance that
603the logging output from such multiple libraries used together will be
604difficult for the using developer to control and/or interpret, because a
605given numeric value might mean different things for different libraries.
606
607
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000608Useful Handlers
609---------------
610
Georg Brandl116aa622007-08-15 14:28:22 +0000611In addition to the base :class:`Handler` class, many useful subclasses are
612provided:
613
Vinay Sajip121a1c42010-09-08 10:46:15 +0000614#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000615 objects).
616
Vinay Sajip121a1c42010-09-08 10:46:15 +0000617#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000619.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000620
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000621#. :class:`BaseRotatingHandler` is the base class for handlers that
622 rotate log files at a certain point. It is not meant to be instantiated
623 directly. Instead, use :class:`RotatingFileHandler` or
624 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000625
Vinay Sajip121a1c42010-09-08 10:46:15 +0000626#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000627 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000628
Vinay Sajip121a1c42010-09-08 10:46:15 +0000629#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000630 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000631
Vinay Sajip121a1c42010-09-08 10:46:15 +0000632#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000633 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
Vinay Sajip121a1c42010-09-08 10:46:15 +0000635#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000636 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000637
Vinay Sajip121a1c42010-09-08 10:46:15 +0000638#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000639 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Vinay Sajip121a1c42010-09-08 10:46:15 +0000641#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000642 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Vinay Sajip121a1c42010-09-08 10:46:15 +0000644#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000645 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Vinay Sajip121a1c42010-09-08 10:46:15 +0000647#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000648 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Vinay Sajip121a1c42010-09-08 10:46:15 +0000650#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000651 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000653#. :class:`WatchedFileHandler` instances watch the file they are
654 logging to. If the file changes, it is closed and reopened using the file
655 name. This handler is only useful on Unix-like systems; Windows does not
656 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000657
Vinay Sajip121a1c42010-09-08 10:46:15 +0000658#. :class:`QueueHandler` instances send messages to a queue, such as
659 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
660
Vinay Sajip30bf1222009-01-10 19:23:34 +0000661.. currentmodule:: logging
662
Georg Brandlf9734072008-12-07 15:30:06 +0000663#. :class:`NullHandler` instances do nothing with error messages. They are used
664 by library developers who want to use logging, but want to avoid the "No
665 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000666 the library user has not configured logging. See :ref:`library-config` for
667 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000668
669.. versionadded:: 3.1
670
671The :class:`NullHandler` class was not present in previous versions.
672
Vinay Sajip121a1c42010-09-08 10:46:15 +0000673.. versionadded:: 3.2
674
675The :class:`QueueHandler` class was not present in previous versions.
676
Vinay Sajipa17775f2008-12-30 07:32:59 +0000677The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
678classes are defined in the core logging package. The other handlers are
679defined in a sub- module, :mod:`logging.handlers`. (There is also another
680sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682Logged messages are formatted for presentation through instances of the
683:class:`Formatter` class. They are initialized with a format string suitable for
684use with the % operator and a dictionary.
685
686For formatting multiple messages in a batch, instances of
687:class:`BufferingFormatter` can be used. In addition to the format string (which
688is applied to each message in the batch), there is provision for header and
689trailer format strings.
690
691When filtering based on logger level and/or handler level is not enough,
692instances of :class:`Filter` can be added to both :class:`Logger` and
693:class:`Handler` instances (through their :meth:`addFilter` method). Before
694deciding to process a message further, both loggers and handlers consult all
695their filters for permission. If any filter returns a false value, the message
696is not processed further.
697
698The basic :class:`Filter` functionality allows filtering by specific logger
699name. If this feature is used, messages sent to the named logger and its
700children are allowed through the filter, and all others dropped.
701
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000702Module-Level Functions
703----------------------
704
Georg Brandl116aa622007-08-15 14:28:22 +0000705In addition to the classes described above, there are a number of module- level
706functions.
707
708
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000709.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000710
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000711 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000712 logger which is the root logger of the hierarchy. If specified, the name is
713 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
714 Choice of these names is entirely up to the developer who is using logging.
715
716 All calls to this function with a given name return the same logger instance.
717 This means that logger instances never need to be passed between different parts
718 of an application.
719
720
721.. function:: getLoggerClass()
722
723 Return either the standard :class:`Logger` class, or the last class passed to
724 :func:`setLoggerClass`. This function may be called from within a new class
725 definition, to ensure that installing a customised :class:`Logger` class will
726 not undo customisations already applied by other code. For example::
727
728 class MyLogger(logging.getLoggerClass()):
729 # ... override behaviour here
730
731
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000732.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
735 message format string, and the *args* are the arguments which are merged into
736 *msg* using the string formatting operator. (Note that this means that you can
737 use keywords in the format string, together with a single dictionary argument.)
738
739 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
740 which, if it does not evaluate as false, causes exception information to be
741 added to the logging message. If an exception tuple (in the format returned by
742 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
743 is called to get the exception information.
744
745 The other optional keyword argument is *extra* which can be used to pass a
746 dictionary which is used to populate the __dict__ of the LogRecord created for
747 the logging event with user-defined attributes. These custom attributes can then
748 be used as you like. For example, they could be incorporated into logged
749 messages. For example::
750
751 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
752 logging.basicConfig(format=FORMAT)
753 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
754 logging.warning("Protocol problem: %s", "connection reset", extra=d)
755
Vinay Sajip4039aff2010-09-11 10:25:28 +0000756 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000757
758 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
759
760 The keys in the dictionary passed in *extra* should not clash with the keys used
761 by the logging system. (See the :class:`Formatter` documentation for more
762 information on which keys are used by the logging system.)
763
764 If you choose to use these attributes in logged messages, you need to exercise
765 some care. In the above example, for instance, the :class:`Formatter` has been
766 set up with a format string which expects 'clientip' and 'user' in the attribute
767 dictionary of the LogRecord. If these are missing, the message will not be
768 logged because a string formatting exception will occur. So in this case, you
769 always need to pass the *extra* dictionary with these keys.
770
771 While this might be annoying, this feature is intended for use in specialized
772 circumstances, such as multi-threaded servers where the same code executes in
773 many contexts, and interesting conditions which arise are dependent on this
774 context (such as remote client IP address and authenticated user name, in the
775 above example). In such circumstances, it is likely that specialized
776 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
777
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000779.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781 Logs a message with level :const:`INFO` on the root logger. The arguments are
782 interpreted as for :func:`debug`.
783
784
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000785.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787 Logs a message with level :const:`WARNING` on the root logger. The arguments are
788 interpreted as for :func:`debug`.
789
790
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000791.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793 Logs a message with level :const:`ERROR` on the root logger. The arguments are
794 interpreted as for :func:`debug`.
795
796
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000797.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000798
799 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
800 are interpreted as for :func:`debug`.
801
802
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000803.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805 Logs a message with level :const:`ERROR` on the root logger. The arguments are
806 interpreted as for :func:`debug`. Exception info is added to the logging
807 message. This function should only be called from an exception handler.
808
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000809.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811 Logs a message with level *level* on the root logger. The other arguments are
812 interpreted as for :func:`debug`.
813
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000814 PLEASE NOTE: The above module-level functions which delegate to the root
815 logger should *not* be used in threads, in versions of Python earlier than
816 2.7.1 and 3.2, unless at least one handler has been added to the root
817 logger *before* the threads are started. These convenience functions call
818 :func:`basicConfig` to ensure that at least one handler is available; in
819 earlier versions of Python, this can (under rare circumstances) lead to
820 handlers being added multiple times to the root logger, which can in turn
821 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823.. function:: disable(lvl)
824
825 Provides an overriding level *lvl* for all loggers which takes precedence over
826 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000827 output down across the whole application, this function can be useful. Its
828 effect is to disable all logging calls of severity *lvl* and below, so that
829 if you call it with a value of INFO, then all INFO and DEBUG events would be
830 discarded, whereas those of severity WARNING and above would be processed
831 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833
834.. function:: addLevelName(lvl, levelName)
835
836 Associates level *lvl* with text *levelName* in an internal dictionary, which is
837 used to map numeric levels to a textual representation, for example when a
838 :class:`Formatter` formats a message. This function can also be used to define
839 your own levels. The only constraints are that all levels used must be
840 registered using this function, levels should be positive integers and they
841 should increase in increasing order of severity.
842
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000843 NOTE: If you are thinking of defining your own levels, please see the section
844 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846.. function:: getLevelName(lvl)
847
848 Returns the textual representation of logging level *lvl*. If the level is one
849 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
850 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
851 have associated levels with names using :func:`addLevelName` then the name you
852 have associated with *lvl* is returned. If a numeric value corresponding to one
853 of the defined levels is passed in, the corresponding string representation is
854 returned. Otherwise, the string "Level %s" % lvl is returned.
855
856
857.. function:: makeLogRecord(attrdict)
858
859 Creates and returns a new :class:`LogRecord` instance whose attributes are
860 defined by *attrdict*. This function is useful for taking a pickled
861 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
862 it as a :class:`LogRecord` instance at the receiving end.
863
864
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000865.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867 Does basic configuration for the logging system by creating a
868 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000869 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000870 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
871 if no handlers are defined for the root logger.
872
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000873 This function does nothing if the root logger already has handlers
874 configured for it.
875
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000876 PLEASE NOTE: This function should be called from the main thread
877 before other threads are started. In versions of Python prior to
878 2.7.1 and 3.2, if this function is called from multiple threads,
879 it is possible (in rare circumstances) that a handler will be added
880 to the root logger more than once, leading to unexpected results
881 such as messages being duplicated in the log.
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883 The following keyword arguments are supported.
884
885 +--------------+---------------------------------------------+
886 | Format | Description |
887 +==============+=============================================+
888 | ``filename`` | Specifies that a FileHandler be created, |
889 | | using the specified filename, rather than a |
890 | | StreamHandler. |
891 +--------------+---------------------------------------------+
892 | ``filemode`` | Specifies the mode to open the file, if |
893 | | filename is specified (if filemode is |
894 | | unspecified, it defaults to 'a'). |
895 +--------------+---------------------------------------------+
896 | ``format`` | Use the specified format string for the |
897 | | handler. |
898 +--------------+---------------------------------------------+
899 | ``datefmt`` | Use the specified date/time format. |
900 +--------------+---------------------------------------------+
901 | ``level`` | Set the root logger level to the specified |
902 | | level. |
903 +--------------+---------------------------------------------+
904 | ``stream`` | Use the specified stream to initialize the |
905 | | StreamHandler. Note that this argument is |
906 | | incompatible with 'filename' - if both are |
907 | | present, 'stream' is ignored. |
908 +--------------+---------------------------------------------+
909
Georg Brandl116aa622007-08-15 14:28:22 +0000910.. function:: shutdown()
911
912 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000913 closing all handlers. This should be called at application exit and no
914 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916
917.. function:: setLoggerClass(klass)
918
919 Tells the logging system to use the class *klass* when instantiating a logger.
920 The class should define :meth:`__init__` such that only a name argument is
921 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
922 function is typically called before any loggers are instantiated by applications
923 which need to use custom logger behavior.
924
925
926.. seealso::
927
928 :pep:`282` - A Logging System
929 The proposal which described this feature for inclusion in the Python standard
930 library.
931
Christian Heimes255f53b2007-12-08 15:33:56 +0000932 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000933 This is the original source for the :mod:`logging` package. The version of the
934 package available from this site is suitable for use with Python 1.5.2, 2.1.x
935 and 2.2.x, which do not include the :mod:`logging` package in the standard
936 library.
937
Vinay Sajip4039aff2010-09-11 10:25:28 +0000938.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940Logger Objects
941--------------
942
943Loggers have the following attributes and methods. Note that Loggers are never
944instantiated directly, but always through the module-level function
945``logging.getLogger(name)``.
946
Vinay Sajip0258ce82010-09-22 20:34:53 +0000947.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949.. attribute:: Logger.propagate
950
951 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000952 its child loggers to the handlers of higher level (ancestor) loggers. The
953 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955
956.. method:: Logger.setLevel(lvl)
957
958 Sets the threshold for this logger to *lvl*. Logging messages which are less
959 severe than *lvl* will be ignored. When a logger is created, the level is set to
960 :const:`NOTSET` (which causes all messages to be processed when the logger is
961 the root logger, or delegation to the parent when the logger is a non-root
962 logger). Note that the root logger is created with level :const:`WARNING`.
963
964 The term "delegation to the parent" means that if a logger has a level of
965 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
966 a level other than NOTSET is found, or the root is reached.
967
968 If an ancestor is found with a level other than NOTSET, then that ancestor's
969 level is treated as the effective level of the logger where the ancestor search
970 began, and is used to determine how a logging event is handled.
971
972 If the root is reached, and it has a level of NOTSET, then all messages will be
973 processed. Otherwise, the root's level will be used as the effective level.
974
975
976.. method:: Logger.isEnabledFor(lvl)
977
978 Indicates if a message of severity *lvl* would be processed by this logger.
979 This method checks first the module-level level set by
980 ``logging.disable(lvl)`` and then the logger's effective level as determined
981 by :meth:`getEffectiveLevel`.
982
983
984.. method:: Logger.getEffectiveLevel()
985
986 Indicates the effective level for this logger. If a value other than
987 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
988 the hierarchy is traversed towards the root until a value other than
989 :const:`NOTSET` is found, and that value is returned.
990
991
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000992.. method:: Logger.getChild(suffix)
993
994 Returns a logger which is a descendant to this logger, as determined by the suffix.
995 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
996 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
997 convenience method, useful when the parent logger is named using e.g. ``__name__``
998 rather than a literal string.
999
1000 .. versionadded:: 3.2
1001
Georg Brandl67b21b72010-08-17 15:07:14 +00001002
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001003.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001004
1005 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1006 message format string, and the *args* are the arguments which are merged into
1007 *msg* using the string formatting operator. (Note that this means that you can
1008 use keywords in the format string, together with a single dictionary argument.)
1009
1010 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
1011 which, if it does not evaluate as false, causes exception information to be
1012 added to the logging message. If an exception tuple (in the format returned by
1013 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1014 is called to get the exception information.
1015
1016 The other optional keyword argument is *extra* which can be used to pass a
1017 dictionary which is used to populate the __dict__ of the LogRecord created for
1018 the logging event with user-defined attributes. These custom attributes can then
1019 be used as you like. For example, they could be incorporated into logged
1020 messages. For example::
1021
1022 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1023 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001024 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001025 logger = logging.getLogger("tcpserver")
1026 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1027
1028 would print something like ::
1029
1030 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1031
1032 The keys in the dictionary passed in *extra* should not clash with the keys used
1033 by the logging system. (See the :class:`Formatter` documentation for more
1034 information on which keys are used by the logging system.)
1035
1036 If you choose to use these attributes in logged messages, you need to exercise
1037 some care. In the above example, for instance, the :class:`Formatter` has been
1038 set up with a format string which expects 'clientip' and 'user' in the attribute
1039 dictionary of the LogRecord. If these are missing, the message will not be
1040 logged because a string formatting exception will occur. So in this case, you
1041 always need to pass the *extra* dictionary with these keys.
1042
1043 While this might be annoying, this feature is intended for use in specialized
1044 circumstances, such as multi-threaded servers where the same code executes in
1045 many contexts, and interesting conditions which arise are dependent on this
1046 context (such as remote client IP address and authenticated user name, in the
1047 above example). In such circumstances, it is likely that specialized
1048 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1049
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001051.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001052
1053 Logs a message with level :const:`INFO` on this logger. The arguments are
1054 interpreted as for :meth:`debug`.
1055
1056
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001057.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059 Logs a message with level :const:`WARNING` on this logger. The arguments are
1060 interpreted as for :meth:`debug`.
1061
1062
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001063.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065 Logs a message with level :const:`ERROR` on this logger. The arguments are
1066 interpreted as for :meth:`debug`.
1067
1068
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001069.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1072 interpreted as for :meth:`debug`.
1073
1074
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001075.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077 Logs a message with integer level *lvl* on this logger. The other arguments are
1078 interpreted as for :meth:`debug`.
1079
1080
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001081.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001082
1083 Logs a message with level :const:`ERROR` on this logger. The arguments are
1084 interpreted as for :meth:`debug`. Exception info is added to the logging
1085 message. This method should only be called from an exception handler.
1086
1087
1088.. method:: Logger.addFilter(filt)
1089
1090 Adds the specified filter *filt* to this logger.
1091
1092
1093.. method:: Logger.removeFilter(filt)
1094
1095 Removes the specified filter *filt* from this logger.
1096
1097
1098.. method:: Logger.filter(record)
1099
1100 Applies this logger's filters to the record and returns a true value if the
1101 record is to be processed.
1102
1103
1104.. method:: Logger.addHandler(hdlr)
1105
1106 Adds the specified handler *hdlr* to this logger.
1107
1108
1109.. method:: Logger.removeHandler(hdlr)
1110
1111 Removes the specified handler *hdlr* from this logger.
1112
1113
1114.. method:: Logger.findCaller()
1115
1116 Finds the caller's source filename and line number. Returns the filename, line
1117 number and function name as a 3-element tuple.
1118
Georg Brandl116aa622007-08-15 14:28:22 +00001119
1120.. method:: Logger.handle(record)
1121
1122 Handles a record by passing it to all handlers associated with this logger and
1123 its ancestors (until a false value of *propagate* is found). This method is used
1124 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001125 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001128.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130 This is a factory method which can be overridden in subclasses to create
1131 specialized :class:`LogRecord` instances.
1132
Vinay Sajip83eadd12010-09-20 10:31:18 +00001133.. method:: Logger.hasHandlers()
1134
1135 Checks to see if this logger has any handlers configured. This is done by
1136 looking for handlers in this logger and its parents in the logger hierarchy.
1137 Returns True if a handler was found, else False. The method stops searching
1138 up the hierarchy whenever a logger with the "propagate" attribute set to
1139 False is found - that will be the last logger which is checked for the
1140 existence of handlers.
1141
1142.. versionadded:: 3.2
1143
1144The :meth:`hasHandlers` method was not present in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001145
1146.. _minimal-example:
1147
1148Basic example
1149-------------
1150
Georg Brandl116aa622007-08-15 14:28:22 +00001151The :mod:`logging` package provides a lot of flexibility, and its configuration
1152can appear daunting. This section demonstrates that simple use of the logging
1153package is possible.
1154
1155The simplest example shows logging to the console::
1156
1157 import logging
1158
1159 logging.debug('A debug message')
1160 logging.info('Some information')
1161 logging.warning('A shot across the bows')
1162
1163If you run the above script, you'll see this::
1164
1165 WARNING:root:A shot across the bows
1166
1167Because no particular logger was specified, the system used the root logger. The
1168debug and info messages didn't appear because by default, the root logger is
1169configured to only handle messages with a severity of WARNING or above. The
1170message format is also a configuration default, as is the output destination of
1171the messages - ``sys.stderr``. The severity level, the message format and
1172destination can be easily changed, as shown in the example below::
1173
1174 import logging
1175
1176 logging.basicConfig(level=logging.DEBUG,
1177 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001178 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001179 filemode='w')
1180 logging.debug('A debug message')
1181 logging.info('Some information')
1182 logging.warning('A shot across the bows')
1183
1184The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001185which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001186something like the following::
1187
1188 2004-07-02 13:00:08,743 DEBUG A debug message
1189 2004-07-02 13:00:08,743 INFO Some information
1190 2004-07-02 13:00:08,743 WARNING A shot across the bows
1191
1192This time, all messages with a severity of DEBUG or above were handled, and the
1193format of the messages was also changed, and output went to the specified file
1194rather than the console.
1195
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001196.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001197
1198Formatting uses the old Python string formatting - see section
1199:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001200specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1201documentation.
1202
1203+-------------------+-----------------------------------------------+
1204| Format | Description |
1205+===================+===============================================+
1206| ``%(name)s`` | Name of the logger (logging channel). |
1207+-------------------+-----------------------------------------------+
1208| ``%(levelname)s`` | Text logging level for the message |
1209| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1210| | ``'ERROR'``, ``'CRITICAL'``). |
1211+-------------------+-----------------------------------------------+
1212| ``%(asctime)s`` | Human-readable time when the |
1213| | :class:`LogRecord` was created. By default |
1214| | this is of the form "2003-07-08 16:49:45,896" |
1215| | (the numbers after the comma are millisecond |
1216| | portion of the time). |
1217+-------------------+-----------------------------------------------+
1218| ``%(message)s`` | The logged message. |
1219+-------------------+-----------------------------------------------+
1220
1221To change the date/time format, you can pass an additional keyword parameter,
1222*datefmt*, as in the following::
1223
1224 import logging
1225
1226 logging.basicConfig(level=logging.DEBUG,
1227 format='%(asctime)s %(levelname)-8s %(message)s',
1228 datefmt='%a, %d %b %Y %H:%M:%S',
1229 filename='/temp/myapp.log',
1230 filemode='w')
1231 logging.debug('A debug message')
1232 logging.info('Some information')
1233 logging.warning('A shot across the bows')
1234
1235which would result in output like ::
1236
1237 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1238 Fri, 02 Jul 2004 13:06:18 INFO Some information
1239 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1240
1241The date format string follows the requirements of :func:`strftime` - see the
1242documentation for the :mod:`time` module.
1243
1244If, instead of sending logging output to the console or a file, you'd rather use
1245a file-like object which you have created separately, you can pass it to
1246:func:`basicConfig` using the *stream* keyword argument. Note that if both
1247*stream* and *filename* keyword arguments are passed, the *stream* argument is
1248ignored.
1249
1250Of course, you can put variable information in your output. To do this, simply
1251have the message be a format string and pass in additional arguments containing
1252the variable information, as in the following example::
1253
1254 import logging
1255
1256 logging.basicConfig(level=logging.DEBUG,
1257 format='%(asctime)s %(levelname)-8s %(message)s',
1258 datefmt='%a, %d %b %Y %H:%M:%S',
1259 filename='/temp/myapp.log',
1260 filemode='w')
1261 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1262
1263which would result in ::
1264
1265 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1266
1267
1268.. _multiple-destinations:
1269
1270Logging to multiple destinations
1271--------------------------------
1272
1273Let's say you want to log to console and file with different message formats and
1274in differing circumstances. Say you want to log messages with levels of DEBUG
1275and higher to file, and those messages at level INFO and higher to the console.
1276Let's also assume that the file should contain timestamps, but the console
1277messages should not. Here's how you can achieve this::
1278
1279 import logging
1280
1281 # set up logging to file - see previous section for more details
1282 logging.basicConfig(level=logging.DEBUG,
1283 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1284 datefmt='%m-%d %H:%M',
1285 filename='/temp/myapp.log',
1286 filemode='w')
1287 # define a Handler which writes INFO messages or higher to the sys.stderr
1288 console = logging.StreamHandler()
1289 console.setLevel(logging.INFO)
1290 # set a format which is simpler for console use
1291 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1292 # tell the handler to use this format
1293 console.setFormatter(formatter)
1294 # add the handler to the root logger
1295 logging.getLogger('').addHandler(console)
1296
1297 # Now, we can log to the root logger, or any other logger. First the root...
1298 logging.info('Jackdaws love my big sphinx of quartz.')
1299
1300 # Now, define a couple of other loggers which might represent areas in your
1301 # application:
1302
1303 logger1 = logging.getLogger('myapp.area1')
1304 logger2 = logging.getLogger('myapp.area2')
1305
1306 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1307 logger1.info('How quickly daft jumping zebras vex.')
1308 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1309 logger2.error('The five boxing wizards jump quickly.')
1310
1311When you run this, on the console you will see ::
1312
1313 root : INFO Jackdaws love my big sphinx of quartz.
1314 myapp.area1 : INFO How quickly daft jumping zebras vex.
1315 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1316 myapp.area2 : ERROR The five boxing wizards jump quickly.
1317
1318and in the file you will see something like ::
1319
1320 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1321 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1322 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1323 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1324 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1325
1326As you can see, the DEBUG message only shows up in the file. The other messages
1327are sent to both destinations.
1328
1329This example uses console and file handlers, but you can use any number and
1330combination of handlers you choose.
1331
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001332.. _logging-exceptions:
1333
1334Exceptions raised during logging
1335--------------------------------
1336
1337The logging package is designed to swallow exceptions which occur while logging
1338in production. This is so that errors which occur while handling logging events
1339- such as logging misconfiguration, network or other similar errors - do not
1340cause the application using logging to terminate prematurely.
1341
1342:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1343swallowed. Other exceptions which occur during the :meth:`emit` method of a
1344:class:`Handler` subclass are passed to its :meth:`handleError` method.
1345
1346The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001347to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1348traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001349
Georg Brandlef871f62010-03-12 10:06:40 +00001350**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001351during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001352occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001353usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Christian Heimes790c8232008-01-07 21:14:23 +00001355.. _context-info:
1356
1357Adding contextual information to your logging output
1358----------------------------------------------------
1359
1360Sometimes you want logging output to contain contextual information in
1361addition to the parameters passed to the logging call. For example, in a
1362networked application, it may be desirable to log client-specific information
1363in the log (e.g. remote client's username, or IP address). Although you could
1364use the *extra* parameter to achieve this, it's not always convenient to pass
1365the information in this way. While it might be tempting to create
1366:class:`Logger` instances on a per-connection basis, this is not a good idea
1367because these instances are not garbage collected. While this is not a problem
1368in practice, when the number of :class:`Logger` instances is dependent on the
1369level of granularity you want to use in logging an application, it could
1370be hard to manage if the number of :class:`Logger` instances becomes
1371effectively unbounded.
1372
Vinay Sajipc31be632010-09-06 22:18:20 +00001373
1374Using LoggerAdapters to impart contextual information
1375^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1376
Christian Heimes04c420f2008-01-18 18:40:46 +00001377An easy way in which you can pass contextual information to be output along
1378with logging event information is to use the :class:`LoggerAdapter` class.
1379This class is designed to look like a :class:`Logger`, so that you can call
1380:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1381:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1382same signatures as their counterparts in :class:`Logger`, so you can use the
1383two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001384
Christian Heimes04c420f2008-01-18 18:40:46 +00001385When you create an instance of :class:`LoggerAdapter`, you pass it a
1386:class:`Logger` instance and a dict-like object which contains your contextual
1387information. When you call one of the logging methods on an instance of
1388:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1389:class:`Logger` passed to its constructor, and arranges to pass the contextual
1390information in the delegated call. Here's a snippet from the code of
1391:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001392
Christian Heimes04c420f2008-01-18 18:40:46 +00001393 def debug(self, msg, *args, **kwargs):
1394 """
1395 Delegate a debug call to the underlying logger, after adding
1396 contextual information from this adapter instance.
1397 """
1398 msg, kwargs = self.process(msg, kwargs)
1399 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001400
Christian Heimes04c420f2008-01-18 18:40:46 +00001401The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1402information is added to the logging output. It's passed the message and
1403keyword arguments of the logging call, and it passes back (potentially)
1404modified versions of these to use in the call to the underlying logger. The
1405default implementation of this method leaves the message alone, but inserts
1406an "extra" key in the keyword argument whose value is the dict-like object
1407passed to the constructor. Of course, if you had passed an "extra" keyword
1408argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001409
Christian Heimes04c420f2008-01-18 18:40:46 +00001410The advantage of using "extra" is that the values in the dict-like object are
1411merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1412customized strings with your :class:`Formatter` instances which know about
1413the keys of the dict-like object. If you need a different method, e.g. if you
1414want to prepend or append the contextual information to the message string,
1415you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1416to do what you need. Here's an example script which uses this class, which
1417also illustrates what dict-like behaviour is needed from an arbitrary
1418"dict-like" object for use in the constructor::
1419
Christian Heimes587c2bf2008-01-19 16:21:02 +00001420 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001421
Christian Heimes587c2bf2008-01-19 16:21:02 +00001422 class ConnInfo:
1423 """
1424 An example class which shows how an arbitrary class can be used as
1425 the 'extra' context information repository passed to a LoggerAdapter.
1426 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001427
Christian Heimes587c2bf2008-01-19 16:21:02 +00001428 def __getitem__(self, name):
1429 """
1430 To allow this instance to look like a dict.
1431 """
1432 from random import choice
1433 if name == "ip":
1434 result = choice(["127.0.0.1", "192.168.0.1"])
1435 elif name == "user":
1436 result = choice(["jim", "fred", "sheila"])
1437 else:
1438 result = self.__dict__.get(name, "?")
1439 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001440
Christian Heimes587c2bf2008-01-19 16:21:02 +00001441 def __iter__(self):
1442 """
1443 To allow iteration over keys, which will be merged into
1444 the LogRecord dict before formatting and output.
1445 """
1446 keys = ["ip", "user"]
1447 keys.extend(self.__dict__.keys())
1448 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001449
Christian Heimes587c2bf2008-01-19 16:21:02 +00001450 if __name__ == "__main__":
1451 from random import choice
1452 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1453 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1454 { "ip" : "123.231.231.123", "user" : "sheila" })
1455 logging.basicConfig(level=logging.DEBUG,
1456 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1457 a1.debug("A debug message")
1458 a1.info("An info message with %s", "some parameters")
1459 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1460 for x in range(10):
1461 lvl = choice(levels)
1462 lvlname = logging.getLevelName(lvl)
1463 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001464
1465When this script is run, the output should look something like this::
1466
Christian Heimes587c2bf2008-01-19 16:21:02 +00001467 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1468 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1469 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
1470 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
1471 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
1472 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
1473 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
1474 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
1475 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
1476 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
1477 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
1478 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 +00001479
Christian Heimes790c8232008-01-07 21:14:23 +00001480
Vinay Sajipac007992010-09-17 12:45:26 +00001481.. _filters-contextual:
1482
Vinay Sajipc31be632010-09-06 22:18:20 +00001483Using Filters to impart contextual information
1484^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1485
1486You can also add contextual information to log output using a user-defined
1487:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1488passed to them, including adding additional attributes which can then be output
1489using a suitable format string, or if needed a custom :class:`Formatter`.
1490
1491For example in a web application, the request being processed (or at least,
1492the interesting parts of it) can be stored in a threadlocal
1493(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1494add, say, information from the request - say, the remote IP address and remote
1495user's username - to the ``LogRecord``, using the attribute names 'ip' and
1496'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1497string can be used to get similar output to that shown above. Here's an example
1498script::
1499
1500 import logging
1501 from random import choice
1502
1503 class ContextFilter(logging.Filter):
1504 """
1505 This is a filter which injects contextual information into the log.
1506
1507 Rather than use actual contextual information, we just use random
1508 data in this demo.
1509 """
1510
1511 USERS = ['jim', 'fred', 'sheila']
1512 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1513
1514 def filter(self, record):
1515
1516 record.ip = choice(ContextFilter.IPS)
1517 record.user = choice(ContextFilter.USERS)
1518 return True
1519
1520 if __name__ == "__main__":
1521 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1522 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1523 { "ip" : "123.231.231.123", "user" : "sheila" })
1524 logging.basicConfig(level=logging.DEBUG,
1525 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1526 a1 = logging.getLogger("a.b.c")
1527 a2 = logging.getLogger("d.e.f")
1528
1529 f = ContextFilter()
1530 a1.addFilter(f)
1531 a2.addFilter(f)
1532 a1.debug("A debug message")
1533 a1.info("An info message with %s", "some parameters")
1534 for x in range(10):
1535 lvl = choice(levels)
1536 lvlname = logging.getLevelName(lvl)
1537 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1538
1539which, when run, produces something like::
1540
1541 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1542 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1543 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1544 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters
1545 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters
1546 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters
1547 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
1548 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1549 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters
1550 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
1551 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters
1552 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters
1553
1554
Vinay Sajipd31f3632010-06-29 15:31:15 +00001555.. _multiple-processes:
1556
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001557Logging to a single file from multiple processes
1558------------------------------------------------
1559
1560Although logging is thread-safe, and logging to a single file from multiple
1561threads in a single process *is* supported, logging to a single file from
1562*multiple processes* is *not* supported, because there is no standard way to
1563serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001564need to log to a single file from multiple processes, one way of doing this is
1565to have all the processes log to a :class:`SocketHandler`, and have a separate
1566process which implements a socket server which reads from the socket and logs
1567to file. (If you prefer, you can dedicate one thread in one of the existing
1568processes to perform this function.) The following section documents this
1569approach in more detail and includes a working socket receiver which can be
1570used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001571
Vinay Sajip5a92b132009-08-15 23:35:08 +00001572If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001573:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001574:class:`Lock` class from this module to serialize access to the file from
1575your processes. The existing :class:`FileHandler` and subclasses do not make
1576use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001577Note that at present, the :mod:`multiprocessing` module does not provide
1578working lock functionality on all platforms (see
1579http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001580
Vinay Sajip121a1c42010-09-08 10:46:15 +00001581.. currentmodule:: logging.handlers
1582
1583Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1584all logging events to one of the processes in your multi-process application.
1585The following example script demonstrates how you can do this; in the example
1586a separate listener process listens for events sent by other processes and logs
1587them according to its own logging configuration. Although the example only
1588demonstrates one way of doing it (for example, you may want to use a listener
1589thread rather than a separate listener process - the implementation would be
1590analogous) it does allow for completely different logging configurations for
1591the listener and the other processes in your application, and can be used as
1592the basis for code meeting your own specific requirements::
1593
1594 # You'll need these imports in your own code
1595 import logging
1596 import logging.handlers
1597 import multiprocessing
1598
1599 # Next two import lines for this demo only
1600 from random import choice, random
1601 import time
1602
1603 #
1604 # Because you'll want to define the logging configurations for listener and workers, the
1605 # listener and worker process functions take a configurer parameter which is a callable
1606 # for configuring logging for that process. These functions are also passed the queue,
1607 # which they use for communication.
1608 #
1609 # In practice, you can configure the listener however you want, but note that in this
1610 # simple example, the listener does not apply level or filter logic to received records.
1611 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1612 # sending events which would be filtered out between processes.
1613 #
1614 # The size of the rotated files is made small so you can see the results easily.
1615 def listener_configurer():
1616 root = logging.getLogger()
1617 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
1618 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1619 h.setFormatter(f)
1620 root.addHandler(h)
1621
1622 # This is the listener process top-level loop: wait for logging events
1623 # (LogRecords)on the queue and handle them, quit when you get a None for a
1624 # LogRecord.
1625 def listener_process(queue, configurer):
1626 configurer()
1627 while True:
1628 try:
1629 record = queue.get()
1630 if record is None: # We send this as a sentinel to tell the listener to quit.
1631 break
1632 logger = logging.getLogger(record.name)
1633 logger.handle(record) # No level or filter logic applied - just do it!
1634 except (KeyboardInterrupt, SystemExit):
1635 raise
1636 except:
1637 import sys, traceback
1638 print >> sys.stderr, 'Whoops! Problem:'
1639 traceback.print_exc(file=sys.stderr)
1640
1641 # Arrays used for random selections in this demo
1642
1643 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1644 logging.ERROR, logging.CRITICAL]
1645
1646 LOGGERS = ['a.b.c', 'd.e.f']
1647
1648 MESSAGES = [
1649 'Random message #1',
1650 'Random message #2',
1651 'Random message #3',
1652 ]
1653
1654 # The worker configuration is done at the start of the worker process run.
1655 # Note that on Windows you can't rely on fork semantics, so each process
1656 # will run the logging configuration code when it starts.
1657 def worker_configurer(queue):
1658 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1659 root = logging.getLogger()
1660 root.addHandler(h)
1661 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
1662
1663 # This is the worker process top-level loop, which just logs ten events with
1664 # random intervening delays before terminating.
1665 # The print messages are just so you know it's doing something!
1666 def worker_process(queue, configurer):
1667 configurer(queue)
1668 name = multiprocessing.current_process().name
1669 print('Worker started: %s' % name)
1670 for i in range(10):
1671 time.sleep(random())
1672 logger = logging.getLogger(choice(LOGGERS))
1673 level = choice(LEVELS)
1674 message = choice(MESSAGES)
1675 logger.log(level, message)
1676 print('Worker finished: %s' % name)
1677
1678 # Here's where the demo gets orchestrated. Create the queue, create and start
1679 # the listener, create ten workers and start them, wait for them to finish,
1680 # then send a None to the queue to tell the listener to finish.
1681 def main():
1682 queue = multiprocessing.Queue(-1)
1683 listener = multiprocessing.Process(target=listener_process,
1684 args=(queue, listener_configurer))
1685 listener.start()
1686 workers = []
1687 for i in range(10):
1688 worker = multiprocessing.Process(target=worker_process,
1689 args=(queue, worker_configurer))
1690 workers.append(worker)
1691 worker.start()
1692 for w in workers:
1693 w.join()
1694 queue.put_nowait(None)
1695 listener.join()
1696
1697 if __name__ == '__main__':
1698 main()
1699
1700
1701.. currentmodule:: logging
1702
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001703
Georg Brandl116aa622007-08-15 14:28:22 +00001704.. _network-logging:
1705
1706Sending and receiving logging events across a network
1707-----------------------------------------------------
1708
1709Let's say you want to send logging events across a network, and handle them at
1710the receiving end. A simple way of doing this is attaching a
1711:class:`SocketHandler` instance to the root logger at the sending end::
1712
1713 import logging, logging.handlers
1714
1715 rootLogger = logging.getLogger('')
1716 rootLogger.setLevel(logging.DEBUG)
1717 socketHandler = logging.handlers.SocketHandler('localhost',
1718 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1719 # don't bother with a formatter, since a socket handler sends the event as
1720 # an unformatted pickle
1721 rootLogger.addHandler(socketHandler)
1722
1723 # Now, we can log to the root logger, or any other logger. First the root...
1724 logging.info('Jackdaws love my big sphinx of quartz.')
1725
1726 # Now, define a couple of other loggers which might represent areas in your
1727 # application:
1728
1729 logger1 = logging.getLogger('myapp.area1')
1730 logger2 = logging.getLogger('myapp.area2')
1731
1732 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1733 logger1.info('How quickly daft jumping zebras vex.')
1734 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1735 logger2.error('The five boxing wizards jump quickly.')
1736
Alexandre Vassalottice261952008-05-12 02:31:37 +00001737At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001738module. Here is a basic working example::
1739
Georg Brandla35f4b92009-05-31 16:41:59 +00001740 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001741 import logging
1742 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001743 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001744 import struct
1745
1746
Alexandre Vassalottice261952008-05-12 02:31:37 +00001747 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001748 """Handler for a streaming logging request.
1749
1750 This basically logs the record using whatever logging policy is
1751 configured locally.
1752 """
1753
1754 def handle(self):
1755 """
1756 Handle multiple requests - each expected to be a 4-byte length,
1757 followed by the LogRecord in pickle format. Logs the record
1758 according to whatever policy is configured locally.
1759 """
Collin Winter46334482007-09-10 00:49:57 +00001760 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001761 chunk = self.connection.recv(4)
1762 if len(chunk) < 4:
1763 break
1764 slen = struct.unpack(">L", chunk)[0]
1765 chunk = self.connection.recv(slen)
1766 while len(chunk) < slen:
1767 chunk = chunk + self.connection.recv(slen - len(chunk))
1768 obj = self.unPickle(chunk)
1769 record = logging.makeLogRecord(obj)
1770 self.handleLogRecord(record)
1771
1772 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001773 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001774
1775 def handleLogRecord(self, record):
1776 # if a name is specified, we use the named logger rather than the one
1777 # implied by the record.
1778 if self.server.logname is not None:
1779 name = self.server.logname
1780 else:
1781 name = record.name
1782 logger = logging.getLogger(name)
1783 # N.B. EVERY record gets logged. This is because Logger.handle
1784 # is normally called AFTER logger-level filtering. If you want
1785 # to do filtering, do it at the client end to save wasting
1786 # cycles and network bandwidth!
1787 logger.handle(record)
1788
Alexandre Vassalottice261952008-05-12 02:31:37 +00001789 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001790 """simple TCP socket-based logging receiver suitable for testing.
1791 """
1792
1793 allow_reuse_address = 1
1794
1795 def __init__(self, host='localhost',
1796 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1797 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001798 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001799 self.abort = 0
1800 self.timeout = 1
1801 self.logname = None
1802
1803 def serve_until_stopped(self):
1804 import select
1805 abort = 0
1806 while not abort:
1807 rd, wr, ex = select.select([self.socket.fileno()],
1808 [], [],
1809 self.timeout)
1810 if rd:
1811 self.handle_request()
1812 abort = self.abort
1813
1814 def main():
1815 logging.basicConfig(
1816 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1817 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001818 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001819 tcpserver.serve_until_stopped()
1820
1821 if __name__ == "__main__":
1822 main()
1823
1824First run the server, and then the client. On the client side, nothing is
1825printed on the console; on the server side, you should see something like::
1826
1827 About to start TCP server...
1828 59 root INFO Jackdaws love my big sphinx of quartz.
1829 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1830 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1831 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1832 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1833
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001834Note that there are some security issues with pickle in some scenarios. If
1835these affect you, you can use an alternative serialization scheme by overriding
1836the :meth:`makePickle` method and implementing your alternative there, as
1837well as adapting the above script to use your alternative serialization.
1838
Vinay Sajip4039aff2010-09-11 10:25:28 +00001839.. _arbitrary-object-messages:
1840
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001841Using arbitrary objects as messages
1842-----------------------------------
1843
1844In the preceding sections and examples, it has been assumed that the message
1845passed when logging the event is a string. However, this is not the only
1846possibility. You can pass an arbitrary object as a message, and its
1847:meth:`__str__` method will be called when the logging system needs to convert
1848it to a string representation. In fact, if you want to, you can avoid
1849computing a string representation altogether - for example, the
1850:class:`SocketHandler` emits an event by pickling it and sending it over the
1851wire.
1852
Vinay Sajip55778922010-09-23 09:09:15 +00001853Dealing with handlers that block
1854--------------------------------
1855
1856.. currentmodule:: logging.handlers
1857
1858Sometimes you have to get your logging handlers to do their work without
1859blocking the thread you’re logging from. This is common in Web applications,
1860though of course it also occurs in other scenarios.
1861
1862A common culprit which demonstrates sluggish behaviour is the
1863:class:`SMTPHandler`: sending emails can take a long time, for a
1864number of reasons outside the developer’s control (for example, a poorly
1865performing mail or network infrastructure). But almost any network-based
1866handler can block: Even a :class:`SocketHandler` operation may do a
1867DNS query under the hood which is too slow (and this query can be deep in the
1868socket library code, below the Python layer, and outside your control).
1869
1870One solution is to use a two-part approach. For the first part, attach only a
1871:class:`QueueHandler` to those loggers which are accessed from
1872performance-critical threads. They simply write to their queue, which can be
1873sized to a large enough capacity or initialized with no upper bound to their
1874size. The write to the queue will typically be accepted quickly, though you
1875will probably need to catch the :ref:`queue.Full` exception as a precaution
1876in your code. If you are a library developer who has performance-critical
1877threads in their code, be sure to document this (together with a suggestion to
1878attach only ``QueueHandlers`` to your loggers) for the benefit of other
1879developers who will use your code.
1880
1881The second part of the solution is :class:`QueueListener`, which has been
1882designed as the counterpart to :class:`QueueHandler`. A
1883:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
1884and it fires up an internal thread which listens to its queue for LogRecords
1885sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
1886matter). The ``LogRecords`` are removed from the queue and passed to the
1887handlers for processing.
1888
1889The advantage of having a separate :class:`QueueListener` class is that you
1890can use the same instance to service multiple ``QueueHandlers``. This is more
1891resource-friendly than, say, having threaded versions of the existing handler
1892classes, which would eat up one thread per handler for no particular benefit.
1893
1894An example of using these two classes follows (imports omitted)::
1895
1896 que = queue.Queue(-1) # no limit on size
1897 queue_handler = QueueHandler(que)
1898 handler = logging.StreamHandler()
1899 listener = QueueListener(que, handler)
1900 root = logging.getLogger()
1901 root.addHandler(queue_handler)
1902 formatter = logging.Formatter('%(threadName)s: %(message)s')
1903 handler.setFormatter(formatter)
1904 listener.start()
1905 # The log output will display the thread which generated
1906 # the event (the main thread) rather than the internal
1907 # thread which monitors the internal queue. This is what
1908 # you want to happen.
1909 root.warning('Look out!')
1910 listener.stop()
1911
1912which, when run, will produce::
1913
1914 MainThread: Look out!
1915
1916
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001917Optimization
1918------------
1919
1920Formatting of message arguments is deferred until it cannot be avoided.
1921However, computing the arguments passed to the logging method can also be
1922expensive, and you may want to avoid doing it if the logger will just throw
1923away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1924method which takes a level argument and returns true if the event would be
1925created by the Logger for that level of call. You can write code like this::
1926
1927 if logger.isEnabledFor(logging.DEBUG):
1928 logger.debug("Message with %s, %s", expensive_func1(),
1929 expensive_func2())
1930
1931so that if the logger's threshold is set above ``DEBUG``, the calls to
1932:func:`expensive_func1` and :func:`expensive_func2` are never made.
1933
1934There are other optimizations which can be made for specific applications which
1935need more precise control over what logging information is collected. Here's a
1936list of things you can do to avoid processing during logging which you don't
1937need:
1938
1939+-----------------------------------------------+----------------------------------------+
1940| What you don't want to collect | How to avoid collecting it |
1941+===============================================+========================================+
1942| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1943+-----------------------------------------------+----------------------------------------+
1944| Threading information. | Set ``logging.logThreads`` to ``0``. |
1945+-----------------------------------------------+----------------------------------------+
1946| Process information. | Set ``logging.logProcesses`` to ``0``. |
1947+-----------------------------------------------+----------------------------------------+
1948
1949Also note that the core logging module only includes the basic handlers. If
1950you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1951take up any memory.
1952
1953.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001954
1955Handler Objects
1956---------------
1957
1958Handlers have the following attributes and methods. Note that :class:`Handler`
1959is never instantiated directly; this class acts as a base for more useful
1960subclasses. However, the :meth:`__init__` method in subclasses needs to call
1961:meth:`Handler.__init__`.
1962
1963
1964.. method:: Handler.__init__(level=NOTSET)
1965
1966 Initializes the :class:`Handler` instance by setting its level, setting the list
1967 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1968 serializing access to an I/O mechanism.
1969
1970
1971.. method:: Handler.createLock()
1972
1973 Initializes a thread lock which can be used to serialize access to underlying
1974 I/O functionality which may not be threadsafe.
1975
1976
1977.. method:: Handler.acquire()
1978
1979 Acquires the thread lock created with :meth:`createLock`.
1980
1981
1982.. method:: Handler.release()
1983
1984 Releases the thread lock acquired with :meth:`acquire`.
1985
1986
1987.. method:: Handler.setLevel(lvl)
1988
1989 Sets the threshold for this handler to *lvl*. Logging messages which are less
1990 severe than *lvl* will be ignored. When a handler is created, the level is set
1991 to :const:`NOTSET` (which causes all messages to be processed).
1992
1993
1994.. method:: Handler.setFormatter(form)
1995
1996 Sets the :class:`Formatter` for this handler to *form*.
1997
1998
1999.. method:: Handler.addFilter(filt)
2000
2001 Adds the specified filter *filt* to this handler.
2002
2003
2004.. method:: Handler.removeFilter(filt)
2005
2006 Removes the specified filter *filt* from this handler.
2007
2008
2009.. method:: Handler.filter(record)
2010
2011 Applies this handler's filters to the record and returns a true value if the
2012 record is to be processed.
2013
2014
2015.. method:: Handler.flush()
2016
2017 Ensure all logging output has been flushed. This version does nothing and is
2018 intended to be implemented by subclasses.
2019
2020
2021.. method:: Handler.close()
2022
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002023 Tidy up any resources used by the handler. This version does no output but
2024 removes the handler from an internal list of handlers which is closed when
2025 :func:`shutdown` is called. Subclasses should ensure that this gets called
2026 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002027
2028
2029.. method:: Handler.handle(record)
2030
2031 Conditionally emits the specified logging record, depending on filters which may
2032 have been added to the handler. Wraps the actual emission of the record with
2033 acquisition/release of the I/O thread lock.
2034
2035
2036.. method:: Handler.handleError(record)
2037
2038 This method should be called from handlers when an exception is encountered
2039 during an :meth:`emit` call. By default it does nothing, which means that
2040 exceptions get silently ignored. This is what is mostly wanted for a logging
2041 system - most users will not care about errors in the logging system, they are
2042 more interested in application errors. You could, however, replace this with a
2043 custom handler if you wish. The specified record is the one which was being
2044 processed when the exception occurred.
2045
2046
2047.. method:: Handler.format(record)
2048
2049 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2050 default formatter for the module.
2051
2052
2053.. method:: Handler.emit(record)
2054
2055 Do whatever it takes to actually log the specified logging record. This version
2056 is intended to be implemented by subclasses and so raises a
2057 :exc:`NotImplementedError`.
2058
2059
Vinay Sajipd31f3632010-06-29 15:31:15 +00002060.. _stream-handler:
2061
Georg Brandl116aa622007-08-15 14:28:22 +00002062StreamHandler
2063^^^^^^^^^^^^^
2064
2065The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2066sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2067file-like object (or, more precisely, any object which supports :meth:`write`
2068and :meth:`flush` methods).
2069
2070
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002071.. currentmodule:: logging
2072
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002073.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002074
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002075 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002076 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2077 will be used.
2078
2079
Benjamin Petersone41251e2008-04-25 01:59:09 +00002080 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002081
Benjamin Petersone41251e2008-04-25 01:59:09 +00002082 If a formatter is specified, it is used to format the record. The record
2083 is then written to the stream with a trailing newline. If exception
2084 information is present, it is formatted using
2085 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002086
2087
Benjamin Petersone41251e2008-04-25 01:59:09 +00002088 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002089
Benjamin Petersone41251e2008-04-25 01:59:09 +00002090 Flushes the stream by calling its :meth:`flush` method. Note that the
2091 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002092 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002093
2094
Vinay Sajipd31f3632010-06-29 15:31:15 +00002095.. _file-handler:
2096
Georg Brandl116aa622007-08-15 14:28:22 +00002097FileHandler
2098^^^^^^^^^^^
2099
2100The :class:`FileHandler` class, located in the core :mod:`logging` package,
2101sends logging output to a disk file. It inherits the output functionality from
2102:class:`StreamHandler`.
2103
2104
Vinay Sajipd31f3632010-06-29 15:31:15 +00002105.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002106
2107 Returns a new instance of the :class:`FileHandler` class. The specified file is
2108 opened and used as the stream for logging. If *mode* is not specified,
2109 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002110 with that encoding. If *delay* is true, then file opening is deferred until the
2111 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002112
2113
Benjamin Petersone41251e2008-04-25 01:59:09 +00002114 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002115
Benjamin Petersone41251e2008-04-25 01:59:09 +00002116 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002117
2118
Benjamin Petersone41251e2008-04-25 01:59:09 +00002119 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002120
Benjamin Petersone41251e2008-04-25 01:59:09 +00002121 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002122
Vinay Sajipd31f3632010-06-29 15:31:15 +00002123.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002124
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002125NullHandler
2126^^^^^^^^^^^
2127
2128.. versionadded:: 3.1
2129
2130The :class:`NullHandler` class, located in the core :mod:`logging` package,
2131does not do any formatting or output. It is essentially a "no-op" handler
2132for use by library developers.
2133
2134
2135.. class:: NullHandler()
2136
2137 Returns a new instance of the :class:`NullHandler` class.
2138
2139
2140 .. method:: emit(record)
2141
2142 This method does nothing.
2143
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002144See :ref:`library-config` for more information on how to use
2145:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002146
Vinay Sajipd31f3632010-06-29 15:31:15 +00002147.. _watched-file-handler:
2148
Georg Brandl116aa622007-08-15 14:28:22 +00002149WatchedFileHandler
2150^^^^^^^^^^^^^^^^^^
2151
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002152.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002153
Georg Brandl116aa622007-08-15 14:28:22 +00002154The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2155module, is a :class:`FileHandler` which watches the file it is logging to. If
2156the file changes, it is closed and reopened using the file name.
2157
2158A file change can happen because of usage of programs such as *newsyslog* and
2159*logrotate* which perform log file rotation. This handler, intended for use
2160under Unix/Linux, watches the file to see if it has changed since the last emit.
2161(A file is deemed to have changed if its device or inode have changed.) If the
2162file has changed, the old file stream is closed, and the file opened to get a
2163new stream.
2164
2165This handler is not appropriate for use under Windows, because under Windows
2166open log files cannot be moved or renamed - logging opens the files with
2167exclusive locks - and so there is no need for such a handler. Furthermore,
2168*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2169this value.
2170
2171
Christian Heimese7a15bb2008-01-24 16:21:45 +00002172.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002173
2174 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2175 file is opened and used as the stream for logging. If *mode* is not specified,
2176 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002177 with that encoding. If *delay* is true, then file opening is deferred until the
2178 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002179
2180
Benjamin Petersone41251e2008-04-25 01:59:09 +00002181 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002182
Benjamin Petersone41251e2008-04-25 01:59:09 +00002183 Outputs the record to the file, but first checks to see if the file has
2184 changed. If it has, the existing stream is flushed and closed and the
2185 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002186
Vinay Sajipd31f3632010-06-29 15:31:15 +00002187.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002188
2189RotatingFileHandler
2190^^^^^^^^^^^^^^^^^^^
2191
2192The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2193module, supports rotation of disk log files.
2194
2195
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002196.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002197
2198 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2199 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002200 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2201 with that encoding. If *delay* is true, then file opening is deferred until the
2202 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002203
2204 You can use the *maxBytes* and *backupCount* values to allow the file to
2205 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2206 the file is closed and a new file is silently opened for output. Rollover occurs
2207 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2208 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2209 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2210 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2211 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2212 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2213 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2214 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2215 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2216
2217
Benjamin Petersone41251e2008-04-25 01:59:09 +00002218 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002219
Benjamin Petersone41251e2008-04-25 01:59:09 +00002220 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002221
2222
Benjamin Petersone41251e2008-04-25 01:59:09 +00002223 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002224
Benjamin Petersone41251e2008-04-25 01:59:09 +00002225 Outputs the record to the file, catering for rollover as described
2226 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002227
Vinay Sajipd31f3632010-06-29 15:31:15 +00002228.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002229
2230TimedRotatingFileHandler
2231^^^^^^^^^^^^^^^^^^^^^^^^
2232
2233The :class:`TimedRotatingFileHandler` class, located in the
2234:mod:`logging.handlers` module, supports rotation of disk log files at certain
2235timed intervals.
2236
2237
Vinay Sajipd31f3632010-06-29 15:31:15 +00002238.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002239
2240 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2241 specified file is opened and used as the stream for logging. On rotating it also
2242 sets the filename suffix. Rotating happens based on the product of *when* and
2243 *interval*.
2244
2245 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002246 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002247
Christian Heimesb558a2e2008-03-02 22:46:37 +00002248 +----------------+-----------------------+
2249 | Value | Type of interval |
2250 +================+=======================+
2251 | ``'S'`` | Seconds |
2252 +----------------+-----------------------+
2253 | ``'M'`` | Minutes |
2254 +----------------+-----------------------+
2255 | ``'H'`` | Hours |
2256 +----------------+-----------------------+
2257 | ``'D'`` | Days |
2258 +----------------+-----------------------+
2259 | ``'W'`` | Week day (0=Monday) |
2260 +----------------+-----------------------+
2261 | ``'midnight'`` | Roll over at midnight |
2262 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002263
Christian Heimesb558a2e2008-03-02 22:46:37 +00002264 The system will save old log files by appending extensions to the filename.
2265 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002266 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002267 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002268
2269 When computing the next rollover time for the first time (when the handler
2270 is created), the last modification time of an existing log file, or else
2271 the current time, is used to compute when the next rotation will occur.
2272
Georg Brandl0c77a822008-06-10 16:37:50 +00002273 If the *utc* argument is true, times in UTC will be used; otherwise
2274 local time is used.
2275
2276 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002277 will be kept, and if more would be created when rollover occurs, the oldest
2278 one is deleted. The deletion logic uses the interval to determine which
2279 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002280
Vinay Sajipd31f3632010-06-29 15:31:15 +00002281 If *delay* is true, then file opening is deferred until the first call to
2282 :meth:`emit`.
2283
Georg Brandl116aa622007-08-15 14:28:22 +00002284
Benjamin Petersone41251e2008-04-25 01:59:09 +00002285 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002286
Benjamin Petersone41251e2008-04-25 01:59:09 +00002287 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002288
2289
Benjamin Petersone41251e2008-04-25 01:59:09 +00002290 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002291
Benjamin Petersone41251e2008-04-25 01:59:09 +00002292 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002293
2294
Vinay Sajipd31f3632010-06-29 15:31:15 +00002295.. _socket-handler:
2296
Georg Brandl116aa622007-08-15 14:28:22 +00002297SocketHandler
2298^^^^^^^^^^^^^
2299
2300The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2301sends logging output to a network socket. The base class uses a TCP socket.
2302
2303
2304.. class:: SocketHandler(host, port)
2305
2306 Returns a new instance of the :class:`SocketHandler` class intended to
2307 communicate with a remote machine whose address is given by *host* and *port*.
2308
2309
Benjamin Petersone41251e2008-04-25 01:59:09 +00002310 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002311
Benjamin Petersone41251e2008-04-25 01:59:09 +00002312 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002313
2314
Benjamin Petersone41251e2008-04-25 01:59:09 +00002315 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002316
Benjamin Petersone41251e2008-04-25 01:59:09 +00002317 Pickles the record's attribute dictionary and writes it to the socket in
2318 binary format. If there is an error with the socket, silently drops the
2319 packet. If the connection was previously lost, re-establishes the
2320 connection. To unpickle the record at the receiving end into a
2321 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002322
2323
Benjamin Petersone41251e2008-04-25 01:59:09 +00002324 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002325
Benjamin Petersone41251e2008-04-25 01:59:09 +00002326 Handles an error which has occurred during :meth:`emit`. The most likely
2327 cause is a lost connection. Closes the socket so that we can retry on the
2328 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002329
2330
Benjamin Petersone41251e2008-04-25 01:59:09 +00002331 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002332
Benjamin Petersone41251e2008-04-25 01:59:09 +00002333 This is a factory method which allows subclasses to define the precise
2334 type of socket they want. The default implementation creates a TCP socket
2335 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002336
2337
Benjamin Petersone41251e2008-04-25 01:59:09 +00002338 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002339
Benjamin Petersone41251e2008-04-25 01:59:09 +00002340 Pickles the record's attribute dictionary in binary format with a length
2341 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002342
Vinay Sajipd31f3632010-06-29 15:31:15 +00002343 Note that pickles aren't completely secure. If you are concerned about
2344 security, you may want to override this method to implement a more secure
2345 mechanism. For example, you can sign pickles using HMAC and then verify
2346 them on the receiving end, or alternatively you can disable unpickling of
2347 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002348
Benjamin Petersone41251e2008-04-25 01:59:09 +00002349 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002350
Benjamin Petersone41251e2008-04-25 01:59:09 +00002351 Send a pickled string *packet* to the socket. This function allows for
2352 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002353
2354
Vinay Sajipd31f3632010-06-29 15:31:15 +00002355.. _datagram-handler:
2356
Georg Brandl116aa622007-08-15 14:28:22 +00002357DatagramHandler
2358^^^^^^^^^^^^^^^
2359
2360The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2361module, inherits from :class:`SocketHandler` to support sending logging messages
2362over UDP sockets.
2363
2364
2365.. class:: DatagramHandler(host, port)
2366
2367 Returns a new instance of the :class:`DatagramHandler` class intended to
2368 communicate with a remote machine whose address is given by *host* and *port*.
2369
2370
Benjamin Petersone41251e2008-04-25 01:59:09 +00002371 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002372
Benjamin Petersone41251e2008-04-25 01:59:09 +00002373 Pickles the record's attribute dictionary and writes it to the socket in
2374 binary format. If there is an error with the socket, silently drops the
2375 packet. To unpickle the record at the receiving end into a
2376 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002377
2378
Benjamin Petersone41251e2008-04-25 01:59:09 +00002379 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002380
Benjamin Petersone41251e2008-04-25 01:59:09 +00002381 The factory method of :class:`SocketHandler` is here overridden to create
2382 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002383
2384
Benjamin Petersone41251e2008-04-25 01:59:09 +00002385 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002386
Benjamin Petersone41251e2008-04-25 01:59:09 +00002387 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002388
2389
Vinay Sajipd31f3632010-06-29 15:31:15 +00002390.. _syslog-handler:
2391
Georg Brandl116aa622007-08-15 14:28:22 +00002392SysLogHandler
2393^^^^^^^^^^^^^
2394
2395The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2396supports sending logging messages to a remote or local Unix syslog.
2397
2398
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002399.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002400
2401 Returns a new instance of the :class:`SysLogHandler` class intended to
2402 communicate with a remote Unix machine whose address is given by *address* in
2403 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002404 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002405 alternative to providing a ``(host, port)`` tuple is providing an address as a
2406 string, for example "/dev/log". In this case, a Unix domain socket is used to
2407 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002408 :const:`LOG_USER` is used. The type of socket opened depends on the
2409 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2410 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2411 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2412
Vinay Sajip972412d2010-09-23 20:31:24 +00002413 Note that if your server is not listening on UDP port 514,
2414 :class:`SysLogHandler` may appear not to work. In that case, check what
2415 address you should be using for a domain socket - it's system dependent.
2416 For example, on Linux it's usually "/dev/log" but on OS/X it's
2417 "/var/run/syslog". You'll need to check your platform and use the
2418 appropriate address (you may need to do this check at runtime if your
2419 application needs to run on several platforms). On Windows, you pretty
2420 much have to use the UDP option.
2421
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002422 .. versionchanged:: 3.2
2423 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002424
2425
Benjamin Petersone41251e2008-04-25 01:59:09 +00002426 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002427
Benjamin Petersone41251e2008-04-25 01:59:09 +00002428 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002429
2430
Benjamin Petersone41251e2008-04-25 01:59:09 +00002431 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002432
Benjamin Petersone41251e2008-04-25 01:59:09 +00002433 The record is formatted, and then sent to the syslog server. If exception
2434 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002435
2436
Benjamin Petersone41251e2008-04-25 01:59:09 +00002437 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002438
Benjamin Petersone41251e2008-04-25 01:59:09 +00002439 Encodes the facility and priority into an integer. You can pass in strings
2440 or integers - if strings are passed, internal mapping dictionaries are
2441 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002442
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002443 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2444 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002445
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002446 **Priorities**
2447
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002448 +--------------------------+---------------+
2449 | Name (string) | Symbolic value|
2450 +==========================+===============+
2451 | ``alert`` | LOG_ALERT |
2452 +--------------------------+---------------+
2453 | ``crit`` or ``critical`` | LOG_CRIT |
2454 +--------------------------+---------------+
2455 | ``debug`` | LOG_DEBUG |
2456 +--------------------------+---------------+
2457 | ``emerg`` or ``panic`` | LOG_EMERG |
2458 +--------------------------+---------------+
2459 | ``err`` or ``error`` | LOG_ERR |
2460 +--------------------------+---------------+
2461 | ``info`` | LOG_INFO |
2462 +--------------------------+---------------+
2463 | ``notice`` | LOG_NOTICE |
2464 +--------------------------+---------------+
2465 | ``warn`` or ``warning`` | LOG_WARNING |
2466 +--------------------------+---------------+
2467
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002468 **Facilities**
2469
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002470 +---------------+---------------+
2471 | Name (string) | Symbolic value|
2472 +===============+===============+
2473 | ``auth`` | LOG_AUTH |
2474 +---------------+---------------+
2475 | ``authpriv`` | LOG_AUTHPRIV |
2476 +---------------+---------------+
2477 | ``cron`` | LOG_CRON |
2478 +---------------+---------------+
2479 | ``daemon`` | LOG_DAEMON |
2480 +---------------+---------------+
2481 | ``ftp`` | LOG_FTP |
2482 +---------------+---------------+
2483 | ``kern`` | LOG_KERN |
2484 +---------------+---------------+
2485 | ``lpr`` | LOG_LPR |
2486 +---------------+---------------+
2487 | ``mail`` | LOG_MAIL |
2488 +---------------+---------------+
2489 | ``news`` | LOG_NEWS |
2490 +---------------+---------------+
2491 | ``syslog`` | LOG_SYSLOG |
2492 +---------------+---------------+
2493 | ``user`` | LOG_USER |
2494 +---------------+---------------+
2495 | ``uucp`` | LOG_UUCP |
2496 +---------------+---------------+
2497 | ``local0`` | LOG_LOCAL0 |
2498 +---------------+---------------+
2499 | ``local1`` | LOG_LOCAL1 |
2500 +---------------+---------------+
2501 | ``local2`` | LOG_LOCAL2 |
2502 +---------------+---------------+
2503 | ``local3`` | LOG_LOCAL3 |
2504 +---------------+---------------+
2505 | ``local4`` | LOG_LOCAL4 |
2506 +---------------+---------------+
2507 | ``local5`` | LOG_LOCAL5 |
2508 +---------------+---------------+
2509 | ``local6`` | LOG_LOCAL6 |
2510 +---------------+---------------+
2511 | ``local7`` | LOG_LOCAL7 |
2512 +---------------+---------------+
2513
2514 .. method:: mapPriority(levelname)
2515
2516 Maps a logging level name to a syslog priority name.
2517 You may need to override this if you are using custom levels, or
2518 if the default algorithm is not suitable for your needs. The
2519 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2520 ``CRITICAL`` to the equivalent syslog names, and all other level
2521 names to "warning".
2522
2523.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002524
2525NTEventLogHandler
2526^^^^^^^^^^^^^^^^^
2527
2528The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2529module, supports sending logging messages to a local Windows NT, Windows 2000 or
2530Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2531extensions for Python installed.
2532
2533
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002534.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002535
2536 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2537 used to define the application name as it appears in the event log. An
2538 appropriate registry entry is created using this name. The *dllname* should give
2539 the fully qualified pathname of a .dll or .exe which contains message
2540 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2541 - this is installed with the Win32 extensions and contains some basic
2542 placeholder message definitions. Note that use of these placeholders will make
2543 your event logs big, as the entire message source is held in the log. If you
2544 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2545 contains the message definitions you want to use in the event log). The
2546 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2547 defaults to ``'Application'``.
2548
2549
Benjamin Petersone41251e2008-04-25 01:59:09 +00002550 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002551
Benjamin Petersone41251e2008-04-25 01:59:09 +00002552 At this point, you can remove the application name from the registry as a
2553 source of event log entries. However, if you do this, you will not be able
2554 to see the events as you intended in the Event Log Viewer - it needs to be
2555 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002556 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002557
2558
Benjamin Petersone41251e2008-04-25 01:59:09 +00002559 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002560
Benjamin Petersone41251e2008-04-25 01:59:09 +00002561 Determines the message ID, event category and event type, and then logs
2562 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002563
2564
Benjamin Petersone41251e2008-04-25 01:59:09 +00002565 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002566
Benjamin Petersone41251e2008-04-25 01:59:09 +00002567 Returns the event category for the record. Override this if you want to
2568 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002569
2570
Benjamin Petersone41251e2008-04-25 01:59:09 +00002571 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002572
Benjamin Petersone41251e2008-04-25 01:59:09 +00002573 Returns the event type for the record. Override this if you want to
2574 specify your own types. This version does a mapping using the handler's
2575 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2576 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2577 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2578 your own levels, you will either need to override this method or place a
2579 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002580
2581
Benjamin Petersone41251e2008-04-25 01:59:09 +00002582 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002583
Benjamin Petersone41251e2008-04-25 01:59:09 +00002584 Returns the message ID for the record. If you are using your own messages,
2585 you could do this by having the *msg* passed to the logger being an ID
2586 rather than a format string. Then, in here, you could use a dictionary
2587 lookup to get the message ID. This version returns 1, which is the base
2588 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002589
Vinay Sajipd31f3632010-06-29 15:31:15 +00002590.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002591
2592SMTPHandler
2593^^^^^^^^^^^
2594
2595The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2596supports sending logging messages to an email address via SMTP.
2597
2598
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002599.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002600
2601 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2602 initialized with the from and to addresses and subject line of the email. The
2603 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2604 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2605 the standard SMTP port is used. If your SMTP server requires authentication, you
2606 can specify a (username, password) tuple for the *credentials* argument.
2607
Georg Brandl116aa622007-08-15 14:28:22 +00002608
Benjamin Petersone41251e2008-04-25 01:59:09 +00002609 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002610
Benjamin Petersone41251e2008-04-25 01:59:09 +00002611 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002612
2613
Benjamin Petersone41251e2008-04-25 01:59:09 +00002614 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002615
Benjamin Petersone41251e2008-04-25 01:59:09 +00002616 If you want to specify a subject line which is record-dependent, override
2617 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002618
Vinay Sajipd31f3632010-06-29 15:31:15 +00002619.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002620
2621MemoryHandler
2622^^^^^^^^^^^^^
2623
2624The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2625supports buffering of logging records in memory, periodically flushing them to a
2626:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2627event of a certain severity or greater is seen.
2628
2629:class:`MemoryHandler` is a subclass of the more general
2630:class:`BufferingHandler`, which is an abstract class. This buffers logging
2631records in memory. Whenever each record is added to the buffer, a check is made
2632by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2633should, then :meth:`flush` is expected to do the needful.
2634
2635
2636.. class:: BufferingHandler(capacity)
2637
2638 Initializes the handler with a buffer of the specified capacity.
2639
2640
Benjamin Petersone41251e2008-04-25 01:59:09 +00002641 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002642
Benjamin Petersone41251e2008-04-25 01:59:09 +00002643 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2644 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002645
2646
Benjamin Petersone41251e2008-04-25 01:59:09 +00002647 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002648
Benjamin Petersone41251e2008-04-25 01:59:09 +00002649 You can override this to implement custom flushing behavior. This version
2650 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002651
2652
Benjamin Petersone41251e2008-04-25 01:59:09 +00002653 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002654
Benjamin Petersone41251e2008-04-25 01:59:09 +00002655 Returns true if the buffer is up to capacity. This method can be
2656 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002657
2658
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002659.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002660
2661 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2662 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2663 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2664 set using :meth:`setTarget` before this handler does anything useful.
2665
2666
Benjamin Petersone41251e2008-04-25 01:59:09 +00002667 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002668
Benjamin Petersone41251e2008-04-25 01:59:09 +00002669 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2670 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002671
2672
Benjamin Petersone41251e2008-04-25 01:59:09 +00002673 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002674
Benjamin Petersone41251e2008-04-25 01:59:09 +00002675 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00002676 records to the target, if there is one. The buffer is also cleared when
2677 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002678
2679
Benjamin Petersone41251e2008-04-25 01:59:09 +00002680 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002681
Benjamin Petersone41251e2008-04-25 01:59:09 +00002682 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002683
2684
Benjamin Petersone41251e2008-04-25 01:59:09 +00002685 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002686
Benjamin Petersone41251e2008-04-25 01:59:09 +00002687 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002688
2689
Vinay Sajipd31f3632010-06-29 15:31:15 +00002690.. _http-handler:
2691
Georg Brandl116aa622007-08-15 14:28:22 +00002692HTTPHandler
2693^^^^^^^^^^^
2694
2695The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2696supports sending logging messages to a Web server, using either ``GET`` or
2697``POST`` semantics.
2698
2699
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002700.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002701
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002702 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
2703 of the form ``host:port``, should you need to use a specific port number.
2704 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
2705 connection will be used. If *credentials* is specified, it should be a
2706 2-tuple consisting of userid and password, which will be placed in an HTTP
2707 'Authorization' header using Basic authentication. If you specify
2708 credentials, you should also specify secure=True so that your userid and
2709 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00002710
2711
Benjamin Petersone41251e2008-04-25 01:59:09 +00002712 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002713
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002714 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002715
2716
Vinay Sajip121a1c42010-09-08 10:46:15 +00002717.. _queue-handler:
2718
2719
2720QueueHandler
2721^^^^^^^^^^^^
2722
2723The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
2724supports sending logging messages to a queue, such as those implemented in the
2725:mod:`queue` or :mod:`multiprocessing` modules.
2726
Vinay Sajip0637d492010-09-23 08:15:54 +00002727Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
2728to let handlers do their work on a separate thread from the one which does the
2729logging. This is important in Web applications and also other service
2730applications where threads servicing clients need to respond as quickly as
2731possible, while any potentially slow operations (such as sending an email via
2732:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002733
2734.. class:: QueueHandler(queue)
2735
2736 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00002737 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00002738 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00002739 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002740
2741
2742 .. method:: emit(record)
2743
Vinay Sajip0258ce82010-09-22 20:34:53 +00002744 Enqueues the result of preparing the LogRecord.
2745
2746 .. method:: prepare(record)
2747
2748 Prepares a record for queuing. The object returned by this
2749 method is enqueued.
2750
2751 The base implementation formats the record to merge the message
2752 and arguments, and removes unpickleable items from the record
2753 in-place.
2754
2755 You might want to override this method if you want to convert
2756 the record to a dict or JSON string, or send a modified copy
2757 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002758
2759 .. method:: enqueue(record)
2760
2761 Enqueues the record on the queue using ``put_nowait()``; you may
2762 want to override this if you want to use blocking behaviour, or a
2763 timeout, or a customised queue implementation.
2764
2765
2766.. versionadded:: 3.2
2767
2768The :class:`QueueHandler` class was not present in previous versions.
2769
Vinay Sajip0637d492010-09-23 08:15:54 +00002770.. queue-listener:
2771
2772QueueListener
2773^^^^^^^^^^^^^
2774
2775The :class:`QueueListener` class, located in the :mod:`logging.handlers`
2776module, supports receiving logging messages from a queue, such as those
2777implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
2778messages are received from a queue in an internal thread and passed, on
2779the same thread, to one or more handlers for processing.
2780
2781Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
2782to let handlers do their work on a separate thread from the one which does the
2783logging. This is important in Web applications and also other service
2784applications where threads servicing clients need to respond as quickly as
2785possible, while any potentially slow operations (such as sending an email via
2786:class:`SMTPHandler`) are done on a separate thread.
2787
2788.. class:: QueueListener(queue, *handlers)
2789
2790 Returns a new instance of the :class:`QueueListener` class. The instance is
2791 initialized with the queue to send messages to and a list of handlers which
2792 will handle entries placed on the queue. The queue can be any queue-
2793 like object; it's passed as-is to the :meth:`dequeue` method, which needs
2794 to know how to get messages from it.
2795
2796 .. method:: dequeue(block)
2797
2798 Dequeues a record and return it, optionally blocking.
2799
2800 The base implementation uses ``get()``. You may want to override this
2801 method if you want to use timeouts or work with custom queue
2802 implementations.
2803
2804 .. method:: prepare(record)
2805
2806 Prepare a record for handling.
2807
2808 This implementation just returns the passed-in record. You may want to
2809 override this method if you need to do any custom marshalling or
2810 manipulation of the record before passing it to the handlers.
2811
2812 .. method:: handle(record)
2813
2814 Handle a record.
2815
2816 This just loops through the handlers offering them the record
2817 to handle. The actual object passed to the handlers is that which
2818 is returned from :meth:`prepare`.
2819
2820 .. method:: start()
2821
2822 Starts the listener.
2823
2824 This starts up a background thread to monitor the queue for
2825 LogRecords to process.
2826
2827 .. method:: stop()
2828
2829 Stops the listener.
2830
2831 This asks the thread to terminate, and then waits for it to do so.
2832 Note that if you don't call this before your application exits, there
2833 may be some records still left on the queue, which won't be processed.
2834
2835.. versionadded:: 3.2
2836
2837The :class:`QueueListener` class was not present in previous versions.
2838
Vinay Sajip63891ed2010-09-13 20:02:39 +00002839.. _zeromq-handlers:
2840
Vinay Sajip0637d492010-09-23 08:15:54 +00002841Subclassing QueueHandler
2842^^^^^^^^^^^^^^^^^^^^^^^^
2843
Vinay Sajip63891ed2010-09-13 20:02:39 +00002844You can use a :class:`QueueHandler` subclass to send messages to other kinds
2845of queues, for example a ZeroMQ "publish" socket. In the example below,the
2846socket is created separately and passed to the handler (as its 'queue')::
2847
2848 import zmq # using pyzmq, the Python binding for ZeroMQ
2849 import json # for serializing records portably
2850
2851 ctx = zmq.Context()
2852 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
2853 sock.bind('tcp://*:5556') # or wherever
2854
2855 class ZeroMQSocketHandler(QueueHandler):
2856 def enqueue(self, record):
2857 data = json.dumps(record.__dict__)
2858 self.queue.send(data)
2859
Vinay Sajip0055c422010-09-14 09:42:39 +00002860 handler = ZeroMQSocketHandler(sock)
2861
2862
Vinay Sajip63891ed2010-09-13 20:02:39 +00002863Of course there are other ways of organizing this, for example passing in the
2864data needed by the handler to create the socket::
2865
2866 class ZeroMQSocketHandler(QueueHandler):
2867 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
2868 self.ctx = ctx or zmq.Context()
2869 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00002870 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00002871 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00002872
2873 def enqueue(self, record):
2874 data = json.dumps(record.__dict__)
2875 self.queue.send(data)
2876
Vinay Sajipde726922010-09-14 06:59:24 +00002877 def close(self):
2878 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00002879
Vinay Sajip0637d492010-09-23 08:15:54 +00002880Subclassing QueueListener
2881^^^^^^^^^^^^^^^^^^^^^^^^^
2882
2883You can also subclass :class:`QueueListener` to get messages from other kinds
2884of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
2885
2886 class ZeroMQSocketListener(QueueListener):
2887 def __init__(self, uri, *handlers, **kwargs):
2888 self.ctx = kwargs.get('ctx') or zmq.Context()
2889 socket = zmq.Socket(self.ctx, zmq.SUB)
2890 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
2891 socket.connect(uri)
2892
2893 def dequeue(self):
2894 msg = self.queue.recv()
2895 return logging.makeLogRecord(json.loads(msg))
2896
Christian Heimes8b0facf2007-12-04 19:30:01 +00002897.. _formatter-objects:
2898
Georg Brandl116aa622007-08-15 14:28:22 +00002899Formatter Objects
2900-----------------
2901
Benjamin Peterson75edad02009-01-01 15:05:06 +00002902.. currentmodule:: logging
2903
Georg Brandl116aa622007-08-15 14:28:22 +00002904:class:`Formatter`\ s have the following attributes and methods. They are
2905responsible for converting a :class:`LogRecord` to (usually) a string which can
2906be interpreted by either a human or an external system. The base
2907:class:`Formatter` allows a formatting string to be specified. If none is
2908supplied, the default value of ``'%(message)s'`` is used.
2909
2910A Formatter can be initialized with a format string which makes use of knowledge
2911of the :class:`LogRecord` attributes - such as the default value mentioned above
2912making use of the fact that the user's message and arguments are pre-formatted
2913into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002914standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00002915for more information on string formatting.
2916
2917Currently, the useful mapping keys in a :class:`LogRecord` are:
2918
2919+-------------------------+-----------------------------------------------+
2920| Format | Description |
2921+=========================+===============================================+
2922| ``%(name)s`` | Name of the logger (logging channel). |
2923+-------------------------+-----------------------------------------------+
2924| ``%(levelno)s`` | Numeric logging level for the message |
2925| | (:const:`DEBUG`, :const:`INFO`, |
2926| | :const:`WARNING`, :const:`ERROR`, |
2927| | :const:`CRITICAL`). |
2928+-------------------------+-----------------------------------------------+
2929| ``%(levelname)s`` | Text logging level for the message |
2930| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2931| | ``'ERROR'``, ``'CRITICAL'``). |
2932+-------------------------+-----------------------------------------------+
2933| ``%(pathname)s`` | Full pathname of the source file where the |
2934| | logging call was issued (if available). |
2935+-------------------------+-----------------------------------------------+
2936| ``%(filename)s`` | Filename portion of pathname. |
2937+-------------------------+-----------------------------------------------+
2938| ``%(module)s`` | Module (name portion of filename). |
2939+-------------------------+-----------------------------------------------+
2940| ``%(funcName)s`` | Name of function containing the logging call. |
2941+-------------------------+-----------------------------------------------+
2942| ``%(lineno)d`` | Source line number where the logging call was |
2943| | issued (if available). |
2944+-------------------------+-----------------------------------------------+
2945| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2946| | (as returned by :func:`time.time`). |
2947+-------------------------+-----------------------------------------------+
2948| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2949| | created, relative to the time the logging |
2950| | module was loaded. |
2951+-------------------------+-----------------------------------------------+
2952| ``%(asctime)s`` | Human-readable time when the |
2953| | :class:`LogRecord` was created. By default |
2954| | this is of the form "2003-07-08 16:49:45,896" |
2955| | (the numbers after the comma are millisecond |
2956| | portion of the time). |
2957+-------------------------+-----------------------------------------------+
2958| ``%(msecs)d`` | Millisecond portion of the time when the |
2959| | :class:`LogRecord` was created. |
2960+-------------------------+-----------------------------------------------+
2961| ``%(thread)d`` | Thread ID (if available). |
2962+-------------------------+-----------------------------------------------+
2963| ``%(threadName)s`` | Thread name (if available). |
2964+-------------------------+-----------------------------------------------+
2965| ``%(process)d`` | Process ID (if available). |
2966+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00002967| ``%(processName)s`` | Process name (if available). |
2968+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002969| ``%(message)s`` | The logged message, computed as ``msg % |
2970| | args``. |
2971+-------------------------+-----------------------------------------------+
2972
Georg Brandl116aa622007-08-15 14:28:22 +00002973
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002974.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002975
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002976 Returns a new instance of the :class:`Formatter` class. The instance is
2977 initialized with a format string for the message as a whole, as well as a
2978 format string for the date/time portion of a message. If no *fmt* is
2979 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
2980 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00002981
Benjamin Petersone41251e2008-04-25 01:59:09 +00002982 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002983
Benjamin Petersone41251e2008-04-25 01:59:09 +00002984 The record's attribute dictionary is used as the operand to a string
2985 formatting operation. Returns the resulting string. Before formatting the
2986 dictionary, a couple of preparatory steps are carried out. The *message*
2987 attribute of the record is computed using *msg* % *args*. If the
2988 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2989 to format the event time. If there is exception information, it is
2990 formatted using :meth:`formatException` and appended to the message. Note
2991 that the formatted exception information is cached in attribute
2992 *exc_text*. This is useful because the exception information can be
2993 pickled and sent across the wire, but you should be careful if you have
2994 more than one :class:`Formatter` subclass which customizes the formatting
2995 of exception information. In this case, you will have to clear the cached
2996 value after a formatter has done its formatting, so that the next
2997 formatter to handle the event doesn't use the cached value but
2998 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00002999
3000
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003001 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003002
Benjamin Petersone41251e2008-04-25 01:59:09 +00003003 This method should be called from :meth:`format` by a formatter which
3004 wants to make use of a formatted time. This method can be overridden in
3005 formatters to provide for any specific requirement, but the basic behavior
3006 is as follows: if *datefmt* (a string) is specified, it is used with
3007 :func:`time.strftime` to format the creation time of the
3008 record. Otherwise, the ISO8601 format is used. The resulting string is
3009 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003010
3011
Benjamin Petersone41251e2008-04-25 01:59:09 +00003012 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003013
Benjamin Petersone41251e2008-04-25 01:59:09 +00003014 Formats the specified exception information (a standard exception tuple as
3015 returned by :func:`sys.exc_info`) as a string. This default implementation
3016 just uses :func:`traceback.print_exception`. The resulting string is
3017 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003018
Vinay Sajipd31f3632010-06-29 15:31:15 +00003019.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003020
3021Filter Objects
3022--------------
3023
3024:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
3025more sophisticated filtering than is provided by levels. The base filter class
3026only allows events which are below a certain point in the logger hierarchy. For
3027example, a filter initialized with "A.B" will allow events logged by loggers
3028"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
3029initialized with the empty string, all events are passed.
3030
3031
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003032.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003033
3034 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3035 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003036 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003037
3038
Benjamin Petersone41251e2008-04-25 01:59:09 +00003039 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003040
Benjamin Petersone41251e2008-04-25 01:59:09 +00003041 Is the specified record to be logged? Returns zero for no, nonzero for
3042 yes. If deemed appropriate, the record may be modified in-place by this
3043 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003044
Vinay Sajip81010212010-08-19 19:17:41 +00003045Note that filters attached to handlers are consulted whenever an event is
3046emitted by the handler, whereas filters attached to loggers are consulted
3047whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3048etc.) This means that events which have been generated by descendant loggers
3049will not be filtered by a logger's filter setting, unless the filter has also
3050been applied to those descendant loggers.
3051
Vinay Sajipac007992010-09-17 12:45:26 +00003052Other uses for filters
3053^^^^^^^^^^^^^^^^^^^^^^
3054
3055Although filters are used primarily to filter records based on more
3056sophisticated criteria than levels, they get to see every record which is
3057processed by the handler or logger they're attached to: this can be useful if
3058you want to do things like counting how many records were processed by a
3059particular logger or handler, or adding, changing or removing attributes in
3060the LogRecord being processed. Obviously changing the LogRecord needs to be
3061done with some care, but it does allow the injection of contextual information
3062into logs (see :ref:`filters-contextual`).
3063
Vinay Sajipd31f3632010-06-29 15:31:15 +00003064.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003065
3066LogRecord Objects
3067-----------------
3068
Vinay Sajip4039aff2010-09-11 10:25:28 +00003069:class:`LogRecord` instances are created automatically by the :class:`Logger`
3070every time something is logged, and can be created manually via
3071:func:`makeLogRecord` (for example, from a pickled event received over the
3072wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003073
3074
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003075.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003076
Vinay Sajip4039aff2010-09-11 10:25:28 +00003077 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003078
Vinay Sajip4039aff2010-09-11 10:25:28 +00003079 The primary information is passed in :attr:`msg` and :attr:`args`, which
3080 are combined using ``msg % args`` to create the :attr:`message` field of the
3081 record.
3082
3083 .. attribute:: args
3084
3085 Tuple of arguments to be used in formatting :attr:`msg`.
3086
3087 .. attribute:: exc_info
3088
3089 Exception tuple (à la `sys.exc_info`) or `None` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003090 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003091
3092 .. attribute:: func
3093
3094 Name of the function of origin (i.e. in which the logging call was made).
3095
3096 .. attribute:: lineno
3097
3098 Line number in the source file of origin.
3099
3100 .. attribute:: lvl
3101
3102 Numeric logging level.
3103
3104 .. attribute:: message
3105
3106 Bound to the result of :meth:`getMessage` when
3107 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3108
3109 .. attribute:: msg
3110
3111 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3112 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3113
3114 .. attribute:: name
3115
3116 Name of the logger that emitted the record.
3117
3118 .. attribute:: pathname
3119
3120 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003121
Benjamin Petersone41251e2008-04-25 01:59:09 +00003122 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003123
Benjamin Petersone41251e2008-04-25 01:59:09 +00003124 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003125 user-supplied arguments with the message. If the user-supplied message
3126 argument to the logging call is not a string, :func:`str` is called on it to
3127 convert it to a string. This allows use of user-defined classes as
3128 messages, whose ``__str__`` method can return the actual format string to
3129 be used.
3130
3131 .. versionchanged:: 2.5
3132 *func* was added.
Benjamin Petersone41251e2008-04-25 01:59:09 +00003133
Vinay Sajipd31f3632010-06-29 15:31:15 +00003134.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003135
Christian Heimes04c420f2008-01-18 18:40:46 +00003136LoggerAdapter Objects
3137---------------------
3138
Christian Heimes04c420f2008-01-18 18:40:46 +00003139:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003140information into logging calls. For a usage example , see the section on
3141`adding contextual information to your logging output`__.
3142
3143__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00003144
3145.. class:: LoggerAdapter(logger, extra)
3146
3147 Returns an instance of :class:`LoggerAdapter` initialized with an
3148 underlying :class:`Logger` instance and a dict-like object.
3149
Benjamin Petersone41251e2008-04-25 01:59:09 +00003150 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003151
Benjamin Petersone41251e2008-04-25 01:59:09 +00003152 Modifies the message and/or keyword arguments passed to a logging call in
3153 order to insert contextual information. This implementation takes the object
3154 passed as *extra* to the constructor and adds it to *kwargs* using key
3155 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3156 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003157
Vinay Sajipc84f0162010-09-21 11:25:39 +00003158In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003159methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003160:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3161:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3162:meth:`hasHandlers`. These methods have the same signatures as their
3163counterparts in :class:`Logger`, so you can use the two types of instances
3164interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003165
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003166.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003167 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3168 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3169 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003170
Georg Brandl116aa622007-08-15 14:28:22 +00003171
3172Thread Safety
3173-------------
3174
3175The logging module is intended to be thread-safe without any special work
3176needing to be done by its clients. It achieves this though using threading
3177locks; there is one lock to serialize access to the module's shared data, and
3178each handler also creates a lock to serialize access to its underlying I/O.
3179
Benjamin Petersond23f8222009-04-05 19:13:16 +00003180If you are implementing asynchronous signal handlers using the :mod:`signal`
3181module, you may not be able to use logging from within such handlers. This is
3182because lock implementations in the :mod:`threading` module are not always
3183re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003184
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003185
3186Integration with the warnings module
3187------------------------------------
3188
3189The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3190with the :mod:`warnings` module.
3191
3192.. function:: captureWarnings(capture)
3193
3194 This function is used to turn the capture of warnings by logging on and
3195 off.
3196
3197 If `capture` is `True`, warnings issued by the :mod:`warnings` module
3198 will be redirected to the logging system. Specifically, a warning will be
3199 formatted using :func:`warnings.formatwarning` and the resulting string
3200 logged to a logger named "py.warnings" with a severity of `WARNING`.
3201
3202 If `capture` is `False`, the redirection of warnings to the logging system
3203 will stop, and warnings will be redirected to their original destinations
3204 (i.e. those in effect before `captureWarnings(True)` was called).
3205
3206
Georg Brandl116aa622007-08-15 14:28:22 +00003207Configuration
3208-------------
3209
3210
3211.. _logging-config-api:
3212
3213Configuration functions
3214^^^^^^^^^^^^^^^^^^^^^^^
3215
Georg Brandl116aa622007-08-15 14:28:22 +00003216The following functions configure the logging module. They are located in the
3217:mod:`logging.config` module. Their use is optional --- you can configure the
3218logging module using these functions or by making calls to the main API (defined
3219in :mod:`logging` itself) and defining handlers which are declared either in
3220:mod:`logging` or :mod:`logging.handlers`.
3221
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003222.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003223
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003224 Takes the logging configuration from a dictionary. The contents of
3225 this dictionary are described in :ref:`logging-config-dictschema`
3226 below.
3227
3228 If an error is encountered during configuration, this function will
3229 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3230 or :exc:`ImportError` with a suitably descriptive message. The
3231 following is a (possibly incomplete) list of conditions which will
3232 raise an error:
3233
3234 * A ``level`` which is not a string or which is a string not
3235 corresponding to an actual logging level.
3236 * A ``propagate`` value which is not a boolean.
3237 * An id which does not have a corresponding destination.
3238 * A non-existent handler id found during an incremental call.
3239 * An invalid logger name.
3240 * Inability to resolve to an internal or external object.
3241
3242 Parsing is performed by the :class:`DictConfigurator` class, whose
3243 constructor is passed the dictionary used for configuration, and
3244 has a :meth:`configure` method. The :mod:`logging.config` module
3245 has a callable attribute :attr:`dictConfigClass`
3246 which is initially set to :class:`DictConfigurator`.
3247 You can replace the value of :attr:`dictConfigClass` with a
3248 suitable implementation of your own.
3249
3250 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3251 the specified dictionary, and then calls the :meth:`configure` method on
3252 the returned object to put the configuration into effect::
3253
3254 def dictConfig(config):
3255 dictConfigClass(config).configure()
3256
3257 For example, a subclass of :class:`DictConfigurator` could call
3258 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3259 set up custom prefixes which would be usable in the subsequent
3260 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3261 this new subclass, and then :func:`dictConfig` could be called exactly as
3262 in the default, uncustomized state.
3263
3264.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003265
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003266 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003267 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003268 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003269 configurations (if the developer provides a mechanism to present the choices
3270 and load the chosen configuration). Defaults to be passed to the ConfigParser
3271 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003272
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003273
3274.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003275
3276 Starts up a socket server on the specified port, and listens for new
3277 configurations. If no port is specified, the module's default
3278 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3279 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3280 :class:`Thread` instance on which you can call :meth:`start` to start the
3281 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003282 call :func:`stopListening`.
3283
3284 To send a configuration to the socket, read in the configuration file and
3285 send it to the socket as a string of bytes preceded by a four-byte length
3286 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003287
3288
3289.. function:: stopListening()
3290
Christian Heimes8b0facf2007-12-04 19:30:01 +00003291 Stops the listening server which was created with a call to :func:`listen`.
3292 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003293 :func:`listen`.
3294
3295
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003296.. _logging-config-dictschema:
3297
3298Configuration dictionary schema
3299^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3300
3301Describing a logging configuration requires listing the various
3302objects to create and the connections between them; for example, you
3303may create a handler named "console" and then say that the logger
3304named "startup" will send its messages to the "console" handler.
3305These objects aren't limited to those provided by the :mod:`logging`
3306module because you might write your own formatter or handler class.
3307The parameters to these classes may also need to include external
3308objects such as ``sys.stderr``. The syntax for describing these
3309objects and connections is defined in :ref:`logging-config-dict-connections`
3310below.
3311
3312Dictionary Schema Details
3313"""""""""""""""""""""""""
3314
3315The dictionary passed to :func:`dictConfig` must contain the following
3316keys:
3317
3318* `version` - to be set to an integer value representing the schema
3319 version. The only valid value at present is 1, but having this key
3320 allows the schema to evolve while still preserving backwards
3321 compatibility.
3322
3323All other keys are optional, but if present they will be interpreted
3324as described below. In all cases below where a 'configuring dict' is
3325mentioned, it will be checked for the special ``'()'`` key to see if a
3326custom instantiation is required. If so, the mechanism described in
3327:ref:`logging-config-dict-userdef` below is used to create an instance;
3328otherwise, the context is used to determine what to instantiate.
3329
3330* `formatters` - the corresponding value will be a dict in which each
3331 key is a formatter id and each value is a dict describing how to
3332 configure the corresponding Formatter instance.
3333
3334 The configuring dict is searched for keys ``format`` and ``datefmt``
3335 (with defaults of ``None``) and these are used to construct a
3336 :class:`logging.Formatter` instance.
3337
3338* `filters` - the corresponding value will be a dict in which each key
3339 is a filter id and each value is a dict describing how to configure
3340 the corresponding Filter instance.
3341
3342 The configuring dict is searched for the key ``name`` (defaulting to the
3343 empty string) and this is used to construct a :class:`logging.Filter`
3344 instance.
3345
3346* `handlers` - the corresponding value will be a dict in which each
3347 key is a handler id and each value is a dict describing how to
3348 configure the corresponding Handler instance.
3349
3350 The configuring dict is searched for the following keys:
3351
3352 * ``class`` (mandatory). This is the fully qualified name of the
3353 handler class.
3354
3355 * ``level`` (optional). The level of the handler.
3356
3357 * ``formatter`` (optional). The id of the formatter for this
3358 handler.
3359
3360 * ``filters`` (optional). A list of ids of the filters for this
3361 handler.
3362
3363 All *other* keys are passed through as keyword arguments to the
3364 handler's constructor. For example, given the snippet::
3365
3366 handlers:
3367 console:
3368 class : logging.StreamHandler
3369 formatter: brief
3370 level : INFO
3371 filters: [allow_foo]
3372 stream : ext://sys.stdout
3373 file:
3374 class : logging.handlers.RotatingFileHandler
3375 formatter: precise
3376 filename: logconfig.log
3377 maxBytes: 1024
3378 backupCount: 3
3379
3380 the handler with id ``console`` is instantiated as a
3381 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3382 stream. The handler with id ``file`` is instantiated as a
3383 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3384 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3385
3386* `loggers` - the corresponding value will be a dict in which each key
3387 is a logger name and each value is a dict describing how to
3388 configure the corresponding Logger instance.
3389
3390 The configuring dict is searched for the following keys:
3391
3392 * ``level`` (optional). The level of the logger.
3393
3394 * ``propagate`` (optional). The propagation setting of the logger.
3395
3396 * ``filters`` (optional). A list of ids of the filters for this
3397 logger.
3398
3399 * ``handlers`` (optional). A list of ids of the handlers for this
3400 logger.
3401
3402 The specified loggers will be configured according to the level,
3403 propagation, filters and handlers specified.
3404
3405* `root` - this will be the configuration for the root logger.
3406 Processing of the configuration will be as for any logger, except
3407 that the ``propagate`` setting will not be applicable.
3408
3409* `incremental` - whether the configuration is to be interpreted as
3410 incremental to the existing configuration. This value defaults to
3411 ``False``, which means that the specified configuration replaces the
3412 existing configuration with the same semantics as used by the
3413 existing :func:`fileConfig` API.
3414
3415 If the specified value is ``True``, the configuration is processed
3416 as described in the section on :ref:`logging-config-dict-incremental`.
3417
3418* `disable_existing_loggers` - whether any existing loggers are to be
3419 disabled. This setting mirrors the parameter of the same name in
3420 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
3421 This value is ignored if `incremental` is ``True``.
3422
3423.. _logging-config-dict-incremental:
3424
3425Incremental Configuration
3426"""""""""""""""""""""""""
3427
3428It is difficult to provide complete flexibility for incremental
3429configuration. For example, because objects such as filters
3430and formatters are anonymous, once a configuration is set up, it is
3431not possible to refer to such anonymous objects when augmenting a
3432configuration.
3433
3434Furthermore, there is not a compelling case for arbitrarily altering
3435the object graph of loggers, handlers, filters, formatters at
3436run-time, once a configuration is set up; the verbosity of loggers and
3437handlers can be controlled just by setting levels (and, in the case of
3438loggers, propagation flags). Changing the object graph arbitrarily in
3439a safe way is problematic in a multi-threaded environment; while not
3440impossible, the benefits are not worth the complexity it adds to the
3441implementation.
3442
3443Thus, when the ``incremental`` key of a configuration dict is present
3444and is ``True``, the system will completely ignore any ``formatters`` and
3445``filters`` entries, and process only the ``level``
3446settings in the ``handlers`` entries, and the ``level`` and
3447``propagate`` settings in the ``loggers`` and ``root`` entries.
3448
3449Using a value in the configuration dict lets configurations to be sent
3450over the wire as pickled dicts to a socket listener. Thus, the logging
3451verbosity of a long-running application can be altered over time with
3452no need to stop and restart the application.
3453
3454.. _logging-config-dict-connections:
3455
3456Object connections
3457""""""""""""""""""
3458
3459The schema describes a set of logging objects - loggers,
3460handlers, formatters, filters - which are connected to each other in
3461an object graph. Thus, the schema needs to represent connections
3462between the objects. For example, say that, once configured, a
3463particular logger has attached to it a particular handler. For the
3464purposes of this discussion, we can say that the logger represents the
3465source, and the handler the destination, of a connection between the
3466two. Of course in the configured objects this is represented by the
3467logger holding a reference to the handler. In the configuration dict,
3468this is done by giving each destination object an id which identifies
3469it unambiguously, and then using the id in the source object's
3470configuration to indicate that a connection exists between the source
3471and the destination object with that id.
3472
3473So, for example, consider the following YAML snippet::
3474
3475 formatters:
3476 brief:
3477 # configuration for formatter with id 'brief' goes here
3478 precise:
3479 # configuration for formatter with id 'precise' goes here
3480 handlers:
3481 h1: #This is an id
3482 # configuration of handler with id 'h1' goes here
3483 formatter: brief
3484 h2: #This is another id
3485 # configuration of handler with id 'h2' goes here
3486 formatter: precise
3487 loggers:
3488 foo.bar.baz:
3489 # other configuration for logger 'foo.bar.baz'
3490 handlers: [h1, h2]
3491
3492(Note: YAML used here because it's a little more readable than the
3493equivalent Python source form for the dictionary.)
3494
3495The ids for loggers are the logger names which would be used
3496programmatically to obtain a reference to those loggers, e.g.
3497``foo.bar.baz``. The ids for Formatters and Filters can be any string
3498value (such as ``brief``, ``precise`` above) and they are transient,
3499in that they are only meaningful for processing the configuration
3500dictionary and used to determine connections between objects, and are
3501not persisted anywhere when the configuration call is complete.
3502
3503The above snippet indicates that logger named ``foo.bar.baz`` should
3504have two handlers attached to it, which are described by the handler
3505ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3506``brief``, and the formatter for ``h2`` is that described by id
3507``precise``.
3508
3509
3510.. _logging-config-dict-userdef:
3511
3512User-defined objects
3513""""""""""""""""""""
3514
3515The schema supports user-defined objects for handlers, filters and
3516formatters. (Loggers do not need to have different types for
3517different instances, so there is no support in this configuration
3518schema for user-defined logger classes.)
3519
3520Objects to be configured are described by dictionaries
3521which detail their configuration. In some places, the logging system
3522will be able to infer from the context how an object is to be
3523instantiated, but when a user-defined object is to be instantiated,
3524the system will not know how to do this. In order to provide complete
3525flexibility for user-defined object instantiation, the user needs
3526to provide a 'factory' - a callable which is called with a
3527configuration dictionary and which returns the instantiated object.
3528This is signalled by an absolute import path to the factory being
3529made available under the special key ``'()'``. Here's a concrete
3530example::
3531
3532 formatters:
3533 brief:
3534 format: '%(message)s'
3535 default:
3536 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3537 datefmt: '%Y-%m-%d %H:%M:%S'
3538 custom:
3539 (): my.package.customFormatterFactory
3540 bar: baz
3541 spam: 99.9
3542 answer: 42
3543
3544The above YAML snippet defines three formatters. The first, with id
3545``brief``, is a standard :class:`logging.Formatter` instance with the
3546specified format string. The second, with id ``default``, has a
3547longer format and also defines the time format explicitly, and will
3548result in a :class:`logging.Formatter` initialized with those two format
3549strings. Shown in Python source form, the ``brief`` and ``default``
3550formatters have configuration sub-dictionaries::
3551
3552 {
3553 'format' : '%(message)s'
3554 }
3555
3556and::
3557
3558 {
3559 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3560 'datefmt' : '%Y-%m-%d %H:%M:%S'
3561 }
3562
3563respectively, and as these dictionaries do not contain the special key
3564``'()'``, the instantiation is inferred from the context: as a result,
3565standard :class:`logging.Formatter` instances are created. The
3566configuration sub-dictionary for the third formatter, with id
3567``custom``, is::
3568
3569 {
3570 '()' : 'my.package.customFormatterFactory',
3571 'bar' : 'baz',
3572 'spam' : 99.9,
3573 'answer' : 42
3574 }
3575
3576and this contains the special key ``'()'``, which means that
3577user-defined instantiation is wanted. In this case, the specified
3578factory callable will be used. If it is an actual callable it will be
3579used directly - otherwise, if you specify a string (as in the example)
3580the actual callable will be located using normal import mechanisms.
3581The callable will be called with the **remaining** items in the
3582configuration sub-dictionary as keyword arguments. In the above
3583example, the formatter with id ``custom`` will be assumed to be
3584returned by the call::
3585
3586 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3587
3588The key ``'()'`` has been used as the special key because it is not a
3589valid keyword parameter name, and so will not clash with the names of
3590the keyword arguments used in the call. The ``'()'`` also serves as a
3591mnemonic that the corresponding value is a callable.
3592
3593
3594.. _logging-config-dict-externalobj:
3595
3596Access to external objects
3597""""""""""""""""""""""""""
3598
3599There are times where a configuration needs to refer to objects
3600external to the configuration, for example ``sys.stderr``. If the
3601configuration dict is constructed using Python code, this is
3602straightforward, but a problem arises when the configuration is
3603provided via a text file (e.g. JSON, YAML). In a text file, there is
3604no standard way to distinguish ``sys.stderr`` from the literal string
3605``'sys.stderr'``. To facilitate this distinction, the configuration
3606system looks for certain special prefixes in string values and
3607treat them specially. For example, if the literal string
3608``'ext://sys.stderr'`` is provided as a value in the configuration,
3609then the ``ext://`` will be stripped off and the remainder of the
3610value processed using normal import mechanisms.
3611
3612The handling of such prefixes is done in a way analogous to protocol
3613handling: there is a generic mechanism to look for prefixes which
3614match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3615whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3616in a prefix-dependent manner and the result of the processing replaces
3617the string value. If the prefix is not recognised, then the string
3618value will be left as-is.
3619
3620
3621.. _logging-config-dict-internalobj:
3622
3623Access to internal objects
3624""""""""""""""""""""""""""
3625
3626As well as external objects, there is sometimes also a need to refer
3627to objects in the configuration. This will be done implicitly by the
3628configuration system for things that it knows about. For example, the
3629string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3630automatically be converted to the value ``logging.DEBUG``, and the
3631``handlers``, ``filters`` and ``formatter`` entries will take an
3632object id and resolve to the appropriate destination object.
3633
3634However, a more generic mechanism is needed for user-defined
3635objects which are not known to the :mod:`logging` module. For
3636example, consider :class:`logging.handlers.MemoryHandler`, which takes
3637a ``target`` argument which is another handler to delegate to. Since
3638the system already knows about this class, then in the configuration,
3639the given ``target`` just needs to be the object id of the relevant
3640target handler, and the system will resolve to the handler from the
3641id. If, however, a user defines a ``my.package.MyHandler`` which has
3642an ``alternate`` handler, the configuration system would not know that
3643the ``alternate`` referred to a handler. To cater for this, a generic
3644resolution system allows the user to specify::
3645
3646 handlers:
3647 file:
3648 # configuration of file handler goes here
3649
3650 custom:
3651 (): my.package.MyHandler
3652 alternate: cfg://handlers.file
3653
3654The literal string ``'cfg://handlers.file'`` will be resolved in an
3655analogous way to strings with the ``ext://`` prefix, but looking
3656in the configuration itself rather than the import namespace. The
3657mechanism allows access by dot or by index, in a similar way to
3658that provided by ``str.format``. Thus, given the following snippet::
3659
3660 handlers:
3661 email:
3662 class: logging.handlers.SMTPHandler
3663 mailhost: localhost
3664 fromaddr: my_app@domain.tld
3665 toaddrs:
3666 - support_team@domain.tld
3667 - dev_team@domain.tld
3668 subject: Houston, we have a problem.
3669
3670in the configuration, the string ``'cfg://handlers'`` would resolve to
3671the dict with key ``handlers``, the string ``'cfg://handlers.email``
3672would resolve to the dict with key ``email`` in the ``handlers`` dict,
3673and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3674resolve to ``'dev_team.domain.tld'`` and the string
3675``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3676``'support_team@domain.tld'``. The ``subject`` value could be accessed
3677using either ``'cfg://handlers.email.subject'`` or, equivalently,
3678``'cfg://handlers.email[subject]'``. The latter form only needs to be
3679used if the key contains spaces or non-alphanumeric characters. If an
3680index value consists only of decimal digits, access will be attempted
3681using the corresponding integer value, falling back to the string
3682value if needed.
3683
3684Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3685resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3686If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3687the system will attempt to retrieve the value from
3688``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3689to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3690fails.
3691
Georg Brandl116aa622007-08-15 14:28:22 +00003692.. _logging-config-fileformat:
3693
3694Configuration file format
3695^^^^^^^^^^^^^^^^^^^^^^^^^
3696
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003697The configuration file format understood by :func:`fileConfig` is based on
3698:mod:`configparser` functionality. The file must contain sections called
3699``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3700entities of each type which are defined in the file. For each such entity, there
3701is a separate section which identifies how that entity is configured. Thus, for
3702a logger named ``log01`` in the ``[loggers]`` section, the relevant
3703configuration details are held in a section ``[logger_log01]``. Similarly, a
3704handler called ``hand01`` in the ``[handlers]`` section will have its
3705configuration held in a section called ``[handler_hand01]``, while a formatter
3706called ``form01`` in the ``[formatters]`` section will have its configuration
3707specified in a section called ``[formatter_form01]``. The root logger
3708configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003709
3710Examples of these sections in the file are given below. ::
3711
3712 [loggers]
3713 keys=root,log02,log03,log04,log05,log06,log07
3714
3715 [handlers]
3716 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3717
3718 [formatters]
3719 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3720
3721The root logger must specify a level and a list of handlers. An example of a
3722root logger section is given below. ::
3723
3724 [logger_root]
3725 level=NOTSET
3726 handlers=hand01
3727
3728The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3729``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3730logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3731package's namespace.
3732
3733The ``handlers`` entry is a comma-separated list of handler names, which must
3734appear in the ``[handlers]`` section. These names must appear in the
3735``[handlers]`` section and have corresponding sections in the configuration
3736file.
3737
3738For loggers other than the root logger, some additional information is required.
3739This is illustrated by the following example. ::
3740
3741 [logger_parser]
3742 level=DEBUG
3743 handlers=hand01
3744 propagate=1
3745 qualname=compiler.parser
3746
3747The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3748except that if a non-root logger's level is specified as ``NOTSET``, the system
3749consults loggers higher up the hierarchy to determine the effective level of the
3750logger. The ``propagate`` entry is set to 1 to indicate that messages must
3751propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3752indicate that messages are **not** propagated to handlers up the hierarchy. The
3753``qualname`` entry is the hierarchical channel name of the logger, that is to
3754say the name used by the application to get the logger.
3755
3756Sections which specify handler configuration are exemplified by the following.
3757::
3758
3759 [handler_hand01]
3760 class=StreamHandler
3761 level=NOTSET
3762 formatter=form01
3763 args=(sys.stdout,)
3764
3765The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3766in the ``logging`` package's namespace). The ``level`` is interpreted as for
3767loggers, and ``NOTSET`` is taken to mean "log everything".
3768
3769The ``formatter`` entry indicates the key name of the formatter for this
3770handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3771If a name is specified, it must appear in the ``[formatters]`` section and have
3772a corresponding section in the configuration file.
3773
3774The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3775package's namespace, is the list of arguments to the constructor for the handler
3776class. Refer to the constructors for the relevant handlers, or to the examples
3777below, to see how typical entries are constructed. ::
3778
3779 [handler_hand02]
3780 class=FileHandler
3781 level=DEBUG
3782 formatter=form02
3783 args=('python.log', 'w')
3784
3785 [handler_hand03]
3786 class=handlers.SocketHandler
3787 level=INFO
3788 formatter=form03
3789 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3790
3791 [handler_hand04]
3792 class=handlers.DatagramHandler
3793 level=WARN
3794 formatter=form04
3795 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3796
3797 [handler_hand05]
3798 class=handlers.SysLogHandler
3799 level=ERROR
3800 formatter=form05
3801 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3802
3803 [handler_hand06]
3804 class=handlers.NTEventLogHandler
3805 level=CRITICAL
3806 formatter=form06
3807 args=('Python Application', '', 'Application')
3808
3809 [handler_hand07]
3810 class=handlers.SMTPHandler
3811 level=WARN
3812 formatter=form07
3813 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3814
3815 [handler_hand08]
3816 class=handlers.MemoryHandler
3817 level=NOTSET
3818 formatter=form08
3819 target=
3820 args=(10, ERROR)
3821
3822 [handler_hand09]
3823 class=handlers.HTTPHandler
3824 level=NOTSET
3825 formatter=form09
3826 args=('localhost:9022', '/log', 'GET')
3827
3828Sections which specify formatter configuration are typified by the following. ::
3829
3830 [formatter_form01]
3831 format=F1 %(asctime)s %(levelname)s %(message)s
3832 datefmt=
3833 class=logging.Formatter
3834
3835The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003836the :func:`strftime`\ -compatible date/time format string. If empty, the
3837package substitutes ISO8601 format date/times, which is almost equivalent to
3838specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3839also specifies milliseconds, which are appended to the result of using the above
3840format string, with a comma separator. An example time in ISO8601 format is
3841``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00003842
3843The ``class`` entry is optional. It indicates the name of the formatter's class
3844(as a dotted module and class name.) This option is useful for instantiating a
3845:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3846exception tracebacks in an expanded or condensed format.
3847
Christian Heimes8b0facf2007-12-04 19:30:01 +00003848
3849Configuration server example
3850^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3851
3852Here is an example of a module using the logging configuration server::
3853
3854 import logging
3855 import logging.config
3856 import time
3857 import os
3858
3859 # read initial config file
3860 logging.config.fileConfig("logging.conf")
3861
3862 # create and start listener on port 9999
3863 t = logging.config.listen(9999)
3864 t.start()
3865
3866 logger = logging.getLogger("simpleExample")
3867
3868 try:
3869 # loop through logging calls to see the difference
3870 # new configurations make, until Ctrl+C is pressed
3871 while True:
3872 logger.debug("debug message")
3873 logger.info("info message")
3874 logger.warn("warn message")
3875 logger.error("error message")
3876 logger.critical("critical message")
3877 time.sleep(5)
3878 except KeyboardInterrupt:
3879 # cleanup
3880 logging.config.stopListening()
3881 t.join()
3882
3883And here is a script that takes a filename and sends that file to the server,
3884properly preceded with the binary-encoded length, as the new logging
3885configuration::
3886
3887 #!/usr/bin/env python
3888 import socket, sys, struct
3889
3890 data_to_send = open(sys.argv[1], "r").read()
3891
3892 HOST = 'localhost'
3893 PORT = 9999
3894 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00003895 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003896 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00003897 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003898 s.send(struct.pack(">L", len(data_to_send)))
3899 s.send(data_to_send)
3900 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00003901 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003902
3903
3904More examples
3905-------------
3906
3907Multiple handlers and formatters
3908^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3909
3910Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3911or maximum quota for the number of handlers you may add. Sometimes it will be
3912beneficial for an application to log all messages of all severities to a text
3913file while simultaneously logging errors or above to the console. To set this
3914up, simply configure the appropriate handlers. The logging calls in the
3915application code will remain unchanged. Here is a slight modification to the
3916previous simple module-based configuration example::
3917
3918 import logging
3919
3920 logger = logging.getLogger("simple_example")
3921 logger.setLevel(logging.DEBUG)
3922 # create file handler which logs even debug messages
3923 fh = logging.FileHandler("spam.log")
3924 fh.setLevel(logging.DEBUG)
3925 # create console handler with a higher log level
3926 ch = logging.StreamHandler()
3927 ch.setLevel(logging.ERROR)
3928 # create formatter and add it to the handlers
3929 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3930 ch.setFormatter(formatter)
3931 fh.setFormatter(formatter)
3932 # add the handlers to logger
3933 logger.addHandler(ch)
3934 logger.addHandler(fh)
3935
3936 # "application" code
3937 logger.debug("debug message")
3938 logger.info("info message")
3939 logger.warn("warn message")
3940 logger.error("error message")
3941 logger.critical("critical message")
3942
3943Notice that the "application" code does not care about multiple handlers. All
3944that changed was the addition and configuration of a new handler named *fh*.
3945
3946The ability to create new handlers with higher- or lower-severity filters can be
3947very helpful when writing and testing an application. Instead of using many
3948``print`` statements for debugging, use ``logger.debug``: Unlike the print
3949statements, which you will have to delete or comment out later, the logger.debug
3950statements can remain intact in the source code and remain dormant until you
3951need them again. At that time, the only change that needs to happen is to
3952modify the severity level of the logger and/or handler to debug.
3953
3954
3955Using logging in multiple modules
3956^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3957
3958It was mentioned above that multiple calls to
3959``logging.getLogger('someLogger')`` return a reference to the same logger
3960object. This is true not only within the same module, but also across modules
3961as long as it is in the same Python interpreter process. It is true for
3962references to the same object; additionally, application code can define and
3963configure a parent logger in one module and create (but not configure) a child
3964logger in a separate module, and all logger calls to the child will pass up to
3965the parent. Here is a main module::
3966
3967 import logging
3968 import auxiliary_module
3969
3970 # create logger with "spam_application"
3971 logger = logging.getLogger("spam_application")
3972 logger.setLevel(logging.DEBUG)
3973 # create file handler which logs even debug messages
3974 fh = logging.FileHandler("spam.log")
3975 fh.setLevel(logging.DEBUG)
3976 # create console handler with a higher log level
3977 ch = logging.StreamHandler()
3978 ch.setLevel(logging.ERROR)
3979 # create formatter and add it to the handlers
3980 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3981 fh.setFormatter(formatter)
3982 ch.setFormatter(formatter)
3983 # add the handlers to the logger
3984 logger.addHandler(fh)
3985 logger.addHandler(ch)
3986
3987 logger.info("creating an instance of auxiliary_module.Auxiliary")
3988 a = auxiliary_module.Auxiliary()
3989 logger.info("created an instance of auxiliary_module.Auxiliary")
3990 logger.info("calling auxiliary_module.Auxiliary.do_something")
3991 a.do_something()
3992 logger.info("finished auxiliary_module.Auxiliary.do_something")
3993 logger.info("calling auxiliary_module.some_function()")
3994 auxiliary_module.some_function()
3995 logger.info("done with auxiliary_module.some_function()")
3996
3997Here is the auxiliary module::
3998
3999 import logging
4000
4001 # create logger
4002 module_logger = logging.getLogger("spam_application.auxiliary")
4003
4004 class Auxiliary:
4005 def __init__(self):
4006 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4007 self.logger.info("creating an instance of Auxiliary")
4008 def do_something(self):
4009 self.logger.info("doing something")
4010 a = 1 + 1
4011 self.logger.info("done doing something")
4012
4013 def some_function():
4014 module_logger.info("received a call to \"some_function\"")
4015
4016The output looks like this::
4017
Christian Heimes043d6f62008-01-07 17:19:16 +00004018 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004019 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004020 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004021 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004022 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004023 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004024 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004025 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004026 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004027 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004028 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004029 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004030 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004031 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004032 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004033 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004034 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004035 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004036 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004037 done with auxiliary_module.some_function()
4038