blob: 018b16fb5d569dc255e6e088eb77b428934cf4be [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
Vinay Sajipa39c5712010-10-25 13:57:39 +0000304if your application needs special behavior. The constructor takes three
305optional arguments -- a message format string, a date format string and a style
306indicator.
307
308.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
309
310If there is no message format string, the default is to use the
311raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000312
313 %Y-%m-%d %H:%M:%S
314
Vinay Sajipa39c5712010-10-25 13:57:39 +0000315with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
316or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000317
Vinay Sajipa39c5712010-10-25 13:57:39 +0000318If the ``style`` is '%', the message format string uses
319``%(<dictionary key>)s`` styled string substitution; the possible keys are
320documented in :ref:`formatter-objects`. If the style is '{', the message format
321string is assumed to be compatible with :meth:`str.format` (using keyword
322arguments), while if the style is '$' then the message format string should
323conform to what is expected by :meth:`string.Template.substitute`.
324
325.. versionchanged:: 3.2
326 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000327
328The following message format string will log the time in a human-readable
329format, the severity of the message, and the contents of the message, in that
330order::
331
332 "%(asctime)s - %(levelname)s - %(message)s"
333
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000334Formatters use a user-configurable function to convert the creation time of a
335record to a tuple. By default, :func:`time.localtime` is used; to change this
336for a particular formatter instance, set the ``converter`` attribute of the
337instance to a function with the same signature as :func:`time.localtime` or
338:func:`time.gmtime`. To change it for all formatters, for example if you want
339all logging times to be shown in GMT, set the ``converter`` attribute in the
340Formatter class (to ``time.gmtime`` for GMT display).
341
Christian Heimes8b0facf2007-12-04 19:30:01 +0000342
343Configuring Logging
344^^^^^^^^^^^^^^^^^^^
345
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000346Programmers can configure logging in three ways:
347
3481. Creating loggers, handlers, and formatters explicitly using Python
349 code that calls the configuration methods listed above.
3502. Creating a logging config file and reading it using the :func:`fileConfig`
351 function.
3523. Creating a dictionary of configuration information and passing it
353 to the :func:`dictConfig` function.
354
355The following example configures a very simple logger, a console
356handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000357
358 import logging
359
360 # create logger
361 logger = logging.getLogger("simple_example")
362 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000363
Christian Heimes8b0facf2007-12-04 19:30:01 +0000364 # create console handler and set level to debug
365 ch = logging.StreamHandler()
366 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000367
Christian Heimes8b0facf2007-12-04 19:30:01 +0000368 # create formatter
369 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000370
Christian Heimes8b0facf2007-12-04 19:30:01 +0000371 # add formatter to ch
372 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000373
Christian Heimes8b0facf2007-12-04 19:30:01 +0000374 # add ch to logger
375 logger.addHandler(ch)
376
377 # "application" code
378 logger.debug("debug message")
379 logger.info("info message")
380 logger.warn("warn message")
381 logger.error("error message")
382 logger.critical("critical message")
383
384Running this module from the command line produces the following output::
385
386 $ python simple_logging_module.py
387 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
388 2005-03-19 15:10:26,620 - simple_example - INFO - info message
389 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
390 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
391 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
392
393The following Python module creates a logger, handler, and formatter nearly
394identical to those in the example listed above, with the only difference being
395the names of the objects::
396
397 import logging
398 import logging.config
399
400 logging.config.fileConfig("logging.conf")
401
402 # create logger
403 logger = logging.getLogger("simpleExample")
404
405 # "application" code
406 logger.debug("debug message")
407 logger.info("info message")
408 logger.warn("warn message")
409 logger.error("error message")
410 logger.critical("critical message")
411
412Here is the logging.conf file::
413
414 [loggers]
415 keys=root,simpleExample
416
417 [handlers]
418 keys=consoleHandler
419
420 [formatters]
421 keys=simpleFormatter
422
423 [logger_root]
424 level=DEBUG
425 handlers=consoleHandler
426
427 [logger_simpleExample]
428 level=DEBUG
429 handlers=consoleHandler
430 qualname=simpleExample
431 propagate=0
432
433 [handler_consoleHandler]
434 class=StreamHandler
435 level=DEBUG
436 formatter=simpleFormatter
437 args=(sys.stdout,)
438
439 [formatter_simpleFormatter]
440 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
441 datefmt=
442
443The output is nearly identical to that of the non-config-file-based example::
444
445 $ python simple_logging_config.py
446 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
447 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
448 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
449 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
450 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
451
452You can see that the config file approach has a few advantages over the Python
453code approach, mainly separation of configuration and code and the ability of
454noncoders to easily modify the logging properties.
455
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000456Note that the class names referenced in config files need to be either relative
457to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000458import mechanisms. Thus, you could use either
459:class:`handlers.WatchedFileHandler` (relative to the logging module) or
460``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
461and module ``mymodule``, where ``mypackage`` is available on the Python import
462path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000463
Benjamin Peterson56894b52010-06-28 00:16:12 +0000464In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000465dictionaries to hold configuration information. This provides a superset of the
466functionality of the config-file-based approach outlined above, and is the
467recommended configuration method for new applications and deployments. Because
468a Python dictionary is used to hold configuration information, and since you
469can populate that dictionary using different means, you have more options for
470configuration. For example, you can use a configuration file in JSON format,
471or, if you have access to YAML processing functionality, a file in YAML
472format, to populate the configuration dictionary. Or, of course, you can
473construct the dictionary in Python code, receive it in pickled form over a
474socket, or use whatever approach makes sense for your application.
475
476Here's an example of the same configuration as above, in YAML format for
477the new dictionary-based approach::
478
479 version: 1
480 formatters:
481 simple:
482 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
483 handlers:
484 console:
485 class: logging.StreamHandler
486 level: DEBUG
487 formatter: simple
488 stream: ext://sys.stdout
489 loggers:
490 simpleExample:
491 level: DEBUG
492 handlers: [console]
493 propagate: no
494 root:
495 level: DEBUG
496 handlers: [console]
497
498For more information about logging using a dictionary, see
499:ref:`logging-config-api`.
500
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000501.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000502
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000503Configuring Logging for a Library
504^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
505
506When developing a library which uses logging, some consideration needs to be
507given to its configuration. If the using application does not use logging, and
508library code makes logging calls, then a one-off message "No handlers could be
509found for logger X.Y.Z" is printed to the console. This message is intended
510to catch mistakes in logging configuration, but will confuse an application
511developer who is not aware of logging by the library.
512
513In addition to documenting how a library uses logging, a good way to configure
514library logging so that it does not cause a spurious message is to add a
515handler which does nothing. This avoids the message being printed, since a
516handler will be found: it just doesn't produce any output. If the library user
517configures logging for application use, presumably that configuration will add
518some handlers, and if levels are suitably configured then logging calls made
519in library code will send output to those handlers, as normal.
520
521A do-nothing handler can be simply defined as follows::
522
523 import logging
524
525 class NullHandler(logging.Handler):
526 def emit(self, record):
527 pass
528
529An instance of this handler should be added to the top-level logger of the
530logging namespace used by the library. If all logging by a library *foo* is
531done using loggers with names matching "foo.x.y", then the code::
532
533 import logging
534
535 h = NullHandler()
536 logging.getLogger("foo").addHandler(h)
537
538should have the desired effect. If an organisation produces a number of
539libraries, then the logger name specified can be "orgname.foo" rather than
540just "foo".
541
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000542**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
543than* :class:`NullHandler` *to your library's loggers*. This is because the
544configuration of handlers is the prerogative of the application developer who
545uses your library. The application developer knows their target audience and
546what handlers are most appropriate for their application: if you add handlers
547"under the hood", you might well interfere with their ability to carry out
548unit tests and deliver logs which suit their requirements.
549
Georg Brandlf9734072008-12-07 15:30:06 +0000550.. versionadded:: 3.1
Vinay Sajip4039aff2010-09-11 10:25:28 +0000551
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000552The :class:`NullHandler` class was not present in previous versions, but is
553now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000554
555
Christian Heimes8b0facf2007-12-04 19:30:01 +0000556
557Logging Levels
558--------------
559
Georg Brandl116aa622007-08-15 14:28:22 +0000560The numeric values of logging levels are given in the following table. These are
561primarily of interest if you want to define your own levels, and need them to
562have specific values relative to the predefined levels. If you define a level
563with the same numeric value, it overwrites the predefined value; the predefined
564name is lost.
565
566+--------------+---------------+
567| Level | Numeric value |
568+==============+===============+
569| ``CRITICAL`` | 50 |
570+--------------+---------------+
571| ``ERROR`` | 40 |
572+--------------+---------------+
573| ``WARNING`` | 30 |
574+--------------+---------------+
575| ``INFO`` | 20 |
576+--------------+---------------+
577| ``DEBUG`` | 10 |
578+--------------+---------------+
579| ``NOTSET`` | 0 |
580+--------------+---------------+
581
582Levels can also be associated with loggers, being set either by the developer or
583through loading a saved logging configuration. When a logging method is called
584on a logger, the logger compares its own level with the level associated with
585the method call. If the logger's level is higher than the method call's, no
586logging message is actually generated. This is the basic mechanism controlling
587the verbosity of logging output.
588
589Logging messages are encoded as instances of the :class:`LogRecord` class. When
590a logger decides to actually log an event, a :class:`LogRecord` instance is
591created from the logging message.
592
593Logging messages are subjected to a dispatch mechanism through the use of
594:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
595class. Handlers are responsible for ensuring that a logged message (in the form
596of a :class:`LogRecord`) ends up in a particular location (or set of locations)
597which is useful for the target audience for that message (such as end users,
598support desk staff, system administrators, developers). Handlers are passed
599:class:`LogRecord` instances intended for particular destinations. Each logger
600can have zero, one or more handlers associated with it (via the
601:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
602directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000603of the logger* are called to dispatch the message (unless the *propagate* flag
604for a logger is set to a false value, at which point the passing to ancestor
605handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607Just as for loggers, handlers can have levels associated with them. A handler's
608level acts as a filter in the same way as a logger's level does. If a handler
609decides to actually dispatch an event, the :meth:`emit` method is used to send
610the message to its destination. Most user-defined subclasses of :class:`Handler`
611will need to override this :meth:`emit`.
612
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000613.. _custom-levels:
614
615Custom Levels
616^^^^^^^^^^^^^
617
618Defining your own levels is possible, but should not be necessary, as the
619existing levels have been chosen on the basis of practical experience.
620However, if you are convinced that you need custom levels, great care should
621be exercised when doing this, and it is possibly *a very bad idea to define
622custom levels if you are developing a library*. That's because if multiple
623library authors all define their own custom levels, there is a chance that
624the logging output from such multiple libraries used together will be
625difficult for the using developer to control and/or interpret, because a
626given numeric value might mean different things for different libraries.
627
628
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000629Useful Handlers
630---------------
631
Georg Brandl116aa622007-08-15 14:28:22 +0000632In addition to the base :class:`Handler` class, many useful subclasses are
633provided:
634
Vinay Sajip121a1c42010-09-08 10:46:15 +0000635#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000636 objects).
637
Vinay Sajip121a1c42010-09-08 10:46:15 +0000638#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000640.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000641
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000642#. :class:`BaseRotatingHandler` is the base class for handlers that
643 rotate log files at a certain point. It is not meant to be instantiated
644 directly. Instead, use :class:`RotatingFileHandler` or
645 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Vinay Sajip121a1c42010-09-08 10:46:15 +0000647#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000648 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Vinay Sajip121a1c42010-09-08 10:46:15 +0000650#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000651 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Vinay Sajip121a1c42010-09-08 10:46:15 +0000653#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000654 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Vinay Sajip121a1c42010-09-08 10:46:15 +0000656#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000657 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Vinay Sajip121a1c42010-09-08 10:46:15 +0000659#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000660 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Vinay Sajip121a1c42010-09-08 10:46:15 +0000662#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000663 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Vinay Sajip121a1c42010-09-08 10:46:15 +0000665#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000666 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Vinay Sajip121a1c42010-09-08 10:46:15 +0000668#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000669 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Vinay Sajip121a1c42010-09-08 10:46:15 +0000671#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000672 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000674#. :class:`WatchedFileHandler` instances watch the file they are
675 logging to. If the file changes, it is closed and reopened using the file
676 name. This handler is only useful on Unix-like systems; Windows does not
677 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000678
Vinay Sajip121a1c42010-09-08 10:46:15 +0000679#. :class:`QueueHandler` instances send messages to a queue, such as
680 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
681
Vinay Sajip30bf1222009-01-10 19:23:34 +0000682.. currentmodule:: logging
683
Georg Brandlf9734072008-12-07 15:30:06 +0000684#. :class:`NullHandler` instances do nothing with error messages. They are used
685 by library developers who want to use logging, but want to avoid the "No
686 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000687 the library user has not configured logging. See :ref:`library-config` for
688 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000689
690.. versionadded:: 3.1
691
692The :class:`NullHandler` class was not present in previous versions.
693
Vinay Sajip121a1c42010-09-08 10:46:15 +0000694.. versionadded:: 3.2
695
696The :class:`QueueHandler` class was not present in previous versions.
697
Vinay Sajipa17775f2008-12-30 07:32:59 +0000698The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
699classes are defined in the core logging package. The other handlers are
700defined in a sub- module, :mod:`logging.handlers`. (There is also another
701sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703Logged messages are formatted for presentation through instances of the
704:class:`Formatter` class. They are initialized with a format string suitable for
705use with the % operator and a dictionary.
706
707For formatting multiple messages in a batch, instances of
708:class:`BufferingFormatter` can be used. In addition to the format string (which
709is applied to each message in the batch), there is provision for header and
710trailer format strings.
711
712When filtering based on logger level and/or handler level is not enough,
713instances of :class:`Filter` can be added to both :class:`Logger` and
714:class:`Handler` instances (through their :meth:`addFilter` method). Before
715deciding to process a message further, both loggers and handlers consult all
716their filters for permission. If any filter returns a false value, the message
717is not processed further.
718
719The basic :class:`Filter` functionality allows filtering by specific logger
720name. If this feature is used, messages sent to the named logger and its
721children are allowed through the filter, and all others dropped.
722
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000723Module-Level Functions
724----------------------
725
Georg Brandl116aa622007-08-15 14:28:22 +0000726In addition to the classes described above, there are a number of module- level
727functions.
728
729
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000730.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000732 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000733 logger which is the root logger of the hierarchy. If specified, the name is
734 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
735 Choice of these names is entirely up to the developer who is using logging.
736
737 All calls to this function with a given name return the same logger instance.
738 This means that logger instances never need to be passed between different parts
739 of an application.
740
741
742.. function:: getLoggerClass()
743
744 Return either the standard :class:`Logger` class, or the last class passed to
745 :func:`setLoggerClass`. This function may be called from within a new class
746 definition, to ensure that installing a customised :class:`Logger` class will
747 not undo customisations already applied by other code. For example::
748
749 class MyLogger(logging.getLoggerClass()):
750 # ... override behaviour here
751
752
Vinay Sajip61561522010-12-03 11:50:38 +0000753.. function:: getLogRecordFactory()
754
755 Return a callable which is used to create a :class:`LogRecord`.
756
757 .. versionadded:: 3.2
758
759 This function has been provided, along with :func:`setLogRecordFactory`,
760 to allow developers more control over how the :class:`LogRecord`
761 representing a logging event is constructed.
762
763 See :func:`setLogRecordFactory` for more information about the how the
764 factory is called.
765
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000766.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
769 message format string, and the *args* are the arguments which are merged into
770 *msg* using the string formatting operator. (Note that this means that you can
771 use keywords in the format string, together with a single dictionary argument.)
772
Vinay Sajip8593ae62010-11-14 21:33:04 +0000773 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +0000774 which, if it does not evaluate as false, causes exception information to be
775 added to the logging message. If an exception tuple (in the format returned by
776 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
777 is called to get the exception information.
778
Vinay Sajip8593ae62010-11-14 21:33:04 +0000779 The second optional keyword argument is *stack_info*, which defaults to
780 False. If specified as True, stack information is added to the logging
781 message, including the actual logging call. Note that this is not the same
782 stack information as that displayed through specifying *exc_info*: The
783 former is stack frames from the bottom of the stack up to the logging call
784 in the current thread, whereas the latter is information about stack frames
785 which have been unwound, following an exception, while searching for
786 exception handlers.
787
788 You can specify *stack_info* independently of *exc_info*, e.g. to just show
789 how you got to a certain point in your code, even when no exceptions were
790 raised. The stack frames are printed following a header line which says::
791
792 Stack (most recent call last):
793
794 This mimics the `Traceback (most recent call last):` which is used when
795 displaying exception frames.
796
797 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +0000798 dictionary which is used to populate the __dict__ of the LogRecord created for
799 the logging event with user-defined attributes. These custom attributes can then
800 be used as you like. For example, they could be incorporated into logged
801 messages. For example::
802
803 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
804 logging.basicConfig(format=FORMAT)
805 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
806 logging.warning("Protocol problem: %s", "connection reset", extra=d)
807
Vinay Sajip4039aff2010-09-11 10:25:28 +0000808 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
811
812 The keys in the dictionary passed in *extra* should not clash with the keys used
813 by the logging system. (See the :class:`Formatter` documentation for more
814 information on which keys are used by the logging system.)
815
816 If you choose to use these attributes in logged messages, you need to exercise
817 some care. In the above example, for instance, the :class:`Formatter` has been
818 set up with a format string which expects 'clientip' and 'user' in the attribute
819 dictionary of the LogRecord. If these are missing, the message will not be
820 logged because a string formatting exception will occur. So in this case, you
821 always need to pass the *extra* dictionary with these keys.
822
823 While this might be annoying, this feature is intended for use in specialized
824 circumstances, such as multi-threaded servers where the same code executes in
825 many contexts, and interesting conditions which arise are dependent on this
826 context (such as remote client IP address and authenticated user name, in the
827 above example). In such circumstances, it is likely that specialized
828 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
829
Vinay Sajip8593ae62010-11-14 21:33:04 +0000830 .. versionadded:: 3.2
831 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000833.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000834
835 Logs a message with level :const:`INFO` on the root logger. The arguments are
836 interpreted as for :func:`debug`.
837
838
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000839.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841 Logs a message with level :const:`WARNING` on the root logger. The arguments are
842 interpreted as for :func:`debug`.
843
844
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000845.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847 Logs a message with level :const:`ERROR` on the root logger. The arguments are
848 interpreted as for :func:`debug`.
849
850
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000851.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000852
853 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
854 are interpreted as for :func:`debug`.
855
856
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000857.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859 Logs a message with level :const:`ERROR` on the root logger. The arguments are
860 interpreted as for :func:`debug`. Exception info is added to the logging
861 message. This function should only be called from an exception handler.
862
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000863.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865 Logs a message with level *level* on the root logger. The other arguments are
866 interpreted as for :func:`debug`.
867
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000868 PLEASE NOTE: The above module-level functions which delegate to the root
869 logger should *not* be used in threads, in versions of Python earlier than
870 2.7.1 and 3.2, unless at least one handler has been added to the root
871 logger *before* the threads are started. These convenience functions call
872 :func:`basicConfig` to ensure that at least one handler is available; in
873 earlier versions of Python, this can (under rare circumstances) lead to
874 handlers being added multiple times to the root logger, which can in turn
875 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +0000876
877.. function:: disable(lvl)
878
879 Provides an overriding level *lvl* for all loggers which takes precedence over
880 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000881 output down across the whole application, this function can be useful. Its
882 effect is to disable all logging calls of severity *lvl* and below, so that
883 if you call it with a value of INFO, then all INFO and DEBUG events would be
884 discarded, whereas those of severity WARNING and above would be processed
885 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000886
887
888.. function:: addLevelName(lvl, levelName)
889
890 Associates level *lvl* with text *levelName* in an internal dictionary, which is
891 used to map numeric levels to a textual representation, for example when a
892 :class:`Formatter` formats a message. This function can also be used to define
893 your own levels. The only constraints are that all levels used must be
894 registered using this function, levels should be positive integers and they
895 should increase in increasing order of severity.
896
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000897 NOTE: If you are thinking of defining your own levels, please see the section
898 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900.. function:: getLevelName(lvl)
901
902 Returns the textual representation of logging level *lvl*. If the level is one
903 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
904 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
905 have associated levels with names using :func:`addLevelName` then the name you
906 have associated with *lvl* is returned. If a numeric value corresponding to one
907 of the defined levels is passed in, the corresponding string representation is
908 returned. Otherwise, the string "Level %s" % lvl is returned.
909
910
911.. function:: makeLogRecord(attrdict)
912
913 Creates and returns a new :class:`LogRecord` instance whose attributes are
914 defined by *attrdict*. This function is useful for taking a pickled
915 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
916 it as a :class:`LogRecord` instance at the receiving end.
917
918
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000919.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921 Does basic configuration for the logging system by creating a
922 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000923 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000924 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
925 if no handlers are defined for the root logger.
926
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000927 This function does nothing if the root logger already has handlers
928 configured for it.
929
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000930 PLEASE NOTE: This function should be called from the main thread
931 before other threads are started. In versions of Python prior to
932 2.7.1 and 3.2, if this function is called from multiple threads,
933 it is possible (in rare circumstances) that a handler will be added
934 to the root logger more than once, leading to unexpected results
935 such as messages being duplicated in the log.
936
Georg Brandl116aa622007-08-15 14:28:22 +0000937 The following keyword arguments are supported.
938
939 +--------------+---------------------------------------------+
940 | Format | Description |
941 +==============+=============================================+
942 | ``filename`` | Specifies that a FileHandler be created, |
943 | | using the specified filename, rather than a |
944 | | StreamHandler. |
945 +--------------+---------------------------------------------+
946 | ``filemode`` | Specifies the mode to open the file, if |
947 | | filename is specified (if filemode is |
948 | | unspecified, it defaults to 'a'). |
949 +--------------+---------------------------------------------+
950 | ``format`` | Use the specified format string for the |
951 | | handler. |
952 +--------------+---------------------------------------------+
953 | ``datefmt`` | Use the specified date/time format. |
954 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +0000955 | ``style`` | If ``format`` is specified, use this style |
956 | | for the format string. One of '%', '{' or |
957 | | '$' for %-formatting, :meth:`str.format` or |
958 | | :class:`string.Template` respectively, and |
959 | | defaulting to '%' if not specified. |
960 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000961 | ``level`` | Set the root logger level to the specified |
962 | | level. |
963 +--------------+---------------------------------------------+
964 | ``stream`` | Use the specified stream to initialize the |
965 | | StreamHandler. Note that this argument is |
966 | | incompatible with 'filename' - if both are |
967 | | present, 'stream' is ignored. |
968 +--------------+---------------------------------------------+
969
Vinay Sajipc5b27302010-10-31 14:59:16 +0000970 .. versionchanged:: 3.2
971 The ``style`` argument was added.
972
973
Georg Brandl116aa622007-08-15 14:28:22 +0000974.. function:: shutdown()
975
976 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000977 closing all handlers. This should be called at application exit and no
978 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980
981.. function:: setLoggerClass(klass)
982
983 Tells the logging system to use the class *klass* when instantiating a logger.
984 The class should define :meth:`__init__` such that only a name argument is
985 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
986 function is typically called before any loggers are instantiated by applications
987 which need to use custom logger behavior.
988
Vinay Sajip61561522010-12-03 11:50:38 +0000989.. function:: setLogRecordFactory(factory)
990
991 Set a callable which is used to create a :class:`LogRecord`.
992
993 :param factory: The factory callable to be used to instantiate a log record.
994
995 .. versionadded:: 3.2
996
997 This function has been provided, along with :func:`getLogRecordFactory`, to
998 allow developers more control over how the :class:`LogRecord` representing
999 a logging event is constructed.
1000
1001 The factory has the following signature.
1002
1003 factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, \*\*kwargs)
1004
1005 :name: The logger name.
1006 :level: The logging level (numeric).
1007 :fn: The full pathname of the file where the logging call was made.
1008 :lno: The line number in the file where the logging call was made.
1009 :msg: The logging message.
1010 :args: The arguments for the logging message.
1011 :exc_info: An exception tuple, or None.
1012 :func: The name of the function or method which invoked the logging
1013 call.
1014 :sinfo: A stack traceback such as is provided by
1015 :func:`traceback.print_stack`, showing the call hierarchy.
1016 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001017
1018.. seealso::
1019
1020 :pep:`282` - A Logging System
1021 The proposal which described this feature for inclusion in the Python standard
1022 library.
1023
Christian Heimes255f53b2007-12-08 15:33:56 +00001024 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001025 This is the original source for the :mod:`logging` package. The version of the
1026 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1027 and 2.2.x, which do not include the :mod:`logging` package in the standard
1028 library.
1029
Vinay Sajip4039aff2010-09-11 10:25:28 +00001030.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001031
1032Logger Objects
1033--------------
1034
1035Loggers have the following attributes and methods. Note that Loggers are never
1036instantiated directly, but always through the module-level function
1037``logging.getLogger(name)``.
1038
Vinay Sajip0258ce82010-09-22 20:34:53 +00001039.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001040
1041.. attribute:: Logger.propagate
1042
1043 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001044 its child loggers to the handlers of higher level (ancestor) loggers. The
1045 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047
1048.. method:: Logger.setLevel(lvl)
1049
1050 Sets the threshold for this logger to *lvl*. Logging messages which are less
1051 severe than *lvl* will be ignored. When a logger is created, the level is set to
1052 :const:`NOTSET` (which causes all messages to be processed when the logger is
1053 the root logger, or delegation to the parent when the logger is a non-root
1054 logger). Note that the root logger is created with level :const:`WARNING`.
1055
1056 The term "delegation to the parent" means that if a logger has a level of
1057 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1058 a level other than NOTSET is found, or the root is reached.
1059
1060 If an ancestor is found with a level other than NOTSET, then that ancestor's
1061 level is treated as the effective level of the logger where the ancestor search
1062 began, and is used to determine how a logging event is handled.
1063
1064 If the root is reached, and it has a level of NOTSET, then all messages will be
1065 processed. Otherwise, the root's level will be used as the effective level.
1066
1067
1068.. method:: Logger.isEnabledFor(lvl)
1069
1070 Indicates if a message of severity *lvl* would be processed by this logger.
1071 This method checks first the module-level level set by
1072 ``logging.disable(lvl)`` and then the logger's effective level as determined
1073 by :meth:`getEffectiveLevel`.
1074
1075
1076.. method:: Logger.getEffectiveLevel()
1077
1078 Indicates the effective level for this logger. If a value other than
1079 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1080 the hierarchy is traversed towards the root until a value other than
1081 :const:`NOTSET` is found, and that value is returned.
1082
1083
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001084.. method:: Logger.getChild(suffix)
1085
1086 Returns a logger which is a descendant to this logger, as determined by the suffix.
1087 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1088 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1089 convenience method, useful when the parent logger is named using e.g. ``__name__``
1090 rather than a literal string.
1091
1092 .. versionadded:: 3.2
1093
Georg Brandl67b21b72010-08-17 15:07:14 +00001094
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001095.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001096
1097 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1098 message format string, and the *args* are the arguments which are merged into
1099 *msg* using the string formatting operator. (Note that this means that you can
1100 use keywords in the format string, together with a single dictionary argument.)
1101
Vinay Sajip8593ae62010-11-14 21:33:04 +00001102 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001103 which, if it does not evaluate as false, causes exception information to be
1104 added to the logging message. If an exception tuple (in the format returned by
1105 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1106 is called to get the exception information.
1107
Vinay Sajip8593ae62010-11-14 21:33:04 +00001108 The second optional keyword argument is *stack_info*, which defaults to
1109 False. If specified as True, stack information is added to the logging
1110 message, including the actual logging call. Note that this is not the same
1111 stack information as that displayed through specifying *exc_info*: The
1112 former is stack frames from the bottom of the stack up to the logging call
1113 in the current thread, whereas the latter is information about stack frames
1114 which have been unwound, following an exception, while searching for
1115 exception handlers.
1116
1117 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1118 how you got to a certain point in your code, even when no exceptions were
1119 raised. The stack frames are printed following a header line which says::
1120
1121 Stack (most recent call last):
1122
1123 This mimics the `Traceback (most recent call last):` which is used when
1124 displaying exception frames.
1125
1126 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001127 dictionary which is used to populate the __dict__ of the LogRecord created for
1128 the logging event with user-defined attributes. These custom attributes can then
1129 be used as you like. For example, they could be incorporated into logged
1130 messages. For example::
1131
1132 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1133 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001134 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001135 logger = logging.getLogger("tcpserver")
1136 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1137
1138 would print something like ::
1139
1140 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1141
1142 The keys in the dictionary passed in *extra* should not clash with the keys used
1143 by the logging system. (See the :class:`Formatter` documentation for more
1144 information on which keys are used by the logging system.)
1145
1146 If you choose to use these attributes in logged messages, you need to exercise
1147 some care. In the above example, for instance, the :class:`Formatter` has been
1148 set up with a format string which expects 'clientip' and 'user' in the attribute
1149 dictionary of the LogRecord. If these are missing, the message will not be
1150 logged because a string formatting exception will occur. So in this case, you
1151 always need to pass the *extra* dictionary with these keys.
1152
1153 While this might be annoying, this feature is intended for use in specialized
1154 circumstances, such as multi-threaded servers where the same code executes in
1155 many contexts, and interesting conditions which arise are dependent on this
1156 context (such as remote client IP address and authenticated user name, in the
1157 above example). In such circumstances, it is likely that specialized
1158 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1159
Vinay Sajip8593ae62010-11-14 21:33:04 +00001160 .. versionadded:: 3.2
1161 The *stack_info* parameter was added.
1162
Georg Brandl116aa622007-08-15 14:28:22 +00001163
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001164.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001165
1166 Logs a message with level :const:`INFO` on this logger. The arguments are
1167 interpreted as for :meth:`debug`.
1168
1169
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001170.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001171
1172 Logs a message with level :const:`WARNING` on this logger. The arguments are
1173 interpreted as for :meth:`debug`.
1174
1175
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001176.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001177
1178 Logs a message with level :const:`ERROR` on this logger. The arguments are
1179 interpreted as for :meth:`debug`.
1180
1181
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001182.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001183
1184 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1185 interpreted as for :meth:`debug`.
1186
1187
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001188.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001189
1190 Logs a message with integer level *lvl* on this logger. The other arguments are
1191 interpreted as for :meth:`debug`.
1192
1193
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001194.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001195
1196 Logs a message with level :const:`ERROR` on this logger. The arguments are
1197 interpreted as for :meth:`debug`. Exception info is added to the logging
1198 message. This method should only be called from an exception handler.
1199
1200
1201.. method:: Logger.addFilter(filt)
1202
1203 Adds the specified filter *filt* to this logger.
1204
1205
1206.. method:: Logger.removeFilter(filt)
1207
1208 Removes the specified filter *filt* from this logger.
1209
1210
1211.. method:: Logger.filter(record)
1212
1213 Applies this logger's filters to the record and returns a true value if the
1214 record is to be processed.
1215
1216
1217.. method:: Logger.addHandler(hdlr)
1218
1219 Adds the specified handler *hdlr* to this logger.
1220
1221
1222.. method:: Logger.removeHandler(hdlr)
1223
1224 Removes the specified handler *hdlr* from this logger.
1225
1226
Vinay Sajip8593ae62010-11-14 21:33:04 +00001227.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001228
1229 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001230 number, function name and stack information as a 4-element tuple. The stack
1231 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001232
Georg Brandl116aa622007-08-15 14:28:22 +00001233
1234.. method:: Logger.handle(record)
1235
1236 Handles a record by passing it to all handlers associated with this logger and
1237 its ancestors (until a false value of *propagate* is found). This method is used
1238 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001239 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001240
1241
Vinay Sajip8593ae62010-11-14 21:33:04 +00001242.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244 This is a factory method which can be overridden in subclasses to create
1245 specialized :class:`LogRecord` instances.
1246
Vinay Sajip83eadd12010-09-20 10:31:18 +00001247.. method:: Logger.hasHandlers()
1248
1249 Checks to see if this logger has any handlers configured. This is done by
1250 looking for handlers in this logger and its parents in the logger hierarchy.
1251 Returns True if a handler was found, else False. The method stops searching
1252 up the hierarchy whenever a logger with the "propagate" attribute set to
1253 False is found - that will be the last logger which is checked for the
1254 existence of handlers.
1255
1256.. versionadded:: 3.2
1257
1258The :meth:`hasHandlers` method was not present in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001259
1260.. _minimal-example:
1261
1262Basic example
1263-------------
1264
Georg Brandl116aa622007-08-15 14:28:22 +00001265The :mod:`logging` package provides a lot of flexibility, and its configuration
1266can appear daunting. This section demonstrates that simple use of the logging
1267package is possible.
1268
1269The simplest example shows logging to the console::
1270
1271 import logging
1272
1273 logging.debug('A debug message')
1274 logging.info('Some information')
1275 logging.warning('A shot across the bows')
1276
1277If you run the above script, you'll see this::
1278
1279 WARNING:root:A shot across the bows
1280
1281Because no particular logger was specified, the system used the root logger. The
1282debug and info messages didn't appear because by default, the root logger is
1283configured to only handle messages with a severity of WARNING or above. The
1284message format is also a configuration default, as is the output destination of
1285the messages - ``sys.stderr``. The severity level, the message format and
1286destination can be easily changed, as shown in the example below::
1287
1288 import logging
1289
1290 logging.basicConfig(level=logging.DEBUG,
1291 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001292 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001293 filemode='w')
1294 logging.debug('A debug message')
1295 logging.info('Some information')
1296 logging.warning('A shot across the bows')
1297
1298The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001299which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001300something like the following::
1301
1302 2004-07-02 13:00:08,743 DEBUG A debug message
1303 2004-07-02 13:00:08,743 INFO Some information
1304 2004-07-02 13:00:08,743 WARNING A shot across the bows
1305
1306This time, all messages with a severity of DEBUG or above were handled, and the
1307format of the messages was also changed, and output went to the specified file
1308rather than the console.
1309
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001310.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001311
1312Formatting uses the old Python string formatting - see section
1313:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001314specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1315documentation.
1316
1317+-------------------+-----------------------------------------------+
1318| Format | Description |
1319+===================+===============================================+
1320| ``%(name)s`` | Name of the logger (logging channel). |
1321+-------------------+-----------------------------------------------+
1322| ``%(levelname)s`` | Text logging level for the message |
1323| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1324| | ``'ERROR'``, ``'CRITICAL'``). |
1325+-------------------+-----------------------------------------------+
1326| ``%(asctime)s`` | Human-readable time when the |
1327| | :class:`LogRecord` was created. By default |
1328| | this is of the form "2003-07-08 16:49:45,896" |
1329| | (the numbers after the comma are millisecond |
1330| | portion of the time). |
1331+-------------------+-----------------------------------------------+
1332| ``%(message)s`` | The logged message. |
1333+-------------------+-----------------------------------------------+
1334
1335To change the date/time format, you can pass an additional keyword parameter,
1336*datefmt*, as in the following::
1337
1338 import logging
1339
1340 logging.basicConfig(level=logging.DEBUG,
1341 format='%(asctime)s %(levelname)-8s %(message)s',
1342 datefmt='%a, %d %b %Y %H:%M:%S',
1343 filename='/temp/myapp.log',
1344 filemode='w')
1345 logging.debug('A debug message')
1346 logging.info('Some information')
1347 logging.warning('A shot across the bows')
1348
1349which would result in output like ::
1350
1351 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1352 Fri, 02 Jul 2004 13:06:18 INFO Some information
1353 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1354
1355The date format string follows the requirements of :func:`strftime` - see the
1356documentation for the :mod:`time` module.
1357
1358If, instead of sending logging output to the console or a file, you'd rather use
1359a file-like object which you have created separately, you can pass it to
1360:func:`basicConfig` using the *stream* keyword argument. Note that if both
1361*stream* and *filename* keyword arguments are passed, the *stream* argument is
1362ignored.
1363
1364Of course, you can put variable information in your output. To do this, simply
1365have the message be a format string and pass in additional arguments containing
1366the variable information, as in the following example::
1367
1368 import logging
1369
1370 logging.basicConfig(level=logging.DEBUG,
1371 format='%(asctime)s %(levelname)-8s %(message)s',
1372 datefmt='%a, %d %b %Y %H:%M:%S',
1373 filename='/temp/myapp.log',
1374 filemode='w')
1375 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1376
1377which would result in ::
1378
1379 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1380
1381
1382.. _multiple-destinations:
1383
1384Logging to multiple destinations
1385--------------------------------
1386
1387Let's say you want to log to console and file with different message formats and
1388in differing circumstances. Say you want to log messages with levels of DEBUG
1389and higher to file, and those messages at level INFO and higher to the console.
1390Let's also assume that the file should contain timestamps, but the console
1391messages should not. Here's how you can achieve this::
1392
1393 import logging
1394
1395 # set up logging to file - see previous section for more details
1396 logging.basicConfig(level=logging.DEBUG,
1397 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1398 datefmt='%m-%d %H:%M',
1399 filename='/temp/myapp.log',
1400 filemode='w')
1401 # define a Handler which writes INFO messages or higher to the sys.stderr
1402 console = logging.StreamHandler()
1403 console.setLevel(logging.INFO)
1404 # set a format which is simpler for console use
1405 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1406 # tell the handler to use this format
1407 console.setFormatter(formatter)
1408 # add the handler to the root logger
1409 logging.getLogger('').addHandler(console)
1410
1411 # Now, we can log to the root logger, or any other logger. First the root...
1412 logging.info('Jackdaws love my big sphinx of quartz.')
1413
1414 # Now, define a couple of other loggers which might represent areas in your
1415 # application:
1416
1417 logger1 = logging.getLogger('myapp.area1')
1418 logger2 = logging.getLogger('myapp.area2')
1419
1420 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1421 logger1.info('How quickly daft jumping zebras vex.')
1422 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1423 logger2.error('The five boxing wizards jump quickly.')
1424
1425When you run this, on the console you will see ::
1426
1427 root : INFO Jackdaws love my big sphinx of quartz.
1428 myapp.area1 : INFO How quickly daft jumping zebras vex.
1429 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1430 myapp.area2 : ERROR The five boxing wizards jump quickly.
1431
1432and in the file you will see something like ::
1433
1434 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1435 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1436 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1437 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1438 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1439
1440As you can see, the DEBUG message only shows up in the file. The other messages
1441are sent to both destinations.
1442
1443This example uses console and file handlers, but you can use any number and
1444combination of handlers you choose.
1445
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001446.. _logging-exceptions:
1447
1448Exceptions raised during logging
1449--------------------------------
1450
1451The logging package is designed to swallow exceptions which occur while logging
1452in production. This is so that errors which occur while handling logging events
1453- such as logging misconfiguration, network or other similar errors - do not
1454cause the application using logging to terminate prematurely.
1455
1456:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1457swallowed. Other exceptions which occur during the :meth:`emit` method of a
1458:class:`Handler` subclass are passed to its :meth:`handleError` method.
1459
1460The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001461to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1462traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001463
Georg Brandlef871f62010-03-12 10:06:40 +00001464**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001465during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001466occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001467usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001468
Christian Heimes790c8232008-01-07 21:14:23 +00001469.. _context-info:
1470
1471Adding contextual information to your logging output
1472----------------------------------------------------
1473
1474Sometimes you want logging output to contain contextual information in
1475addition to the parameters passed to the logging call. For example, in a
1476networked application, it may be desirable to log client-specific information
1477in the log (e.g. remote client's username, or IP address). Although you could
1478use the *extra* parameter to achieve this, it's not always convenient to pass
1479the information in this way. While it might be tempting to create
1480:class:`Logger` instances on a per-connection basis, this is not a good idea
1481because these instances are not garbage collected. While this is not a problem
1482in practice, when the number of :class:`Logger` instances is dependent on the
1483level of granularity you want to use in logging an application, it could
1484be hard to manage if the number of :class:`Logger` instances becomes
1485effectively unbounded.
1486
Vinay Sajipc31be632010-09-06 22:18:20 +00001487
1488Using LoggerAdapters to impart contextual information
1489^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1490
Christian Heimes04c420f2008-01-18 18:40:46 +00001491An easy way in which you can pass contextual information to be output along
1492with logging event information is to use the :class:`LoggerAdapter` class.
1493This class is designed to look like a :class:`Logger`, so that you can call
1494:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1495:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1496same signatures as their counterparts in :class:`Logger`, so you can use the
1497two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001498
Christian Heimes04c420f2008-01-18 18:40:46 +00001499When you create an instance of :class:`LoggerAdapter`, you pass it a
1500:class:`Logger` instance and a dict-like object which contains your contextual
1501information. When you call one of the logging methods on an instance of
1502:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1503:class:`Logger` passed to its constructor, and arranges to pass the contextual
1504information in the delegated call. Here's a snippet from the code of
1505:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001506
Christian Heimes04c420f2008-01-18 18:40:46 +00001507 def debug(self, msg, *args, **kwargs):
1508 """
1509 Delegate a debug call to the underlying logger, after adding
1510 contextual information from this adapter instance.
1511 """
1512 msg, kwargs = self.process(msg, kwargs)
1513 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001514
Christian Heimes04c420f2008-01-18 18:40:46 +00001515The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1516information is added to the logging output. It's passed the message and
1517keyword arguments of the logging call, and it passes back (potentially)
1518modified versions of these to use in the call to the underlying logger. The
1519default implementation of this method leaves the message alone, but inserts
1520an "extra" key in the keyword argument whose value is the dict-like object
1521passed to the constructor. Of course, if you had passed an "extra" keyword
1522argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001523
Christian Heimes04c420f2008-01-18 18:40:46 +00001524The advantage of using "extra" is that the values in the dict-like object are
1525merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1526customized strings with your :class:`Formatter` instances which know about
1527the keys of the dict-like object. If you need a different method, e.g. if you
1528want to prepend or append the contextual information to the message string,
1529you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1530to do what you need. Here's an example script which uses this class, which
1531also illustrates what dict-like behaviour is needed from an arbitrary
1532"dict-like" object for use in the constructor::
1533
Christian Heimes587c2bf2008-01-19 16:21:02 +00001534 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001535
Christian Heimes587c2bf2008-01-19 16:21:02 +00001536 class ConnInfo:
1537 """
1538 An example class which shows how an arbitrary class can be used as
1539 the 'extra' context information repository passed to a LoggerAdapter.
1540 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001541
Christian Heimes587c2bf2008-01-19 16:21:02 +00001542 def __getitem__(self, name):
1543 """
1544 To allow this instance to look like a dict.
1545 """
1546 from random import choice
1547 if name == "ip":
1548 result = choice(["127.0.0.1", "192.168.0.1"])
1549 elif name == "user":
1550 result = choice(["jim", "fred", "sheila"])
1551 else:
1552 result = self.__dict__.get(name, "?")
1553 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001554
Christian Heimes587c2bf2008-01-19 16:21:02 +00001555 def __iter__(self):
1556 """
1557 To allow iteration over keys, which will be merged into
1558 the LogRecord dict before formatting and output.
1559 """
1560 keys = ["ip", "user"]
1561 keys.extend(self.__dict__.keys())
1562 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001563
Christian Heimes587c2bf2008-01-19 16:21:02 +00001564 if __name__ == "__main__":
1565 from random import choice
1566 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1567 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1568 { "ip" : "123.231.231.123", "user" : "sheila" })
1569 logging.basicConfig(level=logging.DEBUG,
1570 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1571 a1.debug("A debug message")
1572 a1.info("An info message with %s", "some parameters")
1573 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1574 for x in range(10):
1575 lvl = choice(levels)
1576 lvlname = logging.getLevelName(lvl)
1577 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001578
1579When this script is run, the output should look something like this::
1580
Christian Heimes587c2bf2008-01-19 16:21:02 +00001581 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1582 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1583 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
1584 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
1585 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
1586 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
1587 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
1588 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
1589 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
1590 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
1591 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
1592 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 +00001593
Christian Heimes790c8232008-01-07 21:14:23 +00001594
Vinay Sajipac007992010-09-17 12:45:26 +00001595.. _filters-contextual:
1596
Vinay Sajipc31be632010-09-06 22:18:20 +00001597Using Filters to impart contextual information
1598^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1599
1600You can also add contextual information to log output using a user-defined
1601:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1602passed to them, including adding additional attributes which can then be output
1603using a suitable format string, or if needed a custom :class:`Formatter`.
1604
1605For example in a web application, the request being processed (or at least,
1606the interesting parts of it) can be stored in a threadlocal
1607(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1608add, say, information from the request - say, the remote IP address and remote
1609user's username - to the ``LogRecord``, using the attribute names 'ip' and
1610'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1611string can be used to get similar output to that shown above. Here's an example
1612script::
1613
1614 import logging
1615 from random import choice
1616
1617 class ContextFilter(logging.Filter):
1618 """
1619 This is a filter which injects contextual information into the log.
1620
1621 Rather than use actual contextual information, we just use random
1622 data in this demo.
1623 """
1624
1625 USERS = ['jim', 'fred', 'sheila']
1626 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1627
1628 def filter(self, record):
1629
1630 record.ip = choice(ContextFilter.IPS)
1631 record.user = choice(ContextFilter.USERS)
1632 return True
1633
1634 if __name__ == "__main__":
1635 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1636 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1637 { "ip" : "123.231.231.123", "user" : "sheila" })
1638 logging.basicConfig(level=logging.DEBUG,
1639 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1640 a1 = logging.getLogger("a.b.c")
1641 a2 = logging.getLogger("d.e.f")
1642
1643 f = ContextFilter()
1644 a1.addFilter(f)
1645 a2.addFilter(f)
1646 a1.debug("A debug message")
1647 a1.info("An info message with %s", "some parameters")
1648 for x in range(10):
1649 lvl = choice(levels)
1650 lvlname = logging.getLevelName(lvl)
1651 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1652
1653which, when run, produces something like::
1654
1655 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1656 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1657 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
1658 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
1659 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
1660 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
1661 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
1662 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
1663 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
1664 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
1665 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
1666 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
1667
1668
Vinay Sajipd31f3632010-06-29 15:31:15 +00001669.. _multiple-processes:
1670
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001671Logging to a single file from multiple processes
1672------------------------------------------------
1673
1674Although logging is thread-safe, and logging to a single file from multiple
1675threads in a single process *is* supported, logging to a single file from
1676*multiple processes* is *not* supported, because there is no standard way to
1677serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001678need to log to a single file from multiple processes, one way of doing this is
1679to have all the processes log to a :class:`SocketHandler`, and have a separate
1680process which implements a socket server which reads from the socket and logs
1681to file. (If you prefer, you can dedicate one thread in one of the existing
1682processes to perform this function.) The following section documents this
1683approach in more detail and includes a working socket receiver which can be
1684used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001685
Vinay Sajip5a92b132009-08-15 23:35:08 +00001686If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001687:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001688:class:`Lock` class from this module to serialize access to the file from
1689your processes. The existing :class:`FileHandler` and subclasses do not make
1690use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001691Note that at present, the :mod:`multiprocessing` module does not provide
1692working lock functionality on all platforms (see
1693http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001694
Vinay Sajip121a1c42010-09-08 10:46:15 +00001695.. currentmodule:: logging.handlers
1696
1697Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1698all logging events to one of the processes in your multi-process application.
1699The following example script demonstrates how you can do this; in the example
1700a separate listener process listens for events sent by other processes and logs
1701them according to its own logging configuration. Although the example only
1702demonstrates one way of doing it (for example, you may want to use a listener
1703thread rather than a separate listener process - the implementation would be
1704analogous) it does allow for completely different logging configurations for
1705the listener and the other processes in your application, and can be used as
1706the basis for code meeting your own specific requirements::
1707
1708 # You'll need these imports in your own code
1709 import logging
1710 import logging.handlers
1711 import multiprocessing
1712
1713 # Next two import lines for this demo only
1714 from random import choice, random
1715 import time
1716
1717 #
1718 # Because you'll want to define the logging configurations for listener and workers, the
1719 # listener and worker process functions take a configurer parameter which is a callable
1720 # for configuring logging for that process. These functions are also passed the queue,
1721 # which they use for communication.
1722 #
1723 # In practice, you can configure the listener however you want, but note that in this
1724 # simple example, the listener does not apply level or filter logic to received records.
1725 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1726 # sending events which would be filtered out between processes.
1727 #
1728 # The size of the rotated files is made small so you can see the results easily.
1729 def listener_configurer():
1730 root = logging.getLogger()
1731 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
1732 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1733 h.setFormatter(f)
1734 root.addHandler(h)
1735
1736 # This is the listener process top-level loop: wait for logging events
1737 # (LogRecords)on the queue and handle them, quit when you get a None for a
1738 # LogRecord.
1739 def listener_process(queue, configurer):
1740 configurer()
1741 while True:
1742 try:
1743 record = queue.get()
1744 if record is None: # We send this as a sentinel to tell the listener to quit.
1745 break
1746 logger = logging.getLogger(record.name)
1747 logger.handle(record) # No level or filter logic applied - just do it!
1748 except (KeyboardInterrupt, SystemExit):
1749 raise
1750 except:
1751 import sys, traceback
1752 print >> sys.stderr, 'Whoops! Problem:'
1753 traceback.print_exc(file=sys.stderr)
1754
1755 # Arrays used for random selections in this demo
1756
1757 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1758 logging.ERROR, logging.CRITICAL]
1759
1760 LOGGERS = ['a.b.c', 'd.e.f']
1761
1762 MESSAGES = [
1763 'Random message #1',
1764 'Random message #2',
1765 'Random message #3',
1766 ]
1767
1768 # The worker configuration is done at the start of the worker process run.
1769 # Note that on Windows you can't rely on fork semantics, so each process
1770 # will run the logging configuration code when it starts.
1771 def worker_configurer(queue):
1772 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1773 root = logging.getLogger()
1774 root.addHandler(h)
1775 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
1776
1777 # This is the worker process top-level loop, which just logs ten events with
1778 # random intervening delays before terminating.
1779 # The print messages are just so you know it's doing something!
1780 def worker_process(queue, configurer):
1781 configurer(queue)
1782 name = multiprocessing.current_process().name
1783 print('Worker started: %s' % name)
1784 for i in range(10):
1785 time.sleep(random())
1786 logger = logging.getLogger(choice(LOGGERS))
1787 level = choice(LEVELS)
1788 message = choice(MESSAGES)
1789 logger.log(level, message)
1790 print('Worker finished: %s' % name)
1791
1792 # Here's where the demo gets orchestrated. Create the queue, create and start
1793 # the listener, create ten workers and start them, wait for them to finish,
1794 # then send a None to the queue to tell the listener to finish.
1795 def main():
1796 queue = multiprocessing.Queue(-1)
1797 listener = multiprocessing.Process(target=listener_process,
1798 args=(queue, listener_configurer))
1799 listener.start()
1800 workers = []
1801 for i in range(10):
1802 worker = multiprocessing.Process(target=worker_process,
1803 args=(queue, worker_configurer))
1804 workers.append(worker)
1805 worker.start()
1806 for w in workers:
1807 w.join()
1808 queue.put_nowait(None)
1809 listener.join()
1810
1811 if __name__ == '__main__':
1812 main()
1813
1814
1815.. currentmodule:: logging
1816
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001817
Georg Brandl116aa622007-08-15 14:28:22 +00001818.. _network-logging:
1819
1820Sending and receiving logging events across a network
1821-----------------------------------------------------
1822
1823Let's say you want to send logging events across a network, and handle them at
1824the receiving end. A simple way of doing this is attaching a
1825:class:`SocketHandler` instance to the root logger at the sending end::
1826
1827 import logging, logging.handlers
1828
1829 rootLogger = logging.getLogger('')
1830 rootLogger.setLevel(logging.DEBUG)
1831 socketHandler = logging.handlers.SocketHandler('localhost',
1832 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1833 # don't bother with a formatter, since a socket handler sends the event as
1834 # an unformatted pickle
1835 rootLogger.addHandler(socketHandler)
1836
1837 # Now, we can log to the root logger, or any other logger. First the root...
1838 logging.info('Jackdaws love my big sphinx of quartz.')
1839
1840 # Now, define a couple of other loggers which might represent areas in your
1841 # application:
1842
1843 logger1 = logging.getLogger('myapp.area1')
1844 logger2 = logging.getLogger('myapp.area2')
1845
1846 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1847 logger1.info('How quickly daft jumping zebras vex.')
1848 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1849 logger2.error('The five boxing wizards jump quickly.')
1850
Alexandre Vassalottice261952008-05-12 02:31:37 +00001851At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001852module. Here is a basic working example::
1853
Georg Brandla35f4b92009-05-31 16:41:59 +00001854 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001855 import logging
1856 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001857 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001858 import struct
1859
1860
Alexandre Vassalottice261952008-05-12 02:31:37 +00001861 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001862 """Handler for a streaming logging request.
1863
1864 This basically logs the record using whatever logging policy is
1865 configured locally.
1866 """
1867
1868 def handle(self):
1869 """
1870 Handle multiple requests - each expected to be a 4-byte length,
1871 followed by the LogRecord in pickle format. Logs the record
1872 according to whatever policy is configured locally.
1873 """
Collin Winter46334482007-09-10 00:49:57 +00001874 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001875 chunk = self.connection.recv(4)
1876 if len(chunk) < 4:
1877 break
1878 slen = struct.unpack(">L", chunk)[0]
1879 chunk = self.connection.recv(slen)
1880 while len(chunk) < slen:
1881 chunk = chunk + self.connection.recv(slen - len(chunk))
1882 obj = self.unPickle(chunk)
1883 record = logging.makeLogRecord(obj)
1884 self.handleLogRecord(record)
1885
1886 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001887 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001888
1889 def handleLogRecord(self, record):
1890 # if a name is specified, we use the named logger rather than the one
1891 # implied by the record.
1892 if self.server.logname is not None:
1893 name = self.server.logname
1894 else:
1895 name = record.name
1896 logger = logging.getLogger(name)
1897 # N.B. EVERY record gets logged. This is because Logger.handle
1898 # is normally called AFTER logger-level filtering. If you want
1899 # to do filtering, do it at the client end to save wasting
1900 # cycles and network bandwidth!
1901 logger.handle(record)
1902
Alexandre Vassalottice261952008-05-12 02:31:37 +00001903 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001904 """simple TCP socket-based logging receiver suitable for testing.
1905 """
1906
1907 allow_reuse_address = 1
1908
1909 def __init__(self, host='localhost',
1910 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1911 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001912 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001913 self.abort = 0
1914 self.timeout = 1
1915 self.logname = None
1916
1917 def serve_until_stopped(self):
1918 import select
1919 abort = 0
1920 while not abort:
1921 rd, wr, ex = select.select([self.socket.fileno()],
1922 [], [],
1923 self.timeout)
1924 if rd:
1925 self.handle_request()
1926 abort = self.abort
1927
1928 def main():
1929 logging.basicConfig(
1930 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1931 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001932 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001933 tcpserver.serve_until_stopped()
1934
1935 if __name__ == "__main__":
1936 main()
1937
1938First run the server, and then the client. On the client side, nothing is
1939printed on the console; on the server side, you should see something like::
1940
1941 About to start TCP server...
1942 59 root INFO Jackdaws love my big sphinx of quartz.
1943 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1944 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1945 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1946 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1947
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001948Note that there are some security issues with pickle in some scenarios. If
1949these affect you, you can use an alternative serialization scheme by overriding
1950the :meth:`makePickle` method and implementing your alternative there, as
1951well as adapting the above script to use your alternative serialization.
1952
Vinay Sajip4039aff2010-09-11 10:25:28 +00001953.. _arbitrary-object-messages:
1954
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001955Using arbitrary objects as messages
1956-----------------------------------
1957
1958In the preceding sections and examples, it has been assumed that the message
1959passed when logging the event is a string. However, this is not the only
1960possibility. You can pass an arbitrary object as a message, and its
1961:meth:`__str__` method will be called when the logging system needs to convert
1962it to a string representation. In fact, if you want to, you can avoid
1963computing a string representation altogether - for example, the
1964:class:`SocketHandler` emits an event by pickling it and sending it over the
1965wire.
1966
Vinay Sajip55778922010-09-23 09:09:15 +00001967Dealing with handlers that block
1968--------------------------------
1969
1970.. currentmodule:: logging.handlers
1971
1972Sometimes you have to get your logging handlers to do their work without
1973blocking the thread you’re logging from. This is common in Web applications,
1974though of course it also occurs in other scenarios.
1975
1976A common culprit which demonstrates sluggish behaviour is the
1977:class:`SMTPHandler`: sending emails can take a long time, for a
1978number of reasons outside the developer’s control (for example, a poorly
1979performing mail or network infrastructure). But almost any network-based
1980handler can block: Even a :class:`SocketHandler` operation may do a
1981DNS query under the hood which is too slow (and this query can be deep in the
1982socket library code, below the Python layer, and outside your control).
1983
1984One solution is to use a two-part approach. For the first part, attach only a
1985:class:`QueueHandler` to those loggers which are accessed from
1986performance-critical threads. They simply write to their queue, which can be
1987sized to a large enough capacity or initialized with no upper bound to their
1988size. The write to the queue will typically be accepted quickly, though you
1989will probably need to catch the :ref:`queue.Full` exception as a precaution
1990in your code. If you are a library developer who has performance-critical
1991threads in their code, be sure to document this (together with a suggestion to
1992attach only ``QueueHandlers`` to your loggers) for the benefit of other
1993developers who will use your code.
1994
1995The second part of the solution is :class:`QueueListener`, which has been
1996designed as the counterpart to :class:`QueueHandler`. A
1997:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
1998and it fires up an internal thread which listens to its queue for LogRecords
1999sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2000matter). The ``LogRecords`` are removed from the queue and passed to the
2001handlers for processing.
2002
2003The advantage of having a separate :class:`QueueListener` class is that you
2004can use the same instance to service multiple ``QueueHandlers``. This is more
2005resource-friendly than, say, having threaded versions of the existing handler
2006classes, which would eat up one thread per handler for no particular benefit.
2007
2008An example of using these two classes follows (imports omitted)::
2009
2010 que = queue.Queue(-1) # no limit on size
2011 queue_handler = QueueHandler(que)
2012 handler = logging.StreamHandler()
2013 listener = QueueListener(que, handler)
2014 root = logging.getLogger()
2015 root.addHandler(queue_handler)
2016 formatter = logging.Formatter('%(threadName)s: %(message)s')
2017 handler.setFormatter(formatter)
2018 listener.start()
2019 # The log output will display the thread which generated
2020 # the event (the main thread) rather than the internal
2021 # thread which monitors the internal queue. This is what
2022 # you want to happen.
2023 root.warning('Look out!')
2024 listener.stop()
2025
2026which, when run, will produce::
2027
2028 MainThread: Look out!
2029
2030
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002031Optimization
2032------------
2033
2034Formatting of message arguments is deferred until it cannot be avoided.
2035However, computing the arguments passed to the logging method can also be
2036expensive, and you may want to avoid doing it if the logger will just throw
2037away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2038method which takes a level argument and returns true if the event would be
2039created by the Logger for that level of call. You can write code like this::
2040
2041 if logger.isEnabledFor(logging.DEBUG):
2042 logger.debug("Message with %s, %s", expensive_func1(),
2043 expensive_func2())
2044
2045so that if the logger's threshold is set above ``DEBUG``, the calls to
2046:func:`expensive_func1` and :func:`expensive_func2` are never made.
2047
2048There are other optimizations which can be made for specific applications which
2049need more precise control over what logging information is collected. Here's a
2050list of things you can do to avoid processing during logging which you don't
2051need:
2052
2053+-----------------------------------------------+----------------------------------------+
2054| What you don't want to collect | How to avoid collecting it |
2055+===============================================+========================================+
2056| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2057+-----------------------------------------------+----------------------------------------+
2058| Threading information. | Set ``logging.logThreads`` to ``0``. |
2059+-----------------------------------------------+----------------------------------------+
2060| Process information. | Set ``logging.logProcesses`` to ``0``. |
2061+-----------------------------------------------+----------------------------------------+
2062
2063Also note that the core logging module only includes the basic handlers. If
2064you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2065take up any memory.
2066
2067.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002068
2069Handler Objects
2070---------------
2071
2072Handlers have the following attributes and methods. Note that :class:`Handler`
2073is never instantiated directly; this class acts as a base for more useful
2074subclasses. However, the :meth:`__init__` method in subclasses needs to call
2075:meth:`Handler.__init__`.
2076
2077
2078.. method:: Handler.__init__(level=NOTSET)
2079
2080 Initializes the :class:`Handler` instance by setting its level, setting the list
2081 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2082 serializing access to an I/O mechanism.
2083
2084
2085.. method:: Handler.createLock()
2086
2087 Initializes a thread lock which can be used to serialize access to underlying
2088 I/O functionality which may not be threadsafe.
2089
2090
2091.. method:: Handler.acquire()
2092
2093 Acquires the thread lock created with :meth:`createLock`.
2094
2095
2096.. method:: Handler.release()
2097
2098 Releases the thread lock acquired with :meth:`acquire`.
2099
2100
2101.. method:: Handler.setLevel(lvl)
2102
2103 Sets the threshold for this handler to *lvl*. Logging messages which are less
2104 severe than *lvl* will be ignored. When a handler is created, the level is set
2105 to :const:`NOTSET` (which causes all messages to be processed).
2106
2107
2108.. method:: Handler.setFormatter(form)
2109
2110 Sets the :class:`Formatter` for this handler to *form*.
2111
2112
2113.. method:: Handler.addFilter(filt)
2114
2115 Adds the specified filter *filt* to this handler.
2116
2117
2118.. method:: Handler.removeFilter(filt)
2119
2120 Removes the specified filter *filt* from this handler.
2121
2122
2123.. method:: Handler.filter(record)
2124
2125 Applies this handler's filters to the record and returns a true value if the
2126 record is to be processed.
2127
2128
2129.. method:: Handler.flush()
2130
2131 Ensure all logging output has been flushed. This version does nothing and is
2132 intended to be implemented by subclasses.
2133
2134
2135.. method:: Handler.close()
2136
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002137 Tidy up any resources used by the handler. This version does no output but
2138 removes the handler from an internal list of handlers which is closed when
2139 :func:`shutdown` is called. Subclasses should ensure that this gets called
2140 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002141
2142
2143.. method:: Handler.handle(record)
2144
2145 Conditionally emits the specified logging record, depending on filters which may
2146 have been added to the handler. Wraps the actual emission of the record with
2147 acquisition/release of the I/O thread lock.
2148
2149
2150.. method:: Handler.handleError(record)
2151
2152 This method should be called from handlers when an exception is encountered
2153 during an :meth:`emit` call. By default it does nothing, which means that
2154 exceptions get silently ignored. This is what is mostly wanted for a logging
2155 system - most users will not care about errors in the logging system, they are
2156 more interested in application errors. You could, however, replace this with a
2157 custom handler if you wish. The specified record is the one which was being
2158 processed when the exception occurred.
2159
2160
2161.. method:: Handler.format(record)
2162
2163 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2164 default formatter for the module.
2165
2166
2167.. method:: Handler.emit(record)
2168
2169 Do whatever it takes to actually log the specified logging record. This version
2170 is intended to be implemented by subclasses and so raises a
2171 :exc:`NotImplementedError`.
2172
2173
Vinay Sajipd31f3632010-06-29 15:31:15 +00002174.. _stream-handler:
2175
Georg Brandl116aa622007-08-15 14:28:22 +00002176StreamHandler
2177^^^^^^^^^^^^^
2178
2179The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2180sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2181file-like object (or, more precisely, any object which supports :meth:`write`
2182and :meth:`flush` methods).
2183
2184
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002185.. currentmodule:: logging
2186
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002187.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002188
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002189 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002190 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2191 will be used.
2192
2193
Benjamin Petersone41251e2008-04-25 01:59:09 +00002194 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002195
Benjamin Petersone41251e2008-04-25 01:59:09 +00002196 If a formatter is specified, it is used to format the record. The record
2197 is then written to the stream with a trailing newline. If exception
2198 information is present, it is formatted using
2199 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002200
2201
Benjamin Petersone41251e2008-04-25 01:59:09 +00002202 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002203
Benjamin Petersone41251e2008-04-25 01:59:09 +00002204 Flushes the stream by calling its :meth:`flush` method. Note that the
2205 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002206 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002207
Vinay Sajip05ed6952010-10-20 20:34:09 +00002208.. versionchanged:: 3.2
2209 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2210 value ``"\n"``, which is used as the terminator when writing a formatted
2211 record to a stream. If you don't want this newline termination, you can
2212 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002213
Vinay Sajipd31f3632010-06-29 15:31:15 +00002214.. _file-handler:
2215
Georg Brandl116aa622007-08-15 14:28:22 +00002216FileHandler
2217^^^^^^^^^^^
2218
2219The :class:`FileHandler` class, located in the core :mod:`logging` package,
2220sends logging output to a disk file. It inherits the output functionality from
2221:class:`StreamHandler`.
2222
2223
Vinay Sajipd31f3632010-06-29 15:31:15 +00002224.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002225
2226 Returns a new instance of the :class:`FileHandler` class. The specified file is
2227 opened and used as the stream for logging. If *mode* is not specified,
2228 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002229 with that encoding. If *delay* is true, then file opening is deferred until the
2230 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002231
2232
Benjamin Petersone41251e2008-04-25 01:59:09 +00002233 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002234
Benjamin Petersone41251e2008-04-25 01:59:09 +00002235 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002236
2237
Benjamin Petersone41251e2008-04-25 01:59:09 +00002238 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002239
Benjamin Petersone41251e2008-04-25 01:59:09 +00002240 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002241
Vinay Sajipd31f3632010-06-29 15:31:15 +00002242.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002243
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002244NullHandler
2245^^^^^^^^^^^
2246
2247.. versionadded:: 3.1
2248
2249The :class:`NullHandler` class, located in the core :mod:`logging` package,
2250does not do any formatting or output. It is essentially a "no-op" handler
2251for use by library developers.
2252
2253
2254.. class:: NullHandler()
2255
2256 Returns a new instance of the :class:`NullHandler` class.
2257
2258
2259 .. method:: emit(record)
2260
2261 This method does nothing.
2262
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002263 .. method:: handle(record)
2264
2265 This method does nothing.
2266
2267 .. method:: createLock()
2268
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002269 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002270 underlying I/O to which access needs to be serialized.
2271
2272
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002273See :ref:`library-config` for more information on how to use
2274:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002275
Vinay Sajipd31f3632010-06-29 15:31:15 +00002276.. _watched-file-handler:
2277
Georg Brandl116aa622007-08-15 14:28:22 +00002278WatchedFileHandler
2279^^^^^^^^^^^^^^^^^^
2280
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002281.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002282
Georg Brandl116aa622007-08-15 14:28:22 +00002283The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2284module, is a :class:`FileHandler` which watches the file it is logging to. If
2285the file changes, it is closed and reopened using the file name.
2286
2287A file change can happen because of usage of programs such as *newsyslog* and
2288*logrotate* which perform log file rotation. This handler, intended for use
2289under Unix/Linux, watches the file to see if it has changed since the last emit.
2290(A file is deemed to have changed if its device or inode have changed.) If the
2291file has changed, the old file stream is closed, and the file opened to get a
2292new stream.
2293
2294This handler is not appropriate for use under Windows, because under Windows
2295open log files cannot be moved or renamed - logging opens the files with
2296exclusive locks - and so there is no need for such a handler. Furthermore,
2297*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2298this value.
2299
2300
Christian Heimese7a15bb2008-01-24 16:21:45 +00002301.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002302
2303 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2304 file is opened and used as the stream for logging. If *mode* is not specified,
2305 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002306 with that encoding. If *delay* is true, then file opening is deferred until the
2307 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002308
2309
Benjamin Petersone41251e2008-04-25 01:59:09 +00002310 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002311
Benjamin Petersone41251e2008-04-25 01:59:09 +00002312 Outputs the record to the file, but first checks to see if the file has
2313 changed. If it has, the existing stream is flushed and closed and the
2314 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002315
Vinay Sajipd31f3632010-06-29 15:31:15 +00002316.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002317
2318RotatingFileHandler
2319^^^^^^^^^^^^^^^^^^^
2320
2321The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2322module, supports rotation of disk log files.
2323
2324
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002325.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002326
2327 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2328 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002329 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2330 with that encoding. If *delay* is true, then file opening is deferred until the
2331 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002332
2333 You can use the *maxBytes* and *backupCount* values to allow the file to
2334 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2335 the file is closed and a new file is silently opened for output. Rollover occurs
2336 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2337 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2338 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2339 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2340 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2341 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2342 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2343 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2344 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2345
2346
Benjamin Petersone41251e2008-04-25 01:59:09 +00002347 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002348
Benjamin Petersone41251e2008-04-25 01:59:09 +00002349 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002350
2351
Benjamin Petersone41251e2008-04-25 01:59:09 +00002352 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002353
Benjamin Petersone41251e2008-04-25 01:59:09 +00002354 Outputs the record to the file, catering for rollover as described
2355 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002356
Vinay Sajipd31f3632010-06-29 15:31:15 +00002357.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002358
2359TimedRotatingFileHandler
2360^^^^^^^^^^^^^^^^^^^^^^^^
2361
2362The :class:`TimedRotatingFileHandler` class, located in the
2363:mod:`logging.handlers` module, supports rotation of disk log files at certain
2364timed intervals.
2365
2366
Vinay Sajipd31f3632010-06-29 15:31:15 +00002367.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002368
2369 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2370 specified file is opened and used as the stream for logging. On rotating it also
2371 sets the filename suffix. Rotating happens based on the product of *when* and
2372 *interval*.
2373
2374 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002375 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002376
Christian Heimesb558a2e2008-03-02 22:46:37 +00002377 +----------------+-----------------------+
2378 | Value | Type of interval |
2379 +================+=======================+
2380 | ``'S'`` | Seconds |
2381 +----------------+-----------------------+
2382 | ``'M'`` | Minutes |
2383 +----------------+-----------------------+
2384 | ``'H'`` | Hours |
2385 +----------------+-----------------------+
2386 | ``'D'`` | Days |
2387 +----------------+-----------------------+
2388 | ``'W'`` | Week day (0=Monday) |
2389 +----------------+-----------------------+
2390 | ``'midnight'`` | Roll over at midnight |
2391 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002392
Christian Heimesb558a2e2008-03-02 22:46:37 +00002393 The system will save old log files by appending extensions to the filename.
2394 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002395 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002396 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002397
2398 When computing the next rollover time for the first time (when the handler
2399 is created), the last modification time of an existing log file, or else
2400 the current time, is used to compute when the next rotation will occur.
2401
Georg Brandl0c77a822008-06-10 16:37:50 +00002402 If the *utc* argument is true, times in UTC will be used; otherwise
2403 local time is used.
2404
2405 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002406 will be kept, and if more would be created when rollover occurs, the oldest
2407 one is deleted. The deletion logic uses the interval to determine which
2408 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002409
Vinay Sajipd31f3632010-06-29 15:31:15 +00002410 If *delay* is true, then file opening is deferred until the first call to
2411 :meth:`emit`.
2412
Georg Brandl116aa622007-08-15 14:28:22 +00002413
Benjamin Petersone41251e2008-04-25 01:59:09 +00002414 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002415
Benjamin Petersone41251e2008-04-25 01:59:09 +00002416 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002417
2418
Benjamin Petersone41251e2008-04-25 01:59:09 +00002419 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002420
Benjamin Petersone41251e2008-04-25 01:59:09 +00002421 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002422
2423
Vinay Sajipd31f3632010-06-29 15:31:15 +00002424.. _socket-handler:
2425
Georg Brandl116aa622007-08-15 14:28:22 +00002426SocketHandler
2427^^^^^^^^^^^^^
2428
2429The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2430sends logging output to a network socket. The base class uses a TCP socket.
2431
2432
2433.. class:: SocketHandler(host, port)
2434
2435 Returns a new instance of the :class:`SocketHandler` class intended to
2436 communicate with a remote machine whose address is given by *host* and *port*.
2437
2438
Benjamin Petersone41251e2008-04-25 01:59:09 +00002439 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002440
Benjamin Petersone41251e2008-04-25 01:59:09 +00002441 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002442
2443
Benjamin Petersone41251e2008-04-25 01:59:09 +00002444 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002445
Benjamin Petersone41251e2008-04-25 01:59:09 +00002446 Pickles the record's attribute dictionary and writes it to the socket in
2447 binary format. If there is an error with the socket, silently drops the
2448 packet. If the connection was previously lost, re-establishes the
2449 connection. To unpickle the record at the receiving end into a
2450 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002451
2452
Benjamin Petersone41251e2008-04-25 01:59:09 +00002453 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002454
Benjamin Petersone41251e2008-04-25 01:59:09 +00002455 Handles an error which has occurred during :meth:`emit`. The most likely
2456 cause is a lost connection. Closes the socket so that we can retry on the
2457 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002458
2459
Benjamin Petersone41251e2008-04-25 01:59:09 +00002460 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002461
Benjamin Petersone41251e2008-04-25 01:59:09 +00002462 This is a factory method which allows subclasses to define the precise
2463 type of socket they want. The default implementation creates a TCP socket
2464 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002465
2466
Benjamin Petersone41251e2008-04-25 01:59:09 +00002467 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002468
Benjamin Petersone41251e2008-04-25 01:59:09 +00002469 Pickles the record's attribute dictionary in binary format with a length
2470 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002471
Vinay Sajipd31f3632010-06-29 15:31:15 +00002472 Note that pickles aren't completely secure. If you are concerned about
2473 security, you may want to override this method to implement a more secure
2474 mechanism. For example, you can sign pickles using HMAC and then verify
2475 them on the receiving end, or alternatively you can disable unpickling of
2476 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002477
Benjamin Petersone41251e2008-04-25 01:59:09 +00002478 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002479
Benjamin Petersone41251e2008-04-25 01:59:09 +00002480 Send a pickled string *packet* to the socket. This function allows for
2481 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002482
2483
Vinay Sajipd31f3632010-06-29 15:31:15 +00002484.. _datagram-handler:
2485
Georg Brandl116aa622007-08-15 14:28:22 +00002486DatagramHandler
2487^^^^^^^^^^^^^^^
2488
2489The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2490module, inherits from :class:`SocketHandler` to support sending logging messages
2491over UDP sockets.
2492
2493
2494.. class:: DatagramHandler(host, port)
2495
2496 Returns a new instance of the :class:`DatagramHandler` class intended to
2497 communicate with a remote machine whose address is given by *host* and *port*.
2498
2499
Benjamin Petersone41251e2008-04-25 01:59:09 +00002500 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002501
Benjamin Petersone41251e2008-04-25 01:59:09 +00002502 Pickles the record's attribute dictionary and writes it to the socket in
2503 binary format. If there is an error with the socket, silently drops the
2504 packet. To unpickle the record at the receiving end into a
2505 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002506
2507
Benjamin Petersone41251e2008-04-25 01:59:09 +00002508 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002509
Benjamin Petersone41251e2008-04-25 01:59:09 +00002510 The factory method of :class:`SocketHandler` is here overridden to create
2511 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002512
2513
Benjamin Petersone41251e2008-04-25 01:59:09 +00002514 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002515
Benjamin Petersone41251e2008-04-25 01:59:09 +00002516 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002517
2518
Vinay Sajipd31f3632010-06-29 15:31:15 +00002519.. _syslog-handler:
2520
Georg Brandl116aa622007-08-15 14:28:22 +00002521SysLogHandler
2522^^^^^^^^^^^^^
2523
2524The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2525supports sending logging messages to a remote or local Unix syslog.
2526
2527
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002528.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002529
2530 Returns a new instance of the :class:`SysLogHandler` class intended to
2531 communicate with a remote Unix machine whose address is given by *address* in
2532 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002533 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002534 alternative to providing a ``(host, port)`` tuple is providing an address as a
2535 string, for example "/dev/log". In this case, a Unix domain socket is used to
2536 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002537 :const:`LOG_USER` is used. The type of socket opened depends on the
2538 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2539 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2540 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2541
Vinay Sajip972412d2010-09-23 20:31:24 +00002542 Note that if your server is not listening on UDP port 514,
2543 :class:`SysLogHandler` may appear not to work. In that case, check what
2544 address you should be using for a domain socket - it's system dependent.
2545 For example, on Linux it's usually "/dev/log" but on OS/X it's
2546 "/var/run/syslog". You'll need to check your platform and use the
2547 appropriate address (you may need to do this check at runtime if your
2548 application needs to run on several platforms). On Windows, you pretty
2549 much have to use the UDP option.
2550
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002551 .. versionchanged:: 3.2
2552 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002553
2554
Benjamin Petersone41251e2008-04-25 01:59:09 +00002555 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002556
Benjamin Petersone41251e2008-04-25 01:59:09 +00002557 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002558
2559
Benjamin Petersone41251e2008-04-25 01:59:09 +00002560 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002561
Benjamin Petersone41251e2008-04-25 01:59:09 +00002562 The record is formatted, and then sent to the syslog server. If exception
2563 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002564
2565
Benjamin Petersone41251e2008-04-25 01:59:09 +00002566 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002567
Benjamin Petersone41251e2008-04-25 01:59:09 +00002568 Encodes the facility and priority into an integer. You can pass in strings
2569 or integers - if strings are passed, internal mapping dictionaries are
2570 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002571
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002572 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2573 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002574
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002575 **Priorities**
2576
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002577 +--------------------------+---------------+
2578 | Name (string) | Symbolic value|
2579 +==========================+===============+
2580 | ``alert`` | LOG_ALERT |
2581 +--------------------------+---------------+
2582 | ``crit`` or ``critical`` | LOG_CRIT |
2583 +--------------------------+---------------+
2584 | ``debug`` | LOG_DEBUG |
2585 +--------------------------+---------------+
2586 | ``emerg`` or ``panic`` | LOG_EMERG |
2587 +--------------------------+---------------+
2588 | ``err`` or ``error`` | LOG_ERR |
2589 +--------------------------+---------------+
2590 | ``info`` | LOG_INFO |
2591 +--------------------------+---------------+
2592 | ``notice`` | LOG_NOTICE |
2593 +--------------------------+---------------+
2594 | ``warn`` or ``warning`` | LOG_WARNING |
2595 +--------------------------+---------------+
2596
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002597 **Facilities**
2598
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002599 +---------------+---------------+
2600 | Name (string) | Symbolic value|
2601 +===============+===============+
2602 | ``auth`` | LOG_AUTH |
2603 +---------------+---------------+
2604 | ``authpriv`` | LOG_AUTHPRIV |
2605 +---------------+---------------+
2606 | ``cron`` | LOG_CRON |
2607 +---------------+---------------+
2608 | ``daemon`` | LOG_DAEMON |
2609 +---------------+---------------+
2610 | ``ftp`` | LOG_FTP |
2611 +---------------+---------------+
2612 | ``kern`` | LOG_KERN |
2613 +---------------+---------------+
2614 | ``lpr`` | LOG_LPR |
2615 +---------------+---------------+
2616 | ``mail`` | LOG_MAIL |
2617 +---------------+---------------+
2618 | ``news`` | LOG_NEWS |
2619 +---------------+---------------+
2620 | ``syslog`` | LOG_SYSLOG |
2621 +---------------+---------------+
2622 | ``user`` | LOG_USER |
2623 +---------------+---------------+
2624 | ``uucp`` | LOG_UUCP |
2625 +---------------+---------------+
2626 | ``local0`` | LOG_LOCAL0 |
2627 +---------------+---------------+
2628 | ``local1`` | LOG_LOCAL1 |
2629 +---------------+---------------+
2630 | ``local2`` | LOG_LOCAL2 |
2631 +---------------+---------------+
2632 | ``local3`` | LOG_LOCAL3 |
2633 +---------------+---------------+
2634 | ``local4`` | LOG_LOCAL4 |
2635 +---------------+---------------+
2636 | ``local5`` | LOG_LOCAL5 |
2637 +---------------+---------------+
2638 | ``local6`` | LOG_LOCAL6 |
2639 +---------------+---------------+
2640 | ``local7`` | LOG_LOCAL7 |
2641 +---------------+---------------+
2642
2643 .. method:: mapPriority(levelname)
2644
2645 Maps a logging level name to a syslog priority name.
2646 You may need to override this if you are using custom levels, or
2647 if the default algorithm is not suitable for your needs. The
2648 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2649 ``CRITICAL`` to the equivalent syslog names, and all other level
2650 names to "warning".
2651
2652.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002653
2654NTEventLogHandler
2655^^^^^^^^^^^^^^^^^
2656
2657The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2658module, supports sending logging messages to a local Windows NT, Windows 2000 or
2659Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2660extensions for Python installed.
2661
2662
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002663.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002664
2665 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2666 used to define the application name as it appears in the event log. An
2667 appropriate registry entry is created using this name. The *dllname* should give
2668 the fully qualified pathname of a .dll or .exe which contains message
2669 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2670 - this is installed with the Win32 extensions and contains some basic
2671 placeholder message definitions. Note that use of these placeholders will make
2672 your event logs big, as the entire message source is held in the log. If you
2673 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2674 contains the message definitions you want to use in the event log). The
2675 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2676 defaults to ``'Application'``.
2677
2678
Benjamin Petersone41251e2008-04-25 01:59:09 +00002679 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002680
Benjamin Petersone41251e2008-04-25 01:59:09 +00002681 At this point, you can remove the application name from the registry as a
2682 source of event log entries. However, if you do this, you will not be able
2683 to see the events as you intended in the Event Log Viewer - it needs to be
2684 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002685 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002686
2687
Benjamin Petersone41251e2008-04-25 01:59:09 +00002688 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002689
Benjamin Petersone41251e2008-04-25 01:59:09 +00002690 Determines the message ID, event category and event type, and then logs
2691 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002692
2693
Benjamin Petersone41251e2008-04-25 01:59:09 +00002694 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002695
Benjamin Petersone41251e2008-04-25 01:59:09 +00002696 Returns the event category for the record. Override this if you want to
2697 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002698
2699
Benjamin Petersone41251e2008-04-25 01:59:09 +00002700 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002701
Benjamin Petersone41251e2008-04-25 01:59:09 +00002702 Returns the event type for the record. Override this if you want to
2703 specify your own types. This version does a mapping using the handler's
2704 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2705 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2706 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2707 your own levels, you will either need to override this method or place a
2708 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002709
2710
Benjamin Petersone41251e2008-04-25 01:59:09 +00002711 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002712
Benjamin Petersone41251e2008-04-25 01:59:09 +00002713 Returns the message ID for the record. If you are using your own messages,
2714 you could do this by having the *msg* passed to the logger being an ID
2715 rather than a format string. Then, in here, you could use a dictionary
2716 lookup to get the message ID. This version returns 1, which is the base
2717 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002718
Vinay Sajipd31f3632010-06-29 15:31:15 +00002719.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002720
2721SMTPHandler
2722^^^^^^^^^^^
2723
2724The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2725supports sending logging messages to an email address via SMTP.
2726
2727
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002728.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002729
2730 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2731 initialized with the from and to addresses and subject line of the email. The
2732 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2733 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2734 the standard SMTP port is used. If your SMTP server requires authentication, you
2735 can specify a (username, password) tuple for the *credentials* argument.
2736
Georg Brandl116aa622007-08-15 14:28:22 +00002737
Benjamin Petersone41251e2008-04-25 01:59:09 +00002738 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002739
Benjamin Petersone41251e2008-04-25 01:59:09 +00002740 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002741
2742
Benjamin Petersone41251e2008-04-25 01:59:09 +00002743 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002744
Benjamin Petersone41251e2008-04-25 01:59:09 +00002745 If you want to specify a subject line which is record-dependent, override
2746 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002747
Vinay Sajipd31f3632010-06-29 15:31:15 +00002748.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002749
2750MemoryHandler
2751^^^^^^^^^^^^^
2752
2753The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2754supports buffering of logging records in memory, periodically flushing them to a
2755:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2756event of a certain severity or greater is seen.
2757
2758:class:`MemoryHandler` is a subclass of the more general
2759:class:`BufferingHandler`, which is an abstract class. This buffers logging
2760records in memory. Whenever each record is added to the buffer, a check is made
2761by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2762should, then :meth:`flush` is expected to do the needful.
2763
2764
2765.. class:: BufferingHandler(capacity)
2766
2767 Initializes the handler with a buffer of the specified capacity.
2768
2769
Benjamin Petersone41251e2008-04-25 01:59:09 +00002770 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002771
Benjamin Petersone41251e2008-04-25 01:59:09 +00002772 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2773 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002774
2775
Benjamin Petersone41251e2008-04-25 01:59:09 +00002776 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002777
Benjamin Petersone41251e2008-04-25 01:59:09 +00002778 You can override this to implement custom flushing behavior. This version
2779 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002780
2781
Benjamin Petersone41251e2008-04-25 01:59:09 +00002782 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002783
Benjamin Petersone41251e2008-04-25 01:59:09 +00002784 Returns true if the buffer is up to capacity. This method can be
2785 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002786
2787
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002788.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002789
2790 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2791 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2792 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2793 set using :meth:`setTarget` before this handler does anything useful.
2794
2795
Benjamin Petersone41251e2008-04-25 01:59:09 +00002796 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002797
Benjamin Petersone41251e2008-04-25 01:59:09 +00002798 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2799 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002800
2801
Benjamin Petersone41251e2008-04-25 01:59:09 +00002802 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002803
Benjamin Petersone41251e2008-04-25 01:59:09 +00002804 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00002805 records to the target, if there is one. The buffer is also cleared when
2806 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002807
2808
Benjamin Petersone41251e2008-04-25 01:59:09 +00002809 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002810
Benjamin Petersone41251e2008-04-25 01:59:09 +00002811 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002812
2813
Benjamin Petersone41251e2008-04-25 01:59:09 +00002814 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002815
Benjamin Petersone41251e2008-04-25 01:59:09 +00002816 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002817
2818
Vinay Sajipd31f3632010-06-29 15:31:15 +00002819.. _http-handler:
2820
Georg Brandl116aa622007-08-15 14:28:22 +00002821HTTPHandler
2822^^^^^^^^^^^
2823
2824The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2825supports sending logging messages to a Web server, using either ``GET`` or
2826``POST`` semantics.
2827
2828
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002829.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002830
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002831 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
2832 of the form ``host:port``, should you need to use a specific port number.
2833 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
2834 connection will be used. If *credentials* is specified, it should be a
2835 2-tuple consisting of userid and password, which will be placed in an HTTP
2836 'Authorization' header using Basic authentication. If you specify
2837 credentials, you should also specify secure=True so that your userid and
2838 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00002839
2840
Benjamin Petersone41251e2008-04-25 01:59:09 +00002841 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002842
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002843 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002844
2845
Vinay Sajip121a1c42010-09-08 10:46:15 +00002846.. _queue-handler:
2847
2848
2849QueueHandler
2850^^^^^^^^^^^^
2851
2852The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
2853supports sending logging messages to a queue, such as those implemented in the
2854:mod:`queue` or :mod:`multiprocessing` modules.
2855
Vinay Sajip0637d492010-09-23 08:15:54 +00002856Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
2857to let handlers do their work on a separate thread from the one which does the
2858logging. This is important in Web applications and also other service
2859applications where threads servicing clients need to respond as quickly as
2860possible, while any potentially slow operations (such as sending an email via
2861:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002862
2863.. class:: QueueHandler(queue)
2864
2865 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00002866 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00002867 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00002868 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002869
2870
2871 .. method:: emit(record)
2872
Vinay Sajip0258ce82010-09-22 20:34:53 +00002873 Enqueues the result of preparing the LogRecord.
2874
2875 .. method:: prepare(record)
2876
2877 Prepares a record for queuing. The object returned by this
2878 method is enqueued.
2879
2880 The base implementation formats the record to merge the message
2881 and arguments, and removes unpickleable items from the record
2882 in-place.
2883
2884 You might want to override this method if you want to convert
2885 the record to a dict or JSON string, or send a modified copy
2886 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002887
2888 .. method:: enqueue(record)
2889
2890 Enqueues the record on the queue using ``put_nowait()``; you may
2891 want to override this if you want to use blocking behaviour, or a
2892 timeout, or a customised queue implementation.
2893
2894
2895.. versionadded:: 3.2
2896
2897The :class:`QueueHandler` class was not present in previous versions.
2898
Vinay Sajip0637d492010-09-23 08:15:54 +00002899.. queue-listener:
2900
2901QueueListener
2902^^^^^^^^^^^^^
2903
2904The :class:`QueueListener` class, located in the :mod:`logging.handlers`
2905module, supports receiving logging messages from a queue, such as those
2906implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
2907messages are received from a queue in an internal thread and passed, on
2908the same thread, to one or more handlers for processing.
2909
2910Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
2911to let handlers do their work on a separate thread from the one which does the
2912logging. This is important in Web applications and also other service
2913applications where threads servicing clients need to respond as quickly as
2914possible, while any potentially slow operations (such as sending an email via
2915:class:`SMTPHandler`) are done on a separate thread.
2916
2917.. class:: QueueListener(queue, *handlers)
2918
2919 Returns a new instance of the :class:`QueueListener` class. The instance is
2920 initialized with the queue to send messages to and a list of handlers which
2921 will handle entries placed on the queue. The queue can be any queue-
2922 like object; it's passed as-is to the :meth:`dequeue` method, which needs
2923 to know how to get messages from it.
2924
2925 .. method:: dequeue(block)
2926
2927 Dequeues a record and return it, optionally blocking.
2928
2929 The base implementation uses ``get()``. You may want to override this
2930 method if you want to use timeouts or work with custom queue
2931 implementations.
2932
2933 .. method:: prepare(record)
2934
2935 Prepare a record for handling.
2936
2937 This implementation just returns the passed-in record. You may want to
2938 override this method if you need to do any custom marshalling or
2939 manipulation of the record before passing it to the handlers.
2940
2941 .. method:: handle(record)
2942
2943 Handle a record.
2944
2945 This just loops through the handlers offering them the record
2946 to handle. The actual object passed to the handlers is that which
2947 is returned from :meth:`prepare`.
2948
2949 .. method:: start()
2950
2951 Starts the listener.
2952
2953 This starts up a background thread to monitor the queue for
2954 LogRecords to process.
2955
2956 .. method:: stop()
2957
2958 Stops the listener.
2959
2960 This asks the thread to terminate, and then waits for it to do so.
2961 Note that if you don't call this before your application exits, there
2962 may be some records still left on the queue, which won't be processed.
2963
2964.. versionadded:: 3.2
2965
2966The :class:`QueueListener` class was not present in previous versions.
2967
Vinay Sajip63891ed2010-09-13 20:02:39 +00002968.. _zeromq-handlers:
2969
Vinay Sajip0637d492010-09-23 08:15:54 +00002970Subclassing QueueHandler
2971^^^^^^^^^^^^^^^^^^^^^^^^
2972
Vinay Sajip63891ed2010-09-13 20:02:39 +00002973You can use a :class:`QueueHandler` subclass to send messages to other kinds
2974of queues, for example a ZeroMQ "publish" socket. In the example below,the
2975socket is created separately and passed to the handler (as its 'queue')::
2976
2977 import zmq # using pyzmq, the Python binding for ZeroMQ
2978 import json # for serializing records portably
2979
2980 ctx = zmq.Context()
2981 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
2982 sock.bind('tcp://*:5556') # or wherever
2983
2984 class ZeroMQSocketHandler(QueueHandler):
2985 def enqueue(self, record):
2986 data = json.dumps(record.__dict__)
2987 self.queue.send(data)
2988
Vinay Sajip0055c422010-09-14 09:42:39 +00002989 handler = ZeroMQSocketHandler(sock)
2990
2991
Vinay Sajip63891ed2010-09-13 20:02:39 +00002992Of course there are other ways of organizing this, for example passing in the
2993data needed by the handler to create the socket::
2994
2995 class ZeroMQSocketHandler(QueueHandler):
2996 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
2997 self.ctx = ctx or zmq.Context()
2998 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00002999 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003000 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003001
3002 def enqueue(self, record):
3003 data = json.dumps(record.__dict__)
3004 self.queue.send(data)
3005
Vinay Sajipde726922010-09-14 06:59:24 +00003006 def close(self):
3007 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003008
Vinay Sajip0637d492010-09-23 08:15:54 +00003009Subclassing QueueListener
3010^^^^^^^^^^^^^^^^^^^^^^^^^
3011
3012You can also subclass :class:`QueueListener` to get messages from other kinds
3013of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
3014
3015 class ZeroMQSocketListener(QueueListener):
3016 def __init__(self, uri, *handlers, **kwargs):
3017 self.ctx = kwargs.get('ctx') or zmq.Context()
3018 socket = zmq.Socket(self.ctx, zmq.SUB)
3019 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3020 socket.connect(uri)
3021
3022 def dequeue(self):
3023 msg = self.queue.recv()
3024 return logging.makeLogRecord(json.loads(msg))
3025
Christian Heimes8b0facf2007-12-04 19:30:01 +00003026.. _formatter-objects:
3027
Georg Brandl116aa622007-08-15 14:28:22 +00003028Formatter Objects
3029-----------------
3030
Benjamin Peterson75edad02009-01-01 15:05:06 +00003031.. currentmodule:: logging
3032
Georg Brandl116aa622007-08-15 14:28:22 +00003033:class:`Formatter`\ s have the following attributes and methods. They are
3034responsible for converting a :class:`LogRecord` to (usually) a string which can
3035be interpreted by either a human or an external system. The base
3036:class:`Formatter` allows a formatting string to be specified. If none is
3037supplied, the default value of ``'%(message)s'`` is used.
3038
3039A Formatter can be initialized with a format string which makes use of knowledge
3040of the :class:`LogRecord` attributes - such as the default value mentioned above
3041making use of the fact that the user's message and arguments are pre-formatted
3042into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003043standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003044for more information on string formatting.
3045
3046Currently, the useful mapping keys in a :class:`LogRecord` are:
3047
3048+-------------------------+-----------------------------------------------+
3049| Format | Description |
3050+=========================+===============================================+
3051| ``%(name)s`` | Name of the logger (logging channel). |
3052+-------------------------+-----------------------------------------------+
3053| ``%(levelno)s`` | Numeric logging level for the message |
3054| | (:const:`DEBUG`, :const:`INFO`, |
3055| | :const:`WARNING`, :const:`ERROR`, |
3056| | :const:`CRITICAL`). |
3057+-------------------------+-----------------------------------------------+
3058| ``%(levelname)s`` | Text logging level for the message |
3059| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3060| | ``'ERROR'``, ``'CRITICAL'``). |
3061+-------------------------+-----------------------------------------------+
3062| ``%(pathname)s`` | Full pathname of the source file where the |
3063| | logging call was issued (if available). |
3064+-------------------------+-----------------------------------------------+
3065| ``%(filename)s`` | Filename portion of pathname. |
3066+-------------------------+-----------------------------------------------+
3067| ``%(module)s`` | Module (name portion of filename). |
3068+-------------------------+-----------------------------------------------+
3069| ``%(funcName)s`` | Name of function containing the logging call. |
3070+-------------------------+-----------------------------------------------+
3071| ``%(lineno)d`` | Source line number where the logging call was |
3072| | issued (if available). |
3073+-------------------------+-----------------------------------------------+
3074| ``%(created)f`` | Time when the :class:`LogRecord` was created |
3075| | (as returned by :func:`time.time`). |
3076+-------------------------+-----------------------------------------------+
3077| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3078| | created, relative to the time the logging |
3079| | module was loaded. |
3080+-------------------------+-----------------------------------------------+
3081| ``%(asctime)s`` | Human-readable time when the |
3082| | :class:`LogRecord` was created. By default |
3083| | this is of the form "2003-07-08 16:49:45,896" |
3084| | (the numbers after the comma are millisecond |
3085| | portion of the time). |
3086+-------------------------+-----------------------------------------------+
3087| ``%(msecs)d`` | Millisecond portion of the time when the |
3088| | :class:`LogRecord` was created. |
3089+-------------------------+-----------------------------------------------+
3090| ``%(thread)d`` | Thread ID (if available). |
3091+-------------------------+-----------------------------------------------+
3092| ``%(threadName)s`` | Thread name (if available). |
3093+-------------------------+-----------------------------------------------+
3094| ``%(process)d`` | Process ID (if available). |
3095+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003096| ``%(processName)s`` | Process name (if available). |
3097+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003098| ``%(message)s`` | The logged message, computed as ``msg % |
3099| | args``. |
3100+-------------------------+-----------------------------------------------+
3101
Georg Brandl116aa622007-08-15 14:28:22 +00003102
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003103.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003104
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003105 Returns a new instance of the :class:`Formatter` class. The instance is
3106 initialized with a format string for the message as a whole, as well as a
3107 format string for the date/time portion of a message. If no *fmt* is
3108 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3109 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003110
Benjamin Petersone41251e2008-04-25 01:59:09 +00003111 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003112
Benjamin Petersone41251e2008-04-25 01:59:09 +00003113 The record's attribute dictionary is used as the operand to a string
3114 formatting operation. Returns the resulting string. Before formatting the
3115 dictionary, a couple of preparatory steps are carried out. The *message*
3116 attribute of the record is computed using *msg* % *args*. If the
3117 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3118 to format the event time. If there is exception information, it is
3119 formatted using :meth:`formatException` and appended to the message. Note
3120 that the formatted exception information is cached in attribute
3121 *exc_text*. This is useful because the exception information can be
3122 pickled and sent across the wire, but you should be careful if you have
3123 more than one :class:`Formatter` subclass which customizes the formatting
3124 of exception information. In this case, you will have to clear the cached
3125 value after a formatter has done its formatting, so that the next
3126 formatter to handle the event doesn't use the cached value but
3127 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003128
Vinay Sajip8593ae62010-11-14 21:33:04 +00003129 If stack information is available, it's appended after the exception
3130 information, using :meth:`formatStack` to transform it if necessary.
3131
Georg Brandl116aa622007-08-15 14:28:22 +00003132
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003133 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003134
Benjamin Petersone41251e2008-04-25 01:59:09 +00003135 This method should be called from :meth:`format` by a formatter which
3136 wants to make use of a formatted time. This method can be overridden in
3137 formatters to provide for any specific requirement, but the basic behavior
3138 is as follows: if *datefmt* (a string) is specified, it is used with
3139 :func:`time.strftime` to format the creation time of the
3140 record. Otherwise, the ISO8601 format is used. The resulting string is
3141 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003142
3143
Benjamin Petersone41251e2008-04-25 01:59:09 +00003144 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003145
Benjamin Petersone41251e2008-04-25 01:59:09 +00003146 Formats the specified exception information (a standard exception tuple as
3147 returned by :func:`sys.exc_info`) as a string. This default implementation
3148 just uses :func:`traceback.print_exception`. The resulting string is
3149 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003150
Vinay Sajip8593ae62010-11-14 21:33:04 +00003151 .. method:: formatStack(stack_info)
3152
3153 Formats the specified stack information (a string as returned by
3154 :func:`traceback.print_stack`, but with the last newline removed) as a
3155 string. This default implementation just returns the input value.
3156
Vinay Sajipd31f3632010-06-29 15:31:15 +00003157.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003158
3159Filter Objects
3160--------------
3161
Georg Brandl5c66bca2010-10-29 05:36:28 +00003162``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003163filtering than is provided by levels. The base filter class only allows events
3164which are below a certain point in the logger hierarchy. For example, a filter
3165initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3166"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3167empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003168
3169
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003170.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003171
3172 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3173 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003174 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003175
3176
Benjamin Petersone41251e2008-04-25 01:59:09 +00003177 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003178
Benjamin Petersone41251e2008-04-25 01:59:09 +00003179 Is the specified record to be logged? Returns zero for no, nonzero for
3180 yes. If deemed appropriate, the record may be modified in-place by this
3181 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003182
Vinay Sajip81010212010-08-19 19:17:41 +00003183Note that filters attached to handlers are consulted whenever an event is
3184emitted by the handler, whereas filters attached to loggers are consulted
3185whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3186etc.) This means that events which have been generated by descendant loggers
3187will not be filtered by a logger's filter setting, unless the filter has also
3188been applied to those descendant loggers.
3189
Vinay Sajip22246fd2010-10-20 11:40:02 +00003190You don't actually need to subclass ``Filter``: you can pass any instance
3191which has a ``filter`` method with the same semantics.
3192
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003193.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003194 You don't need to create specialized ``Filter`` classes, or use other
3195 classes with a ``filter`` method: you can use a function (or other
3196 callable) as a filter. The filtering logic will check to see if the filter
3197 object has a ``filter`` attribute: if it does, it's assumed to be a
3198 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3199 assumed to be a callable and called with the record as the single
3200 parameter. The returned value should conform to that returned by
3201 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003202
Vinay Sajipac007992010-09-17 12:45:26 +00003203Other uses for filters
3204^^^^^^^^^^^^^^^^^^^^^^
3205
3206Although filters are used primarily to filter records based on more
3207sophisticated criteria than levels, they get to see every record which is
3208processed by the handler or logger they're attached to: this can be useful if
3209you want to do things like counting how many records were processed by a
3210particular logger or handler, or adding, changing or removing attributes in
3211the LogRecord being processed. Obviously changing the LogRecord needs to be
3212done with some care, but it does allow the injection of contextual information
3213into logs (see :ref:`filters-contextual`).
3214
Vinay Sajipd31f3632010-06-29 15:31:15 +00003215.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003216
3217LogRecord Objects
3218-----------------
3219
Vinay Sajip4039aff2010-09-11 10:25:28 +00003220:class:`LogRecord` instances are created automatically by the :class:`Logger`
3221every time something is logged, and can be created manually via
3222:func:`makeLogRecord` (for example, from a pickled event received over the
3223wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003224
3225
Vinay Sajip8593ae62010-11-14 21:33:04 +00003226.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003227
Vinay Sajip4039aff2010-09-11 10:25:28 +00003228 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003229
Vinay Sajip4039aff2010-09-11 10:25:28 +00003230 The primary information is passed in :attr:`msg` and :attr:`args`, which
3231 are combined using ``msg % args`` to create the :attr:`message` field of the
3232 record.
3233
3234 .. attribute:: args
3235
3236 Tuple of arguments to be used in formatting :attr:`msg`.
3237
3238 .. attribute:: exc_info
3239
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003240 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003241 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003242
3243 .. attribute:: func
3244
3245 Name of the function of origin (i.e. in which the logging call was made).
3246
3247 .. attribute:: lineno
3248
3249 Line number in the source file of origin.
3250
3251 .. attribute:: lvl
3252
3253 Numeric logging level.
3254
3255 .. attribute:: message
3256
3257 Bound to the result of :meth:`getMessage` when
3258 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3259
3260 .. attribute:: msg
3261
3262 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3263 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3264
3265 .. attribute:: name
3266
3267 Name of the logger that emitted the record.
3268
3269 .. attribute:: pathname
3270
3271 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003272
Vinay Sajip8593ae62010-11-14 21:33:04 +00003273 .. attribute:: stack_info
3274
3275 Stack frame information (where available) from the bottom of the stack
3276 in the current thread, up to and including the stack frame of the
3277 logging call which resulted in the creation of this record.
3278
Benjamin Petersone41251e2008-04-25 01:59:09 +00003279 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003280
Benjamin Petersone41251e2008-04-25 01:59:09 +00003281 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003282 user-supplied arguments with the message. If the user-supplied message
3283 argument to the logging call is not a string, :func:`str` is called on it to
3284 convert it to a string. This allows use of user-defined classes as
3285 messages, whose ``__str__`` method can return the actual format string to
3286 be used.
3287
Vinay Sajip61561522010-12-03 11:50:38 +00003288 .. versionchanged:: 3.2
3289 The creation of a ``LogRecord`` has been made more configurable by
3290 providing a factory which is used to create the record. The factory can be
3291 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3292 (see this for the factory's signature).
3293
3294 This functionality can be used to inject your own values into a
3295 LogRecord at creation time. You can use the following pattern::
3296
3297 old_factory = logging.getLogRecordFactory()
3298
3299 def record_factory(*args, **kwargs):
3300 record = old_factory(*args, **kwargs)
3301 record.custom_attribute = 0xdecafbad
3302 return record
3303
3304 logging.setLogRecordFactory(record_factory)
3305
3306 With this pattern, multiple factories could be chained, and as long
3307 as they don't overwrite each other's attributes or unintentionally
3308 overwrite the standard attributes listed above, there should be no
3309 surprises.
3310
Vinay Sajipd31f3632010-06-29 15:31:15 +00003311.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003312
Christian Heimes04c420f2008-01-18 18:40:46 +00003313LoggerAdapter Objects
3314---------------------
3315
Christian Heimes04c420f2008-01-18 18:40:46 +00003316:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003317information into logging calls. For a usage example , see the section on
3318`adding contextual information to your logging output`__.
3319
3320__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00003321
3322.. class:: LoggerAdapter(logger, extra)
3323
3324 Returns an instance of :class:`LoggerAdapter` initialized with an
3325 underlying :class:`Logger` instance and a dict-like object.
3326
Benjamin Petersone41251e2008-04-25 01:59:09 +00003327 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003328
Benjamin Petersone41251e2008-04-25 01:59:09 +00003329 Modifies the message and/or keyword arguments passed to a logging call in
3330 order to insert contextual information. This implementation takes the object
3331 passed as *extra* to the constructor and adds it to *kwargs* using key
3332 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3333 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003334
Vinay Sajipc84f0162010-09-21 11:25:39 +00003335In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003336methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003337:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3338:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3339:meth:`hasHandlers`. These methods have the same signatures as their
3340counterparts in :class:`Logger`, so you can use the two types of instances
3341interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003342
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003343.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003344 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3345 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3346 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003347
Georg Brandl116aa622007-08-15 14:28:22 +00003348
3349Thread Safety
3350-------------
3351
3352The logging module is intended to be thread-safe without any special work
3353needing to be done by its clients. It achieves this though using threading
3354locks; there is one lock to serialize access to the module's shared data, and
3355each handler also creates a lock to serialize access to its underlying I/O.
3356
Benjamin Petersond23f8222009-04-05 19:13:16 +00003357If you are implementing asynchronous signal handlers using the :mod:`signal`
3358module, you may not be able to use logging from within such handlers. This is
3359because lock implementations in the :mod:`threading` module are not always
3360re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003361
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003362
3363Integration with the warnings module
3364------------------------------------
3365
3366The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3367with the :mod:`warnings` module.
3368
3369.. function:: captureWarnings(capture)
3370
3371 This function is used to turn the capture of warnings by logging on and
3372 off.
3373
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003374 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3375 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003376 formatted using :func:`warnings.formatwarning` and the resulting string
3377 logged to a logger named "py.warnings" with a severity of `WARNING`.
3378
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003379 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003380 will stop, and warnings will be redirected to their original destinations
3381 (i.e. those in effect before `captureWarnings(True)` was called).
3382
3383
Georg Brandl116aa622007-08-15 14:28:22 +00003384Configuration
3385-------------
3386
3387
3388.. _logging-config-api:
3389
3390Configuration functions
3391^^^^^^^^^^^^^^^^^^^^^^^
3392
Georg Brandl116aa622007-08-15 14:28:22 +00003393The following functions configure the logging module. They are located in the
3394:mod:`logging.config` module. Their use is optional --- you can configure the
3395logging module using these functions or by making calls to the main API (defined
3396in :mod:`logging` itself) and defining handlers which are declared either in
3397:mod:`logging` or :mod:`logging.handlers`.
3398
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003399.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003400
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003401 Takes the logging configuration from a dictionary. The contents of
3402 this dictionary are described in :ref:`logging-config-dictschema`
3403 below.
3404
3405 If an error is encountered during configuration, this function will
3406 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3407 or :exc:`ImportError` with a suitably descriptive message. The
3408 following is a (possibly incomplete) list of conditions which will
3409 raise an error:
3410
3411 * A ``level`` which is not a string or which is a string not
3412 corresponding to an actual logging level.
3413 * A ``propagate`` value which is not a boolean.
3414 * An id which does not have a corresponding destination.
3415 * A non-existent handler id found during an incremental call.
3416 * An invalid logger name.
3417 * Inability to resolve to an internal or external object.
3418
3419 Parsing is performed by the :class:`DictConfigurator` class, whose
3420 constructor is passed the dictionary used for configuration, and
3421 has a :meth:`configure` method. The :mod:`logging.config` module
3422 has a callable attribute :attr:`dictConfigClass`
3423 which is initially set to :class:`DictConfigurator`.
3424 You can replace the value of :attr:`dictConfigClass` with a
3425 suitable implementation of your own.
3426
3427 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3428 the specified dictionary, and then calls the :meth:`configure` method on
3429 the returned object to put the configuration into effect::
3430
3431 def dictConfig(config):
3432 dictConfigClass(config).configure()
3433
3434 For example, a subclass of :class:`DictConfigurator` could call
3435 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3436 set up custom prefixes which would be usable in the subsequent
3437 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3438 this new subclass, and then :func:`dictConfig` could be called exactly as
3439 in the default, uncustomized state.
3440
3441.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003442
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003443 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003444 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003445 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003446 configurations (if the developer provides a mechanism to present the choices
3447 and load the chosen configuration). Defaults to be passed to the ConfigParser
3448 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003449
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003450
3451.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003452
3453 Starts up a socket server on the specified port, and listens for new
3454 configurations. If no port is specified, the module's default
3455 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3456 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3457 :class:`Thread` instance on which you can call :meth:`start` to start the
3458 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003459 call :func:`stopListening`.
3460
3461 To send a configuration to the socket, read in the configuration file and
3462 send it to the socket as a string of bytes preceded by a four-byte length
3463 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003464
3465
3466.. function:: stopListening()
3467
Christian Heimes8b0facf2007-12-04 19:30:01 +00003468 Stops the listening server which was created with a call to :func:`listen`.
3469 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003470 :func:`listen`.
3471
3472
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003473.. _logging-config-dictschema:
3474
3475Configuration dictionary schema
3476^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3477
3478Describing a logging configuration requires listing the various
3479objects to create and the connections between them; for example, you
3480may create a handler named "console" and then say that the logger
3481named "startup" will send its messages to the "console" handler.
3482These objects aren't limited to those provided by the :mod:`logging`
3483module because you might write your own formatter or handler class.
3484The parameters to these classes may also need to include external
3485objects such as ``sys.stderr``. The syntax for describing these
3486objects and connections is defined in :ref:`logging-config-dict-connections`
3487below.
3488
3489Dictionary Schema Details
3490"""""""""""""""""""""""""
3491
3492The dictionary passed to :func:`dictConfig` must contain the following
3493keys:
3494
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003495* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003496 version. The only valid value at present is 1, but having this key
3497 allows the schema to evolve while still preserving backwards
3498 compatibility.
3499
3500All other keys are optional, but if present they will be interpreted
3501as described below. In all cases below where a 'configuring dict' is
3502mentioned, it will be checked for the special ``'()'`` key to see if a
3503custom instantiation is required. If so, the mechanism described in
3504:ref:`logging-config-dict-userdef` below is used to create an instance;
3505otherwise, the context is used to determine what to instantiate.
3506
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003507* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003508 key is a formatter id and each value is a dict describing how to
3509 configure the corresponding Formatter instance.
3510
3511 The configuring dict is searched for keys ``format`` and ``datefmt``
3512 (with defaults of ``None``) and these are used to construct a
3513 :class:`logging.Formatter` instance.
3514
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003515* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003516 is a filter id and each value is a dict describing how to configure
3517 the corresponding Filter instance.
3518
3519 The configuring dict is searched for the key ``name`` (defaulting to the
3520 empty string) and this is used to construct a :class:`logging.Filter`
3521 instance.
3522
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003523* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003524 key is a handler id and each value is a dict describing how to
3525 configure the corresponding Handler instance.
3526
3527 The configuring dict is searched for the following keys:
3528
3529 * ``class`` (mandatory). This is the fully qualified name of the
3530 handler class.
3531
3532 * ``level`` (optional). The level of the handler.
3533
3534 * ``formatter`` (optional). The id of the formatter for this
3535 handler.
3536
3537 * ``filters`` (optional). A list of ids of the filters for this
3538 handler.
3539
3540 All *other* keys are passed through as keyword arguments to the
3541 handler's constructor. For example, given the snippet::
3542
3543 handlers:
3544 console:
3545 class : logging.StreamHandler
3546 formatter: brief
3547 level : INFO
3548 filters: [allow_foo]
3549 stream : ext://sys.stdout
3550 file:
3551 class : logging.handlers.RotatingFileHandler
3552 formatter: precise
3553 filename: logconfig.log
3554 maxBytes: 1024
3555 backupCount: 3
3556
3557 the handler with id ``console`` is instantiated as a
3558 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3559 stream. The handler with id ``file`` is instantiated as a
3560 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3561 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3562
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003563* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003564 is a logger name and each value is a dict describing how to
3565 configure the corresponding Logger instance.
3566
3567 The configuring dict is searched for the following keys:
3568
3569 * ``level`` (optional). The level of the logger.
3570
3571 * ``propagate`` (optional). The propagation setting of the logger.
3572
3573 * ``filters`` (optional). A list of ids of the filters for this
3574 logger.
3575
3576 * ``handlers`` (optional). A list of ids of the handlers for this
3577 logger.
3578
3579 The specified loggers will be configured according to the level,
3580 propagation, filters and handlers specified.
3581
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003582* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003583 Processing of the configuration will be as for any logger, except
3584 that the ``propagate`` setting will not be applicable.
3585
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003586* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003587 incremental to the existing configuration. This value defaults to
3588 ``False``, which means that the specified configuration replaces the
3589 existing configuration with the same semantics as used by the
3590 existing :func:`fileConfig` API.
3591
3592 If the specified value is ``True``, the configuration is processed
3593 as described in the section on :ref:`logging-config-dict-incremental`.
3594
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003595* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003596 disabled. This setting mirrors the parameter of the same name in
3597 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003598 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003599
3600.. _logging-config-dict-incremental:
3601
3602Incremental Configuration
3603"""""""""""""""""""""""""
3604
3605It is difficult to provide complete flexibility for incremental
3606configuration. For example, because objects such as filters
3607and formatters are anonymous, once a configuration is set up, it is
3608not possible to refer to such anonymous objects when augmenting a
3609configuration.
3610
3611Furthermore, there is not a compelling case for arbitrarily altering
3612the object graph of loggers, handlers, filters, formatters at
3613run-time, once a configuration is set up; the verbosity of loggers and
3614handlers can be controlled just by setting levels (and, in the case of
3615loggers, propagation flags). Changing the object graph arbitrarily in
3616a safe way is problematic in a multi-threaded environment; while not
3617impossible, the benefits are not worth the complexity it adds to the
3618implementation.
3619
3620Thus, when the ``incremental`` key of a configuration dict is present
3621and is ``True``, the system will completely ignore any ``formatters`` and
3622``filters`` entries, and process only the ``level``
3623settings in the ``handlers`` entries, and the ``level`` and
3624``propagate`` settings in the ``loggers`` and ``root`` entries.
3625
3626Using a value in the configuration dict lets configurations to be sent
3627over the wire as pickled dicts to a socket listener. Thus, the logging
3628verbosity of a long-running application can be altered over time with
3629no need to stop and restart the application.
3630
3631.. _logging-config-dict-connections:
3632
3633Object connections
3634""""""""""""""""""
3635
3636The schema describes a set of logging objects - loggers,
3637handlers, formatters, filters - which are connected to each other in
3638an object graph. Thus, the schema needs to represent connections
3639between the objects. For example, say that, once configured, a
3640particular logger has attached to it a particular handler. For the
3641purposes of this discussion, we can say that the logger represents the
3642source, and the handler the destination, of a connection between the
3643two. Of course in the configured objects this is represented by the
3644logger holding a reference to the handler. In the configuration dict,
3645this is done by giving each destination object an id which identifies
3646it unambiguously, and then using the id in the source object's
3647configuration to indicate that a connection exists between the source
3648and the destination object with that id.
3649
3650So, for example, consider the following YAML snippet::
3651
3652 formatters:
3653 brief:
3654 # configuration for formatter with id 'brief' goes here
3655 precise:
3656 # configuration for formatter with id 'precise' goes here
3657 handlers:
3658 h1: #This is an id
3659 # configuration of handler with id 'h1' goes here
3660 formatter: brief
3661 h2: #This is another id
3662 # configuration of handler with id 'h2' goes here
3663 formatter: precise
3664 loggers:
3665 foo.bar.baz:
3666 # other configuration for logger 'foo.bar.baz'
3667 handlers: [h1, h2]
3668
3669(Note: YAML used here because it's a little more readable than the
3670equivalent Python source form for the dictionary.)
3671
3672The ids for loggers are the logger names which would be used
3673programmatically to obtain a reference to those loggers, e.g.
3674``foo.bar.baz``. The ids for Formatters and Filters can be any string
3675value (such as ``brief``, ``precise`` above) and they are transient,
3676in that they are only meaningful for processing the configuration
3677dictionary and used to determine connections between objects, and are
3678not persisted anywhere when the configuration call is complete.
3679
3680The above snippet indicates that logger named ``foo.bar.baz`` should
3681have two handlers attached to it, which are described by the handler
3682ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3683``brief``, and the formatter for ``h2`` is that described by id
3684``precise``.
3685
3686
3687.. _logging-config-dict-userdef:
3688
3689User-defined objects
3690""""""""""""""""""""
3691
3692The schema supports user-defined objects for handlers, filters and
3693formatters. (Loggers do not need to have different types for
3694different instances, so there is no support in this configuration
3695schema for user-defined logger classes.)
3696
3697Objects to be configured are described by dictionaries
3698which detail their configuration. In some places, the logging system
3699will be able to infer from the context how an object is to be
3700instantiated, but when a user-defined object is to be instantiated,
3701the system will not know how to do this. In order to provide complete
3702flexibility for user-defined object instantiation, the user needs
3703to provide a 'factory' - a callable which is called with a
3704configuration dictionary and which returns the instantiated object.
3705This is signalled by an absolute import path to the factory being
3706made available under the special key ``'()'``. Here's a concrete
3707example::
3708
3709 formatters:
3710 brief:
3711 format: '%(message)s'
3712 default:
3713 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3714 datefmt: '%Y-%m-%d %H:%M:%S'
3715 custom:
3716 (): my.package.customFormatterFactory
3717 bar: baz
3718 spam: 99.9
3719 answer: 42
3720
3721The above YAML snippet defines three formatters. The first, with id
3722``brief``, is a standard :class:`logging.Formatter` instance with the
3723specified format string. The second, with id ``default``, has a
3724longer format and also defines the time format explicitly, and will
3725result in a :class:`logging.Formatter` initialized with those two format
3726strings. Shown in Python source form, the ``brief`` and ``default``
3727formatters have configuration sub-dictionaries::
3728
3729 {
3730 'format' : '%(message)s'
3731 }
3732
3733and::
3734
3735 {
3736 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3737 'datefmt' : '%Y-%m-%d %H:%M:%S'
3738 }
3739
3740respectively, and as these dictionaries do not contain the special key
3741``'()'``, the instantiation is inferred from the context: as a result,
3742standard :class:`logging.Formatter` instances are created. The
3743configuration sub-dictionary for the third formatter, with id
3744``custom``, is::
3745
3746 {
3747 '()' : 'my.package.customFormatterFactory',
3748 'bar' : 'baz',
3749 'spam' : 99.9,
3750 'answer' : 42
3751 }
3752
3753and this contains the special key ``'()'``, which means that
3754user-defined instantiation is wanted. In this case, the specified
3755factory callable will be used. If it is an actual callable it will be
3756used directly - otherwise, if you specify a string (as in the example)
3757the actual callable will be located using normal import mechanisms.
3758The callable will be called with the **remaining** items in the
3759configuration sub-dictionary as keyword arguments. In the above
3760example, the formatter with id ``custom`` will be assumed to be
3761returned by the call::
3762
3763 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3764
3765The key ``'()'`` has been used as the special key because it is not a
3766valid keyword parameter name, and so will not clash with the names of
3767the keyword arguments used in the call. The ``'()'`` also serves as a
3768mnemonic that the corresponding value is a callable.
3769
3770
3771.. _logging-config-dict-externalobj:
3772
3773Access to external objects
3774""""""""""""""""""""""""""
3775
3776There are times where a configuration needs to refer to objects
3777external to the configuration, for example ``sys.stderr``. If the
3778configuration dict is constructed using Python code, this is
3779straightforward, but a problem arises when the configuration is
3780provided via a text file (e.g. JSON, YAML). In a text file, there is
3781no standard way to distinguish ``sys.stderr`` from the literal string
3782``'sys.stderr'``. To facilitate this distinction, the configuration
3783system looks for certain special prefixes in string values and
3784treat them specially. For example, if the literal string
3785``'ext://sys.stderr'`` is provided as a value in the configuration,
3786then the ``ext://`` will be stripped off and the remainder of the
3787value processed using normal import mechanisms.
3788
3789The handling of such prefixes is done in a way analogous to protocol
3790handling: there is a generic mechanism to look for prefixes which
3791match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3792whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3793in a prefix-dependent manner and the result of the processing replaces
3794the string value. If the prefix is not recognised, then the string
3795value will be left as-is.
3796
3797
3798.. _logging-config-dict-internalobj:
3799
3800Access to internal objects
3801""""""""""""""""""""""""""
3802
3803As well as external objects, there is sometimes also a need to refer
3804to objects in the configuration. This will be done implicitly by the
3805configuration system for things that it knows about. For example, the
3806string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3807automatically be converted to the value ``logging.DEBUG``, and the
3808``handlers``, ``filters`` and ``formatter`` entries will take an
3809object id and resolve to the appropriate destination object.
3810
3811However, a more generic mechanism is needed for user-defined
3812objects which are not known to the :mod:`logging` module. For
3813example, consider :class:`logging.handlers.MemoryHandler`, which takes
3814a ``target`` argument which is another handler to delegate to. Since
3815the system already knows about this class, then in the configuration,
3816the given ``target`` just needs to be the object id of the relevant
3817target handler, and the system will resolve to the handler from the
3818id. If, however, a user defines a ``my.package.MyHandler`` which has
3819an ``alternate`` handler, the configuration system would not know that
3820the ``alternate`` referred to a handler. To cater for this, a generic
3821resolution system allows the user to specify::
3822
3823 handlers:
3824 file:
3825 # configuration of file handler goes here
3826
3827 custom:
3828 (): my.package.MyHandler
3829 alternate: cfg://handlers.file
3830
3831The literal string ``'cfg://handlers.file'`` will be resolved in an
3832analogous way to strings with the ``ext://`` prefix, but looking
3833in the configuration itself rather than the import namespace. The
3834mechanism allows access by dot or by index, in a similar way to
3835that provided by ``str.format``. Thus, given the following snippet::
3836
3837 handlers:
3838 email:
3839 class: logging.handlers.SMTPHandler
3840 mailhost: localhost
3841 fromaddr: my_app@domain.tld
3842 toaddrs:
3843 - support_team@domain.tld
3844 - dev_team@domain.tld
3845 subject: Houston, we have a problem.
3846
3847in the configuration, the string ``'cfg://handlers'`` would resolve to
3848the dict with key ``handlers``, the string ``'cfg://handlers.email``
3849would resolve to the dict with key ``email`` in the ``handlers`` dict,
3850and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3851resolve to ``'dev_team.domain.tld'`` and the string
3852``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3853``'support_team@domain.tld'``. The ``subject`` value could be accessed
3854using either ``'cfg://handlers.email.subject'`` or, equivalently,
3855``'cfg://handlers.email[subject]'``. The latter form only needs to be
3856used if the key contains spaces or non-alphanumeric characters. If an
3857index value consists only of decimal digits, access will be attempted
3858using the corresponding integer value, falling back to the string
3859value if needed.
3860
3861Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3862resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3863If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3864the system will attempt to retrieve the value from
3865``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3866to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3867fails.
3868
Georg Brandl116aa622007-08-15 14:28:22 +00003869.. _logging-config-fileformat:
3870
3871Configuration file format
3872^^^^^^^^^^^^^^^^^^^^^^^^^
3873
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003874The configuration file format understood by :func:`fileConfig` is based on
3875:mod:`configparser` functionality. The file must contain sections called
3876``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3877entities of each type which are defined in the file. For each such entity, there
3878is a separate section which identifies how that entity is configured. Thus, for
3879a logger named ``log01`` in the ``[loggers]`` section, the relevant
3880configuration details are held in a section ``[logger_log01]``. Similarly, a
3881handler called ``hand01`` in the ``[handlers]`` section will have its
3882configuration held in a section called ``[handler_hand01]``, while a formatter
3883called ``form01`` in the ``[formatters]`` section will have its configuration
3884specified in a section called ``[formatter_form01]``. The root logger
3885configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003886
3887Examples of these sections in the file are given below. ::
3888
3889 [loggers]
3890 keys=root,log02,log03,log04,log05,log06,log07
3891
3892 [handlers]
3893 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3894
3895 [formatters]
3896 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3897
3898The root logger must specify a level and a list of handlers. An example of a
3899root logger section is given below. ::
3900
3901 [logger_root]
3902 level=NOTSET
3903 handlers=hand01
3904
3905The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3906``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3907logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3908package's namespace.
3909
3910The ``handlers`` entry is a comma-separated list of handler names, which must
3911appear in the ``[handlers]`` section. These names must appear in the
3912``[handlers]`` section and have corresponding sections in the configuration
3913file.
3914
3915For loggers other than the root logger, some additional information is required.
3916This is illustrated by the following example. ::
3917
3918 [logger_parser]
3919 level=DEBUG
3920 handlers=hand01
3921 propagate=1
3922 qualname=compiler.parser
3923
3924The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3925except that if a non-root logger's level is specified as ``NOTSET``, the system
3926consults loggers higher up the hierarchy to determine the effective level of the
3927logger. The ``propagate`` entry is set to 1 to indicate that messages must
3928propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3929indicate that messages are **not** propagated to handlers up the hierarchy. The
3930``qualname`` entry is the hierarchical channel name of the logger, that is to
3931say the name used by the application to get the logger.
3932
3933Sections which specify handler configuration are exemplified by the following.
3934::
3935
3936 [handler_hand01]
3937 class=StreamHandler
3938 level=NOTSET
3939 formatter=form01
3940 args=(sys.stdout,)
3941
3942The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3943in the ``logging`` package's namespace). The ``level`` is interpreted as for
3944loggers, and ``NOTSET`` is taken to mean "log everything".
3945
3946The ``formatter`` entry indicates the key name of the formatter for this
3947handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3948If a name is specified, it must appear in the ``[formatters]`` section and have
3949a corresponding section in the configuration file.
3950
3951The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3952package's namespace, is the list of arguments to the constructor for the handler
3953class. Refer to the constructors for the relevant handlers, or to the examples
3954below, to see how typical entries are constructed. ::
3955
3956 [handler_hand02]
3957 class=FileHandler
3958 level=DEBUG
3959 formatter=form02
3960 args=('python.log', 'w')
3961
3962 [handler_hand03]
3963 class=handlers.SocketHandler
3964 level=INFO
3965 formatter=form03
3966 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3967
3968 [handler_hand04]
3969 class=handlers.DatagramHandler
3970 level=WARN
3971 formatter=form04
3972 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3973
3974 [handler_hand05]
3975 class=handlers.SysLogHandler
3976 level=ERROR
3977 formatter=form05
3978 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3979
3980 [handler_hand06]
3981 class=handlers.NTEventLogHandler
3982 level=CRITICAL
3983 formatter=form06
3984 args=('Python Application', '', 'Application')
3985
3986 [handler_hand07]
3987 class=handlers.SMTPHandler
3988 level=WARN
3989 formatter=form07
3990 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3991
3992 [handler_hand08]
3993 class=handlers.MemoryHandler
3994 level=NOTSET
3995 formatter=form08
3996 target=
3997 args=(10, ERROR)
3998
3999 [handler_hand09]
4000 class=handlers.HTTPHandler
4001 level=NOTSET
4002 formatter=form09
4003 args=('localhost:9022', '/log', 'GET')
4004
4005Sections which specify formatter configuration are typified by the following. ::
4006
4007 [formatter_form01]
4008 format=F1 %(asctime)s %(levelname)s %(message)s
4009 datefmt=
4010 class=logging.Formatter
4011
4012The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004013the :func:`strftime`\ -compatible date/time format string. If empty, the
4014package substitutes ISO8601 format date/times, which is almost equivalent to
4015specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
4016also specifies milliseconds, which are appended to the result of using the above
4017format string, with a comma separator. An example time in ISO8601 format is
4018``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004019
4020The ``class`` entry is optional. It indicates the name of the formatter's class
4021(as a dotted module and class name.) This option is useful for instantiating a
4022:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4023exception tracebacks in an expanded or condensed format.
4024
Christian Heimes8b0facf2007-12-04 19:30:01 +00004025
4026Configuration server example
4027^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4028
4029Here is an example of a module using the logging configuration server::
4030
4031 import logging
4032 import logging.config
4033 import time
4034 import os
4035
4036 # read initial config file
4037 logging.config.fileConfig("logging.conf")
4038
4039 # create and start listener on port 9999
4040 t = logging.config.listen(9999)
4041 t.start()
4042
4043 logger = logging.getLogger("simpleExample")
4044
4045 try:
4046 # loop through logging calls to see the difference
4047 # new configurations make, until Ctrl+C is pressed
4048 while True:
4049 logger.debug("debug message")
4050 logger.info("info message")
4051 logger.warn("warn message")
4052 logger.error("error message")
4053 logger.critical("critical message")
4054 time.sleep(5)
4055 except KeyboardInterrupt:
4056 # cleanup
4057 logging.config.stopListening()
4058 t.join()
4059
4060And here is a script that takes a filename and sends that file to the server,
4061properly preceded with the binary-encoded length, as the new logging
4062configuration::
4063
4064 #!/usr/bin/env python
4065 import socket, sys, struct
4066
4067 data_to_send = open(sys.argv[1], "r").read()
4068
4069 HOST = 'localhost'
4070 PORT = 9999
4071 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00004072 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004073 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00004074 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004075 s.send(struct.pack(">L", len(data_to_send)))
4076 s.send(data_to_send)
4077 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00004078 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004079
4080
4081More examples
4082-------------
4083
4084Multiple handlers and formatters
4085^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4086
4087Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4088or maximum quota for the number of handlers you may add. Sometimes it will be
4089beneficial for an application to log all messages of all severities to a text
4090file while simultaneously logging errors or above to the console. To set this
4091up, simply configure the appropriate handlers. The logging calls in the
4092application code will remain unchanged. Here is a slight modification to the
4093previous simple module-based configuration example::
4094
4095 import logging
4096
4097 logger = logging.getLogger("simple_example")
4098 logger.setLevel(logging.DEBUG)
4099 # create file handler which logs even debug messages
4100 fh = logging.FileHandler("spam.log")
4101 fh.setLevel(logging.DEBUG)
4102 # create console handler with a higher log level
4103 ch = logging.StreamHandler()
4104 ch.setLevel(logging.ERROR)
4105 # create formatter and add it to the handlers
4106 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4107 ch.setFormatter(formatter)
4108 fh.setFormatter(formatter)
4109 # add the handlers to logger
4110 logger.addHandler(ch)
4111 logger.addHandler(fh)
4112
4113 # "application" code
4114 logger.debug("debug message")
4115 logger.info("info message")
4116 logger.warn("warn message")
4117 logger.error("error message")
4118 logger.critical("critical message")
4119
4120Notice that the "application" code does not care about multiple handlers. All
4121that changed was the addition and configuration of a new handler named *fh*.
4122
4123The ability to create new handlers with higher- or lower-severity filters can be
4124very helpful when writing and testing an application. Instead of using many
4125``print`` statements for debugging, use ``logger.debug``: Unlike the print
4126statements, which you will have to delete or comment out later, the logger.debug
4127statements can remain intact in the source code and remain dormant until you
4128need them again. At that time, the only change that needs to happen is to
4129modify the severity level of the logger and/or handler to debug.
4130
4131
4132Using logging in multiple modules
4133^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4134
4135It was mentioned above that multiple calls to
4136``logging.getLogger('someLogger')`` return a reference to the same logger
4137object. This is true not only within the same module, but also across modules
4138as long as it is in the same Python interpreter process. It is true for
4139references to the same object; additionally, application code can define and
4140configure a parent logger in one module and create (but not configure) a child
4141logger in a separate module, and all logger calls to the child will pass up to
4142the parent. Here is a main module::
4143
4144 import logging
4145 import auxiliary_module
4146
4147 # create logger with "spam_application"
4148 logger = logging.getLogger("spam_application")
4149 logger.setLevel(logging.DEBUG)
4150 # create file handler which logs even debug messages
4151 fh = logging.FileHandler("spam.log")
4152 fh.setLevel(logging.DEBUG)
4153 # create console handler with a higher log level
4154 ch = logging.StreamHandler()
4155 ch.setLevel(logging.ERROR)
4156 # create formatter and add it to the handlers
4157 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4158 fh.setFormatter(formatter)
4159 ch.setFormatter(formatter)
4160 # add the handlers to the logger
4161 logger.addHandler(fh)
4162 logger.addHandler(ch)
4163
4164 logger.info("creating an instance of auxiliary_module.Auxiliary")
4165 a = auxiliary_module.Auxiliary()
4166 logger.info("created an instance of auxiliary_module.Auxiliary")
4167 logger.info("calling auxiliary_module.Auxiliary.do_something")
4168 a.do_something()
4169 logger.info("finished auxiliary_module.Auxiliary.do_something")
4170 logger.info("calling auxiliary_module.some_function()")
4171 auxiliary_module.some_function()
4172 logger.info("done with auxiliary_module.some_function()")
4173
4174Here is the auxiliary module::
4175
4176 import logging
4177
4178 # create logger
4179 module_logger = logging.getLogger("spam_application.auxiliary")
4180
4181 class Auxiliary:
4182 def __init__(self):
4183 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4184 self.logger.info("creating an instance of Auxiliary")
4185 def do_something(self):
4186 self.logger.info("doing something")
4187 a = 1 + 1
4188 self.logger.info("done doing something")
4189
4190 def some_function():
4191 module_logger.info("received a call to \"some_function\"")
4192
4193The output looks like this::
4194
Christian Heimes043d6f62008-01-07 17:19:16 +00004195 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004196 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004197 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004198 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004199 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004200 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004201 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004202 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004203 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004204 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004205 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004206 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004207 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004208 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004209 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004210 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004211 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004212 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004213 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004214 done with auxiliary_module.some_function()
4215