blob: e675bc17165f4f1a0e55d2f2cdb5cae32eb6e712 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
17Logging is performed by calling methods on instances of the :class:`Logger`
18class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +000019conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +000020separators. For example, a logger named "scan" is the parent of loggers
21"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
22and indicate the area of an application in which a logged message originates.
23
24Logged messages also have levels of importance associated with them. The default
25levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
26:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
27importance of a logged message by calling an appropriate method of
28:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
29:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
30constrained to use these levels: you can specify your own and use a more general
31:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
32
Christian Heimes8b0facf2007-12-04 19:30:01 +000033
34Logging tutorial
35----------------
36
37The key benefit of having the logging API provided by a standard library module
38is that all Python modules can participate in logging, so your application log
39can include messages from third-party modules.
40
41It is, of course, possible to log messages with different verbosity levels or to
42different destinations. Support for writing log messages to files, HTTP
43GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Christian Heimesc3f30c42008-02-22 16:37:40 +000044mechanisms are all supported by the standard module. You can also create your
Christian Heimes8b0facf2007-12-04 19:30:01 +000045own log destination class if you have special requirements not met by any of the
46built-in classes.
47
48Simple examples
49^^^^^^^^^^^^^^^
50
51.. sectionauthor:: Doug Hellmann
52.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
53
54Most applications are probably going to want to log to a file, so let's start
55with that case. Using the :func:`basicConfig` function, we can set up the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056default handler so that debug messages are written to a file (in the example,
57we assume that you have the appropriate permissions to create a file called
58*example.log* in the current directory)::
Christian Heimes8b0facf2007-12-04 19:30:01 +000059
60 import logging
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000061 LOG_FILENAME = 'example.log'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Christian Heimes8b0facf2007-12-04 19:30:01 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smith5c01a8d2009-06-04 18:20:51 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Christian Heimes8b0facf2007-12-04 19:30:01 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000080 LOG_FILENAME = 'logging_rotatingfile_example.out'
Christian Heimes8b0facf2007-12-04 19:30:01 +000081
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
Georg Brandlf6945182008-02-01 11:56:49 +0000100 print(filename)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000105 logging_rotatingfile_example.out
106 logging_rotatingfile_example.out.1
107 logging_rotatingfile_example.out.2
108 logging_rotatingfile_example.out.3
109 logging_rotatingfile_example.out.4
110 logging_rotatingfile_example.out.5
Christian Heimes8b0facf2007-12-04 19:30:01 +0000111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112The most current file is always :file:`logging_rotatingfile_example.out`,
Christian Heimes8b0facf2007-12-04 19:30:01 +0000113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smith5c01a8d2009-06-04 18:20:51 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipb6d065f2009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Christian Heimesdcca98d2008-02-25 13:19:43 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000249name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000270requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
294defines the interface that all handlers should have and establishes some
295default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000303instantiate formatter classes, although you could likely subclass the formatter
304if your application needs special behavior. The constructor takes two optional
305arguments: a message format string and a date format string. If there is no
306message format string, the default is to use the raw message. If there is no
307date format string, the default date format is::
308
309 %Y-%m-%d %H:%M:%S
310
311with the milliseconds tacked on at the end.
312
313The message format string uses ``%(<dictionary key>)s`` styled string
314substitution; the possible keys are documented in :ref:`formatter-objects`.
315
316The following message format string will log the time in a human-readable
317format, the severity of the message, and the contents of the message, in that
318order::
319
320 "%(asctime)s - %(levelname)s - %(message)s"
321
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000322Formatters use a user-configurable function to convert the creation time of a
323record to a tuple. By default, :func:`time.localtime` is used; to change this
324for a particular formatter instance, set the ``converter`` attribute of the
325instance to a function with the same signature as :func:`time.localtime` or
326:func:`time.gmtime`. To change it for all formatters, for example if you want
327all logging times to be shown in GMT, set the ``converter`` attribute in the
328Formatter class (to ``time.gmtime`` for GMT display).
329
Christian Heimes8b0facf2007-12-04 19:30:01 +0000330
331Configuring Logging
332^^^^^^^^^^^^^^^^^^^
333
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000334Programmers can configure logging in three ways:
335
3361. Creating loggers, handlers, and formatters explicitly using Python
337 code that calls the configuration methods listed above.
3382. Creating a logging config file and reading it using the :func:`fileConfig`
339 function.
3403. Creating a dictionary of configuration information and passing it
341 to the :func:`dictConfig` function.
342
343The following example configures a very simple logger, a console
344handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000345
346 import logging
347
348 # create logger
349 logger = logging.getLogger("simple_example")
350 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000351
Christian Heimes8b0facf2007-12-04 19:30:01 +0000352 # create console handler and set level to debug
353 ch = logging.StreamHandler()
354 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000355
Christian Heimes8b0facf2007-12-04 19:30:01 +0000356 # create formatter
357 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000358
Christian Heimes8b0facf2007-12-04 19:30:01 +0000359 # add formatter to ch
360 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000361
Christian Heimes8b0facf2007-12-04 19:30:01 +0000362 # add ch to logger
363 logger.addHandler(ch)
364
365 # "application" code
366 logger.debug("debug message")
367 logger.info("info message")
368 logger.warn("warn message")
369 logger.error("error message")
370 logger.critical("critical message")
371
372Running this module from the command line produces the following output::
373
374 $ python simple_logging_module.py
375 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
376 2005-03-19 15:10:26,620 - simple_example - INFO - info message
377 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
378 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
379 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
380
381The following Python module creates a logger, handler, and formatter nearly
382identical to those in the example listed above, with the only difference being
383the names of the objects::
384
385 import logging
386 import logging.config
387
388 logging.config.fileConfig("logging.conf")
389
390 # create logger
391 logger = logging.getLogger("simpleExample")
392
393 # "application" code
394 logger.debug("debug message")
395 logger.info("info message")
396 logger.warn("warn message")
397 logger.error("error message")
398 logger.critical("critical message")
399
400Here is the logging.conf file::
401
402 [loggers]
403 keys=root,simpleExample
404
405 [handlers]
406 keys=consoleHandler
407
408 [formatters]
409 keys=simpleFormatter
410
411 [logger_root]
412 level=DEBUG
413 handlers=consoleHandler
414
415 [logger_simpleExample]
416 level=DEBUG
417 handlers=consoleHandler
418 qualname=simpleExample
419 propagate=0
420
421 [handler_consoleHandler]
422 class=StreamHandler
423 level=DEBUG
424 formatter=simpleFormatter
425 args=(sys.stdout,)
426
427 [formatter_simpleFormatter]
428 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
429 datefmt=
430
431The output is nearly identical to that of the non-config-file-based example::
432
433 $ python simple_logging_config.py
434 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
435 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
436 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
437 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
438 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
439
440You can see that the config file approach has a few advantages over the Python
441code approach, mainly separation of configuration and code and the ability of
442noncoders to easily modify the logging properties.
443
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000444Note that the class names referenced in config files need to be either relative
445to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000446import mechanisms. Thus, you could use either
447:class:`handlers.WatchedFileHandler` (relative to the logging module) or
448``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
449and module ``mymodule``, where ``mypackage`` is available on the Python import
450path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000451
Benjamin Peterson56894b52010-06-28 00:16:12 +0000452In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000453dictionaries to hold configuration information. This provides a superset of the
454functionality of the config-file-based approach outlined above, and is the
455recommended configuration method for new applications and deployments. Because
456a Python dictionary is used to hold configuration information, and since you
457can populate that dictionary using different means, you have more options for
458configuration. For example, you can use a configuration file in JSON format,
459or, if you have access to YAML processing functionality, a file in YAML
460format, to populate the configuration dictionary. Or, of course, you can
461construct the dictionary in Python code, receive it in pickled form over a
462socket, or use whatever approach makes sense for your application.
463
464Here's an example of the same configuration as above, in YAML format for
465the new dictionary-based approach::
466
467 version: 1
468 formatters:
469 simple:
470 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
471 handlers:
472 console:
473 class: logging.StreamHandler
474 level: DEBUG
475 formatter: simple
476 stream: ext://sys.stdout
477 loggers:
478 simpleExample:
479 level: DEBUG
480 handlers: [console]
481 propagate: no
482 root:
483 level: DEBUG
484 handlers: [console]
485
486For more information about logging using a dictionary, see
487:ref:`logging-config-api`.
488
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000489.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000490
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000491Configuring Logging for a Library
492^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
493
494When developing a library which uses logging, some consideration needs to be
495given to its configuration. If the using application does not use logging, and
496library code makes logging calls, then a one-off message "No handlers could be
497found for logger X.Y.Z" is printed to the console. This message is intended
498to catch mistakes in logging configuration, but will confuse an application
499developer who is not aware of logging by the library.
500
501In addition to documenting how a library uses logging, a good way to configure
502library logging so that it does not cause a spurious message is to add a
503handler which does nothing. This avoids the message being printed, since a
504handler will be found: it just doesn't produce any output. If the library user
505configures logging for application use, presumably that configuration will add
506some handlers, and if levels are suitably configured then logging calls made
507in library code will send output to those handlers, as normal.
508
509A do-nothing handler can be simply defined as follows::
510
511 import logging
512
513 class NullHandler(logging.Handler):
514 def emit(self, record):
515 pass
516
517An instance of this handler should be added to the top-level logger of the
518logging namespace used by the library. If all logging by a library *foo* is
519done using loggers with names matching "foo.x.y", then the code::
520
521 import logging
522
523 h = NullHandler()
524 logging.getLogger("foo").addHandler(h)
525
526should have the desired effect. If an organisation produces a number of
527libraries, then the logger name specified can be "orgname.foo" rather than
528just "foo".
529
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000530**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
531than* :class:`NullHandler` *to your library's loggers*. This is because the
532configuration of handlers is the prerogative of the application developer who
533uses your library. The application developer knows their target audience and
534what handlers are most appropriate for their application: if you add handlers
535"under the hood", you might well interfere with their ability to carry out
536unit tests and deliver logs which suit their requirements.
537
Georg Brandlf9734072008-12-07 15:30:06 +0000538.. versionadded:: 3.1
Vinay Sajip4039aff2010-09-11 10:25:28 +0000539
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000540The :class:`NullHandler` class was not present in previous versions, but is
541now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000542
543
Christian Heimes8b0facf2007-12-04 19:30:01 +0000544
545Logging Levels
546--------------
547
Georg Brandl116aa622007-08-15 14:28:22 +0000548The numeric values of logging levels are given in the following table. These are
549primarily of interest if you want to define your own levels, and need them to
550have specific values relative to the predefined levels. If you define a level
551with the same numeric value, it overwrites the predefined value; the predefined
552name is lost.
553
554+--------------+---------------+
555| Level | Numeric value |
556+==============+===============+
557| ``CRITICAL`` | 50 |
558+--------------+---------------+
559| ``ERROR`` | 40 |
560+--------------+---------------+
561| ``WARNING`` | 30 |
562+--------------+---------------+
563| ``INFO`` | 20 |
564+--------------+---------------+
565| ``DEBUG`` | 10 |
566+--------------+---------------+
567| ``NOTSET`` | 0 |
568+--------------+---------------+
569
570Levels can also be associated with loggers, being set either by the developer or
571through loading a saved logging configuration. When a logging method is called
572on a logger, the logger compares its own level with the level associated with
573the method call. If the logger's level is higher than the method call's, no
574logging message is actually generated. This is the basic mechanism controlling
575the verbosity of logging output.
576
577Logging messages are encoded as instances of the :class:`LogRecord` class. When
578a logger decides to actually log an event, a :class:`LogRecord` instance is
579created from the logging message.
580
581Logging messages are subjected to a dispatch mechanism through the use of
582:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
583class. Handlers are responsible for ensuring that a logged message (in the form
584of a :class:`LogRecord`) ends up in a particular location (or set of locations)
585which is useful for the target audience for that message (such as end users,
586support desk staff, system administrators, developers). Handlers are passed
587:class:`LogRecord` instances intended for particular destinations. Each logger
588can have zero, one or more handlers associated with it (via the
589:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
590directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000591of the logger* are called to dispatch the message (unless the *propagate* flag
592for a logger is set to a false value, at which point the passing to ancestor
593handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000594
595Just as for loggers, handlers can have levels associated with them. A handler's
596level acts as a filter in the same way as a logger's level does. If a handler
597decides to actually dispatch an event, the :meth:`emit` method is used to send
598the message to its destination. Most user-defined subclasses of :class:`Handler`
599will need to override this :meth:`emit`.
600
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000601.. _custom-levels:
602
603Custom Levels
604^^^^^^^^^^^^^
605
606Defining your own levels is possible, but should not be necessary, as the
607existing levels have been chosen on the basis of practical experience.
608However, if you are convinced that you need custom levels, great care should
609be exercised when doing this, and it is possibly *a very bad idea to define
610custom levels if you are developing a library*. That's because if multiple
611library authors all define their own custom levels, there is a chance that
612the logging output from such multiple libraries used together will be
613difficult for the using developer to control and/or interpret, because a
614given numeric value might mean different things for different libraries.
615
616
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000617Useful Handlers
618---------------
619
Georg Brandl116aa622007-08-15 14:28:22 +0000620In addition to the base :class:`Handler` class, many useful subclasses are
621provided:
622
Vinay Sajip121a1c42010-09-08 10:46:15 +0000623#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000624 objects).
625
Vinay Sajip121a1c42010-09-08 10:46:15 +0000626#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000628.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000629
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000630#. :class:`BaseRotatingHandler` is the base class for handlers that
631 rotate log files at a certain point. It is not meant to be instantiated
632 directly. Instead, use :class:`RotatingFileHandler` or
633 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
Vinay Sajip121a1c42010-09-08 10:46:15 +0000635#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000636 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000637
Vinay Sajip121a1c42010-09-08 10:46:15 +0000638#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000639 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Vinay Sajip121a1c42010-09-08 10:46:15 +0000641#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000642 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Vinay Sajip121a1c42010-09-08 10:46:15 +0000644#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000645 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Vinay Sajip121a1c42010-09-08 10:46:15 +0000647#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000648 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Vinay Sajip121a1c42010-09-08 10:46:15 +0000650#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000651 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Vinay Sajip121a1c42010-09-08 10:46:15 +0000653#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000654 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Vinay Sajip121a1c42010-09-08 10:46:15 +0000656#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000657 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Vinay Sajip121a1c42010-09-08 10:46:15 +0000659#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000660 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000662#. :class:`WatchedFileHandler` instances watch the file they are
663 logging to. If the file changes, it is closed and reopened using the file
664 name. This handler is only useful on Unix-like systems; Windows does not
665 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000666
Vinay Sajip121a1c42010-09-08 10:46:15 +0000667#. :class:`QueueHandler` instances send messages to a queue, such as
668 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
669
Vinay Sajip30bf1222009-01-10 19:23:34 +0000670.. currentmodule:: logging
671
Georg Brandlf9734072008-12-07 15:30:06 +0000672#. :class:`NullHandler` instances do nothing with error messages. They are used
673 by library developers who want to use logging, but want to avoid the "No
674 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000675 the library user has not configured logging. See :ref:`library-config` for
676 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000677
678.. versionadded:: 3.1
679
680The :class:`NullHandler` class was not present in previous versions.
681
Vinay Sajip121a1c42010-09-08 10:46:15 +0000682.. versionadded:: 3.2
683
684The :class:`QueueHandler` class was not present in previous versions.
685
Vinay Sajipa17775f2008-12-30 07:32:59 +0000686The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
687classes are defined in the core logging package. The other handlers are
688defined in a sub- module, :mod:`logging.handlers`. (There is also another
689sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691Logged messages are formatted for presentation through instances of the
692:class:`Formatter` class. They are initialized with a format string suitable for
693use with the % operator and a dictionary.
694
695For formatting multiple messages in a batch, instances of
696:class:`BufferingFormatter` can be used. In addition to the format string (which
697is applied to each message in the batch), there is provision for header and
698trailer format strings.
699
700When filtering based on logger level and/or handler level is not enough,
701instances of :class:`Filter` can be added to both :class:`Logger` and
702:class:`Handler` instances (through their :meth:`addFilter` method). Before
703deciding to process a message further, both loggers and handlers consult all
704their filters for permission. If any filter returns a false value, the message
705is not processed further.
706
707The basic :class:`Filter` functionality allows filtering by specific logger
708name. If this feature is used, messages sent to the named logger and its
709children are allowed through the filter, and all others dropped.
710
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000711Module-Level Functions
712----------------------
713
Georg Brandl116aa622007-08-15 14:28:22 +0000714In addition to the classes described above, there are a number of module- level
715functions.
716
717
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000718.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000720 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000721 logger which is the root logger of the hierarchy. If specified, the name is
722 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
723 Choice of these names is entirely up to the developer who is using logging.
724
725 All calls to this function with a given name return the same logger instance.
726 This means that logger instances never need to be passed between different parts
727 of an application.
728
729
730.. function:: getLoggerClass()
731
732 Return either the standard :class:`Logger` class, or the last class passed to
733 :func:`setLoggerClass`. This function may be called from within a new class
734 definition, to ensure that installing a customised :class:`Logger` class will
735 not undo customisations already applied by other code. For example::
736
737 class MyLogger(logging.getLoggerClass()):
738 # ... override behaviour here
739
740
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000741.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
744 message format string, and the *args* are the arguments which are merged into
745 *msg* using the string formatting operator. (Note that this means that you can
746 use keywords in the format string, together with a single dictionary argument.)
747
748 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
749 which, if it does not evaluate as false, causes exception information to be
750 added to the logging message. If an exception tuple (in the format returned by
751 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
752 is called to get the exception information.
753
754 The other optional keyword argument is *extra* which can be used to pass a
755 dictionary which is used to populate the __dict__ of the LogRecord created for
756 the logging event with user-defined attributes. These custom attributes can then
757 be used as you like. For example, they could be incorporated into logged
758 messages. For example::
759
760 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
761 logging.basicConfig(format=FORMAT)
762 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
763 logging.warning("Protocol problem: %s", "connection reset", extra=d)
764
Vinay Sajip4039aff2010-09-11 10:25:28 +0000765 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000766
767 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
768
769 The keys in the dictionary passed in *extra* should not clash with the keys used
770 by the logging system. (See the :class:`Formatter` documentation for more
771 information on which keys are used by the logging system.)
772
773 If you choose to use these attributes in logged messages, you need to exercise
774 some care. In the above example, for instance, the :class:`Formatter` has been
775 set up with a format string which expects 'clientip' and 'user' in the attribute
776 dictionary of the LogRecord. If these are missing, the message will not be
777 logged because a string formatting exception will occur. So in this case, you
778 always need to pass the *extra* dictionary with these keys.
779
780 While this might be annoying, this feature is intended for use in specialized
781 circumstances, such as multi-threaded servers where the same code executes in
782 many contexts, and interesting conditions which arise are dependent on this
783 context (such as remote client IP address and authenticated user name, in the
784 above example). In such circumstances, it is likely that specialized
785 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
786
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000788.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000789
790 Logs a message with level :const:`INFO` on the root logger. The arguments are
791 interpreted as for :func:`debug`.
792
793
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000794.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796 Logs a message with level :const:`WARNING` on the root logger. The arguments are
797 interpreted as for :func:`debug`.
798
799
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000800.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000801
802 Logs a message with level :const:`ERROR` on the root logger. The arguments are
803 interpreted as for :func:`debug`.
804
805
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000806.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
809 are interpreted as for :func:`debug`.
810
811
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000812.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000813
814 Logs a message with level :const:`ERROR` on the root logger. The arguments are
815 interpreted as for :func:`debug`. Exception info is added to the logging
816 message. This function should only be called from an exception handler.
817
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000818.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820 Logs a message with level *level* on the root logger. The other arguments are
821 interpreted as for :func:`debug`.
822
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000823 PLEASE NOTE: The above module-level functions which delegate to the root
824 logger should *not* be used in threads, in versions of Python earlier than
825 2.7.1 and 3.2, unless at least one handler has been added to the root
826 logger *before* the threads are started. These convenience functions call
827 :func:`basicConfig` to ensure that at least one handler is available; in
828 earlier versions of Python, this can (under rare circumstances) lead to
829 handlers being added multiple times to the root logger, which can in turn
830 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832.. function:: disable(lvl)
833
834 Provides an overriding level *lvl* for all loggers which takes precedence over
835 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000836 output down across the whole application, this function can be useful. Its
837 effect is to disable all logging calls of severity *lvl* and below, so that
838 if you call it with a value of INFO, then all INFO and DEBUG events would be
839 discarded, whereas those of severity WARNING and above would be processed
840 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842
843.. function:: addLevelName(lvl, levelName)
844
845 Associates level *lvl* with text *levelName* in an internal dictionary, which is
846 used to map numeric levels to a textual representation, for example when a
847 :class:`Formatter` formats a message. This function can also be used to define
848 your own levels. The only constraints are that all levels used must be
849 registered using this function, levels should be positive integers and they
850 should increase in increasing order of severity.
851
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000852 NOTE: If you are thinking of defining your own levels, please see the section
853 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +0000854
855.. function:: getLevelName(lvl)
856
857 Returns the textual representation of logging level *lvl*. If the level is one
858 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
859 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
860 have associated levels with names using :func:`addLevelName` then the name you
861 have associated with *lvl* is returned. If a numeric value corresponding to one
862 of the defined levels is passed in, the corresponding string representation is
863 returned. Otherwise, the string "Level %s" % lvl is returned.
864
865
866.. function:: makeLogRecord(attrdict)
867
868 Creates and returns a new :class:`LogRecord` instance whose attributes are
869 defined by *attrdict*. This function is useful for taking a pickled
870 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
871 it as a :class:`LogRecord` instance at the receiving end.
872
873
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000874.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876 Does basic configuration for the logging system by creating a
877 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000878 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000879 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
880 if no handlers are defined for the root logger.
881
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000882 This function does nothing if the root logger already has handlers
883 configured for it.
884
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000885 PLEASE NOTE: This function should be called from the main thread
886 before other threads are started. In versions of Python prior to
887 2.7.1 and 3.2, if this function is called from multiple threads,
888 it is possible (in rare circumstances) that a handler will be added
889 to the root logger more than once, leading to unexpected results
890 such as messages being duplicated in the log.
891
Georg Brandl116aa622007-08-15 14:28:22 +0000892 The following keyword arguments are supported.
893
894 +--------------+---------------------------------------------+
895 | Format | Description |
896 +==============+=============================================+
897 | ``filename`` | Specifies that a FileHandler be created, |
898 | | using the specified filename, rather than a |
899 | | StreamHandler. |
900 +--------------+---------------------------------------------+
901 | ``filemode`` | Specifies the mode to open the file, if |
902 | | filename is specified (if filemode is |
903 | | unspecified, it defaults to 'a'). |
904 +--------------+---------------------------------------------+
905 | ``format`` | Use the specified format string for the |
906 | | handler. |
907 +--------------+---------------------------------------------+
908 | ``datefmt`` | Use the specified date/time format. |
909 +--------------+---------------------------------------------+
910 | ``level`` | Set the root logger level to the specified |
911 | | level. |
912 +--------------+---------------------------------------------+
913 | ``stream`` | Use the specified stream to initialize the |
914 | | StreamHandler. Note that this argument is |
915 | | incompatible with 'filename' - if both are |
916 | | present, 'stream' is ignored. |
917 +--------------+---------------------------------------------+
918
Georg Brandl116aa622007-08-15 14:28:22 +0000919.. function:: shutdown()
920
921 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000922 closing all handlers. This should be called at application exit and no
923 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925
926.. function:: setLoggerClass(klass)
927
928 Tells the logging system to use the class *klass* when instantiating a logger.
929 The class should define :meth:`__init__` such that only a name argument is
930 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
931 function is typically called before any loggers are instantiated by applications
932 which need to use custom logger behavior.
933
934
935.. seealso::
936
937 :pep:`282` - A Logging System
938 The proposal which described this feature for inclusion in the Python standard
939 library.
940
Christian Heimes255f53b2007-12-08 15:33:56 +0000941 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000942 This is the original source for the :mod:`logging` package. The version of the
943 package available from this site is suitable for use with Python 1.5.2, 2.1.x
944 and 2.2.x, which do not include the :mod:`logging` package in the standard
945 library.
946
Vinay Sajip4039aff2010-09-11 10:25:28 +0000947.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949Logger Objects
950--------------
951
952Loggers have the following attributes and methods. Note that Loggers are never
953instantiated directly, but always through the module-level function
954``logging.getLogger(name)``.
955
Vinay Sajip0258ce82010-09-22 20:34:53 +0000956.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +0000957
958.. attribute:: Logger.propagate
959
960 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000961 its child loggers to the handlers of higher level (ancestor) loggers. The
962 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964
965.. method:: Logger.setLevel(lvl)
966
967 Sets the threshold for this logger to *lvl*. Logging messages which are less
968 severe than *lvl* will be ignored. When a logger is created, the level is set to
969 :const:`NOTSET` (which causes all messages to be processed when the logger is
970 the root logger, or delegation to the parent when the logger is a non-root
971 logger). Note that the root logger is created with level :const:`WARNING`.
972
973 The term "delegation to the parent" means that if a logger has a level of
974 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
975 a level other than NOTSET is found, or the root is reached.
976
977 If an ancestor is found with a level other than NOTSET, then that ancestor's
978 level is treated as the effective level of the logger where the ancestor search
979 began, and is used to determine how a logging event is handled.
980
981 If the root is reached, and it has a level of NOTSET, then all messages will be
982 processed. Otherwise, the root's level will be used as the effective level.
983
984
985.. method:: Logger.isEnabledFor(lvl)
986
987 Indicates if a message of severity *lvl* would be processed by this logger.
988 This method checks first the module-level level set by
989 ``logging.disable(lvl)`` and then the logger's effective level as determined
990 by :meth:`getEffectiveLevel`.
991
992
993.. method:: Logger.getEffectiveLevel()
994
995 Indicates the effective level for this logger. If a value other than
996 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
997 the hierarchy is traversed towards the root until a value other than
998 :const:`NOTSET` is found, and that value is returned.
999
1000
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001001.. method:: Logger.getChild(suffix)
1002
1003 Returns a logger which is a descendant to this logger, as determined by the suffix.
1004 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1005 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1006 convenience method, useful when the parent logger is named using e.g. ``__name__``
1007 rather than a literal string.
1008
1009 .. versionadded:: 3.2
1010
Georg Brandl67b21b72010-08-17 15:07:14 +00001011
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001012.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1015 message format string, and the *args* are the arguments which are merged into
1016 *msg* using the string formatting operator. (Note that this means that you can
1017 use keywords in the format string, together with a single dictionary argument.)
1018
1019 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
1020 which, if it does not evaluate as false, causes exception information to be
1021 added to the logging message. If an exception tuple (in the format returned by
1022 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1023 is called to get the exception information.
1024
1025 The other optional keyword argument is *extra* which can be used to pass a
1026 dictionary which is used to populate the __dict__ of the LogRecord created for
1027 the logging event with user-defined attributes. These custom attributes can then
1028 be used as you like. For example, they could be incorporated into logged
1029 messages. For example::
1030
1031 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1032 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001033 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001034 logger = logging.getLogger("tcpserver")
1035 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1036
1037 would print something like ::
1038
1039 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1040
1041 The keys in the dictionary passed in *extra* should not clash with the keys used
1042 by the logging system. (See the :class:`Formatter` documentation for more
1043 information on which keys are used by the logging system.)
1044
1045 If you choose to use these attributes in logged messages, you need to exercise
1046 some care. In the above example, for instance, the :class:`Formatter` has been
1047 set up with a format string which expects 'clientip' and 'user' in the attribute
1048 dictionary of the LogRecord. If these are missing, the message will not be
1049 logged because a string formatting exception will occur. So in this case, you
1050 always need to pass the *extra* dictionary with these keys.
1051
1052 While this might be annoying, this feature is intended for use in specialized
1053 circumstances, such as multi-threaded servers where the same code executes in
1054 many contexts, and interesting conditions which arise are dependent on this
1055 context (such as remote client IP address and authenticated user name, in the
1056 above example). In such circumstances, it is likely that specialized
1057 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1058
Georg Brandl116aa622007-08-15 14:28:22 +00001059
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001060.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001061
1062 Logs a message with level :const:`INFO` on this logger. The arguments are
1063 interpreted as for :meth:`debug`.
1064
1065
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001066.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068 Logs a message with level :const:`WARNING` on this logger. The arguments are
1069 interpreted as for :meth:`debug`.
1070
1071
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001072.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074 Logs a message with level :const:`ERROR` on this logger. The arguments are
1075 interpreted as for :meth:`debug`.
1076
1077
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001078.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001079
1080 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1081 interpreted as for :meth:`debug`.
1082
1083
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001084.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001085
1086 Logs a message with integer level *lvl* on this logger. The other arguments are
1087 interpreted as for :meth:`debug`.
1088
1089
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001090.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001091
1092 Logs a message with level :const:`ERROR` on this logger. The arguments are
1093 interpreted as for :meth:`debug`. Exception info is added to the logging
1094 message. This method should only be called from an exception handler.
1095
1096
1097.. method:: Logger.addFilter(filt)
1098
1099 Adds the specified filter *filt* to this logger.
1100
1101
1102.. method:: Logger.removeFilter(filt)
1103
1104 Removes the specified filter *filt* from this logger.
1105
1106
1107.. method:: Logger.filter(record)
1108
1109 Applies this logger's filters to the record and returns a true value if the
1110 record is to be processed.
1111
1112
1113.. method:: Logger.addHandler(hdlr)
1114
1115 Adds the specified handler *hdlr* to this logger.
1116
1117
1118.. method:: Logger.removeHandler(hdlr)
1119
1120 Removes the specified handler *hdlr* from this logger.
1121
1122
1123.. method:: Logger.findCaller()
1124
1125 Finds the caller's source filename and line number. Returns the filename, line
1126 number and function name as a 3-element tuple.
1127
Georg Brandl116aa622007-08-15 14:28:22 +00001128
1129.. method:: Logger.handle(record)
1130
1131 Handles a record by passing it to all handlers associated with this logger and
1132 its ancestors (until a false value of *propagate* is found). This method is used
1133 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001134 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001137.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001138
1139 This is a factory method which can be overridden in subclasses to create
1140 specialized :class:`LogRecord` instances.
1141
Vinay Sajip83eadd12010-09-20 10:31:18 +00001142.. method:: Logger.hasHandlers()
1143
1144 Checks to see if this logger has any handlers configured. This is done by
1145 looking for handlers in this logger and its parents in the logger hierarchy.
1146 Returns True if a handler was found, else False. The method stops searching
1147 up the hierarchy whenever a logger with the "propagate" attribute set to
1148 False is found - that will be the last logger which is checked for the
1149 existence of handlers.
1150
1151.. versionadded:: 3.2
1152
1153The :meth:`hasHandlers` method was not present in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001154
1155.. _minimal-example:
1156
1157Basic example
1158-------------
1159
Georg Brandl116aa622007-08-15 14:28:22 +00001160The :mod:`logging` package provides a lot of flexibility, and its configuration
1161can appear daunting. This section demonstrates that simple use of the logging
1162package is possible.
1163
1164The simplest example shows logging to the console::
1165
1166 import logging
1167
1168 logging.debug('A debug message')
1169 logging.info('Some information')
1170 logging.warning('A shot across the bows')
1171
1172If you run the above script, you'll see this::
1173
1174 WARNING:root:A shot across the bows
1175
1176Because no particular logger was specified, the system used the root logger. The
1177debug and info messages didn't appear because by default, the root logger is
1178configured to only handle messages with a severity of WARNING or above. The
1179message format is also a configuration default, as is the output destination of
1180the messages - ``sys.stderr``. The severity level, the message format and
1181destination can be easily changed, as shown in the example below::
1182
1183 import logging
1184
1185 logging.basicConfig(level=logging.DEBUG,
1186 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001187 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001188 filemode='w')
1189 logging.debug('A debug message')
1190 logging.info('Some information')
1191 logging.warning('A shot across the bows')
1192
1193The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001194which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001195something like the following::
1196
1197 2004-07-02 13:00:08,743 DEBUG A debug message
1198 2004-07-02 13:00:08,743 INFO Some information
1199 2004-07-02 13:00:08,743 WARNING A shot across the bows
1200
1201This time, all messages with a severity of DEBUG or above were handled, and the
1202format of the messages was also changed, and output went to the specified file
1203rather than the console.
1204
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001205.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001206
1207Formatting uses the old Python string formatting - see section
1208:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001209specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1210documentation.
1211
1212+-------------------+-----------------------------------------------+
1213| Format | Description |
1214+===================+===============================================+
1215| ``%(name)s`` | Name of the logger (logging channel). |
1216+-------------------+-----------------------------------------------+
1217| ``%(levelname)s`` | Text logging level for the message |
1218| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1219| | ``'ERROR'``, ``'CRITICAL'``). |
1220+-------------------+-----------------------------------------------+
1221| ``%(asctime)s`` | Human-readable time when the |
1222| | :class:`LogRecord` was created. By default |
1223| | this is of the form "2003-07-08 16:49:45,896" |
1224| | (the numbers after the comma are millisecond |
1225| | portion of the time). |
1226+-------------------+-----------------------------------------------+
1227| ``%(message)s`` | The logged message. |
1228+-------------------+-----------------------------------------------+
1229
1230To change the date/time format, you can pass an additional keyword parameter,
1231*datefmt*, as in the following::
1232
1233 import logging
1234
1235 logging.basicConfig(level=logging.DEBUG,
1236 format='%(asctime)s %(levelname)-8s %(message)s',
1237 datefmt='%a, %d %b %Y %H:%M:%S',
1238 filename='/temp/myapp.log',
1239 filemode='w')
1240 logging.debug('A debug message')
1241 logging.info('Some information')
1242 logging.warning('A shot across the bows')
1243
1244which would result in output like ::
1245
1246 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1247 Fri, 02 Jul 2004 13:06:18 INFO Some information
1248 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1249
1250The date format string follows the requirements of :func:`strftime` - see the
1251documentation for the :mod:`time` module.
1252
1253If, instead of sending logging output to the console or a file, you'd rather use
1254a file-like object which you have created separately, you can pass it to
1255:func:`basicConfig` using the *stream* keyword argument. Note that if both
1256*stream* and *filename* keyword arguments are passed, the *stream* argument is
1257ignored.
1258
1259Of course, you can put variable information in your output. To do this, simply
1260have the message be a format string and pass in additional arguments containing
1261the variable information, as in the following example::
1262
1263 import logging
1264
1265 logging.basicConfig(level=logging.DEBUG,
1266 format='%(asctime)s %(levelname)-8s %(message)s',
1267 datefmt='%a, %d %b %Y %H:%M:%S',
1268 filename='/temp/myapp.log',
1269 filemode='w')
1270 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1271
1272which would result in ::
1273
1274 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1275
1276
1277.. _multiple-destinations:
1278
1279Logging to multiple destinations
1280--------------------------------
1281
1282Let's say you want to log to console and file with different message formats and
1283in differing circumstances. Say you want to log messages with levels of DEBUG
1284and higher to file, and those messages at level INFO and higher to the console.
1285Let's also assume that the file should contain timestamps, but the console
1286messages should not. Here's how you can achieve this::
1287
1288 import logging
1289
1290 # set up logging to file - see previous section for more details
1291 logging.basicConfig(level=logging.DEBUG,
1292 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1293 datefmt='%m-%d %H:%M',
1294 filename='/temp/myapp.log',
1295 filemode='w')
1296 # define a Handler which writes INFO messages or higher to the sys.stderr
1297 console = logging.StreamHandler()
1298 console.setLevel(logging.INFO)
1299 # set a format which is simpler for console use
1300 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1301 # tell the handler to use this format
1302 console.setFormatter(formatter)
1303 # add the handler to the root logger
1304 logging.getLogger('').addHandler(console)
1305
1306 # Now, we can log to the root logger, or any other logger. First the root...
1307 logging.info('Jackdaws love my big sphinx of quartz.')
1308
1309 # Now, define a couple of other loggers which might represent areas in your
1310 # application:
1311
1312 logger1 = logging.getLogger('myapp.area1')
1313 logger2 = logging.getLogger('myapp.area2')
1314
1315 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1316 logger1.info('How quickly daft jumping zebras vex.')
1317 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1318 logger2.error('The five boxing wizards jump quickly.')
1319
1320When you run this, on the console you will see ::
1321
1322 root : INFO Jackdaws love my big sphinx of quartz.
1323 myapp.area1 : INFO How quickly daft jumping zebras vex.
1324 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1325 myapp.area2 : ERROR The five boxing wizards jump quickly.
1326
1327and in the file you will see something like ::
1328
1329 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1330 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1331 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1332 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1333 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1334
1335As you can see, the DEBUG message only shows up in the file. The other messages
1336are sent to both destinations.
1337
1338This example uses console and file handlers, but you can use any number and
1339combination of handlers you choose.
1340
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001341.. _logging-exceptions:
1342
1343Exceptions raised during logging
1344--------------------------------
1345
1346The logging package is designed to swallow exceptions which occur while logging
1347in production. This is so that errors which occur while handling logging events
1348- such as logging misconfiguration, network or other similar errors - do not
1349cause the application using logging to terminate prematurely.
1350
1351:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1352swallowed. Other exceptions which occur during the :meth:`emit` method of a
1353:class:`Handler` subclass are passed to its :meth:`handleError` method.
1354
1355The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001356to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1357traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001358
Georg Brandlef871f62010-03-12 10:06:40 +00001359**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001360during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001361occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001362usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001363
Christian Heimes790c8232008-01-07 21:14:23 +00001364.. _context-info:
1365
1366Adding contextual information to your logging output
1367----------------------------------------------------
1368
1369Sometimes you want logging output to contain contextual information in
1370addition to the parameters passed to the logging call. For example, in a
1371networked application, it may be desirable to log client-specific information
1372in the log (e.g. remote client's username, or IP address). Although you could
1373use the *extra* parameter to achieve this, it's not always convenient to pass
1374the information in this way. While it might be tempting to create
1375:class:`Logger` instances on a per-connection basis, this is not a good idea
1376because these instances are not garbage collected. While this is not a problem
1377in practice, when the number of :class:`Logger` instances is dependent on the
1378level of granularity you want to use in logging an application, it could
1379be hard to manage if the number of :class:`Logger` instances becomes
1380effectively unbounded.
1381
Vinay Sajipc31be632010-09-06 22:18:20 +00001382
1383Using LoggerAdapters to impart contextual information
1384^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1385
Christian Heimes04c420f2008-01-18 18:40:46 +00001386An easy way in which you can pass contextual information to be output along
1387with logging event information is to use the :class:`LoggerAdapter` class.
1388This class is designed to look like a :class:`Logger`, so that you can call
1389:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1390:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1391same signatures as their counterparts in :class:`Logger`, so you can use the
1392two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001393
Christian Heimes04c420f2008-01-18 18:40:46 +00001394When you create an instance of :class:`LoggerAdapter`, you pass it a
1395:class:`Logger` instance and a dict-like object which contains your contextual
1396information. When you call one of the logging methods on an instance of
1397:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1398:class:`Logger` passed to its constructor, and arranges to pass the contextual
1399information in the delegated call. Here's a snippet from the code of
1400:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001401
Christian Heimes04c420f2008-01-18 18:40:46 +00001402 def debug(self, msg, *args, **kwargs):
1403 """
1404 Delegate a debug call to the underlying logger, after adding
1405 contextual information from this adapter instance.
1406 """
1407 msg, kwargs = self.process(msg, kwargs)
1408 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001409
Christian Heimes04c420f2008-01-18 18:40:46 +00001410The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1411information is added to the logging output. It's passed the message and
1412keyword arguments of the logging call, and it passes back (potentially)
1413modified versions of these to use in the call to the underlying logger. The
1414default implementation of this method leaves the message alone, but inserts
1415an "extra" key in the keyword argument whose value is the dict-like object
1416passed to the constructor. Of course, if you had passed an "extra" keyword
1417argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001418
Christian Heimes04c420f2008-01-18 18:40:46 +00001419The advantage of using "extra" is that the values in the dict-like object are
1420merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1421customized strings with your :class:`Formatter` instances which know about
1422the keys of the dict-like object. If you need a different method, e.g. if you
1423want to prepend or append the contextual information to the message string,
1424you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1425to do what you need. Here's an example script which uses this class, which
1426also illustrates what dict-like behaviour is needed from an arbitrary
1427"dict-like" object for use in the constructor::
1428
Christian Heimes587c2bf2008-01-19 16:21:02 +00001429 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001430
Christian Heimes587c2bf2008-01-19 16:21:02 +00001431 class ConnInfo:
1432 """
1433 An example class which shows how an arbitrary class can be used as
1434 the 'extra' context information repository passed to a LoggerAdapter.
1435 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001436
Christian Heimes587c2bf2008-01-19 16:21:02 +00001437 def __getitem__(self, name):
1438 """
1439 To allow this instance to look like a dict.
1440 """
1441 from random import choice
1442 if name == "ip":
1443 result = choice(["127.0.0.1", "192.168.0.1"])
1444 elif name == "user":
1445 result = choice(["jim", "fred", "sheila"])
1446 else:
1447 result = self.__dict__.get(name, "?")
1448 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001449
Christian Heimes587c2bf2008-01-19 16:21:02 +00001450 def __iter__(self):
1451 """
1452 To allow iteration over keys, which will be merged into
1453 the LogRecord dict before formatting and output.
1454 """
1455 keys = ["ip", "user"]
1456 keys.extend(self.__dict__.keys())
1457 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001458
Christian Heimes587c2bf2008-01-19 16:21:02 +00001459 if __name__ == "__main__":
1460 from random import choice
1461 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1462 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1463 { "ip" : "123.231.231.123", "user" : "sheila" })
1464 logging.basicConfig(level=logging.DEBUG,
1465 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1466 a1.debug("A debug message")
1467 a1.info("An info message with %s", "some parameters")
1468 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1469 for x in range(10):
1470 lvl = choice(levels)
1471 lvlname = logging.getLevelName(lvl)
1472 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001473
1474When this script is run, the output should look something like this::
1475
Christian Heimes587c2bf2008-01-19 16:21:02 +00001476 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1477 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1478 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
1479 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
1480 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
1481 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
1482 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
1483 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
1484 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
1485 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
1486 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
1487 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 +00001488
Christian Heimes790c8232008-01-07 21:14:23 +00001489
Vinay Sajipac007992010-09-17 12:45:26 +00001490.. _filters-contextual:
1491
Vinay Sajipc31be632010-09-06 22:18:20 +00001492Using Filters to impart contextual information
1493^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1494
1495You can also add contextual information to log output using a user-defined
1496:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1497passed to them, including adding additional attributes which can then be output
1498using a suitable format string, or if needed a custom :class:`Formatter`.
1499
1500For example in a web application, the request being processed (or at least,
1501the interesting parts of it) can be stored in a threadlocal
1502(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1503add, say, information from the request - say, the remote IP address and remote
1504user's username - to the ``LogRecord``, using the attribute names 'ip' and
1505'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1506string can be used to get similar output to that shown above. Here's an example
1507script::
1508
1509 import logging
1510 from random import choice
1511
1512 class ContextFilter(logging.Filter):
1513 """
1514 This is a filter which injects contextual information into the log.
1515
1516 Rather than use actual contextual information, we just use random
1517 data in this demo.
1518 """
1519
1520 USERS = ['jim', 'fred', 'sheila']
1521 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1522
1523 def filter(self, record):
1524
1525 record.ip = choice(ContextFilter.IPS)
1526 record.user = choice(ContextFilter.USERS)
1527 return True
1528
1529 if __name__ == "__main__":
1530 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1531 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1532 { "ip" : "123.231.231.123", "user" : "sheila" })
1533 logging.basicConfig(level=logging.DEBUG,
1534 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1535 a1 = logging.getLogger("a.b.c")
1536 a2 = logging.getLogger("d.e.f")
1537
1538 f = ContextFilter()
1539 a1.addFilter(f)
1540 a2.addFilter(f)
1541 a1.debug("A debug message")
1542 a1.info("An info message with %s", "some parameters")
1543 for x in range(10):
1544 lvl = choice(levels)
1545 lvlname = logging.getLevelName(lvl)
1546 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1547
1548which, when run, produces something like::
1549
1550 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1551 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1552 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
1553 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
1554 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
1555 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
1556 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
1557 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
1558 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
1559 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
1560 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
1561 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
1562
1563
Vinay Sajipd31f3632010-06-29 15:31:15 +00001564.. _multiple-processes:
1565
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001566Logging to a single file from multiple processes
1567------------------------------------------------
1568
1569Although logging is thread-safe, and logging to a single file from multiple
1570threads in a single process *is* supported, logging to a single file from
1571*multiple processes* is *not* supported, because there is no standard way to
1572serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001573need to log to a single file from multiple processes, one way of doing this is
1574to have all the processes log to a :class:`SocketHandler`, and have a separate
1575process which implements a socket server which reads from the socket and logs
1576to file. (If you prefer, you can dedicate one thread in one of the existing
1577processes to perform this function.) The following section documents this
1578approach in more detail and includes a working socket receiver which can be
1579used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001580
Vinay Sajip5a92b132009-08-15 23:35:08 +00001581If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001582:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001583:class:`Lock` class from this module to serialize access to the file from
1584your processes. The existing :class:`FileHandler` and subclasses do not make
1585use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001586Note that at present, the :mod:`multiprocessing` module does not provide
1587working lock functionality on all platforms (see
1588http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001589
Vinay Sajip121a1c42010-09-08 10:46:15 +00001590.. currentmodule:: logging.handlers
1591
1592Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1593all logging events to one of the processes in your multi-process application.
1594The following example script demonstrates how you can do this; in the example
1595a separate listener process listens for events sent by other processes and logs
1596them according to its own logging configuration. Although the example only
1597demonstrates one way of doing it (for example, you may want to use a listener
1598thread rather than a separate listener process - the implementation would be
1599analogous) it does allow for completely different logging configurations for
1600the listener and the other processes in your application, and can be used as
1601the basis for code meeting your own specific requirements::
1602
1603 # You'll need these imports in your own code
1604 import logging
1605 import logging.handlers
1606 import multiprocessing
1607
1608 # Next two import lines for this demo only
1609 from random import choice, random
1610 import time
1611
1612 #
1613 # Because you'll want to define the logging configurations for listener and workers, the
1614 # listener and worker process functions take a configurer parameter which is a callable
1615 # for configuring logging for that process. These functions are also passed the queue,
1616 # which they use for communication.
1617 #
1618 # In practice, you can configure the listener however you want, but note that in this
1619 # simple example, the listener does not apply level or filter logic to received records.
1620 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1621 # sending events which would be filtered out between processes.
1622 #
1623 # The size of the rotated files is made small so you can see the results easily.
1624 def listener_configurer():
1625 root = logging.getLogger()
1626 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
1627 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1628 h.setFormatter(f)
1629 root.addHandler(h)
1630
1631 # This is the listener process top-level loop: wait for logging events
1632 # (LogRecords)on the queue and handle them, quit when you get a None for a
1633 # LogRecord.
1634 def listener_process(queue, configurer):
1635 configurer()
1636 while True:
1637 try:
1638 record = queue.get()
1639 if record is None: # We send this as a sentinel to tell the listener to quit.
1640 break
1641 logger = logging.getLogger(record.name)
1642 logger.handle(record) # No level or filter logic applied - just do it!
1643 except (KeyboardInterrupt, SystemExit):
1644 raise
1645 except:
1646 import sys, traceback
1647 print >> sys.stderr, 'Whoops! Problem:'
1648 traceback.print_exc(file=sys.stderr)
1649
1650 # Arrays used for random selections in this demo
1651
1652 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1653 logging.ERROR, logging.CRITICAL]
1654
1655 LOGGERS = ['a.b.c', 'd.e.f']
1656
1657 MESSAGES = [
1658 'Random message #1',
1659 'Random message #2',
1660 'Random message #3',
1661 ]
1662
1663 # The worker configuration is done at the start of the worker process run.
1664 # Note that on Windows you can't rely on fork semantics, so each process
1665 # will run the logging configuration code when it starts.
1666 def worker_configurer(queue):
1667 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1668 root = logging.getLogger()
1669 root.addHandler(h)
1670 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
1671
1672 # This is the worker process top-level loop, which just logs ten events with
1673 # random intervening delays before terminating.
1674 # The print messages are just so you know it's doing something!
1675 def worker_process(queue, configurer):
1676 configurer(queue)
1677 name = multiprocessing.current_process().name
1678 print('Worker started: %s' % name)
1679 for i in range(10):
1680 time.sleep(random())
1681 logger = logging.getLogger(choice(LOGGERS))
1682 level = choice(LEVELS)
1683 message = choice(MESSAGES)
1684 logger.log(level, message)
1685 print('Worker finished: %s' % name)
1686
1687 # Here's where the demo gets orchestrated. Create the queue, create and start
1688 # the listener, create ten workers and start them, wait for them to finish,
1689 # then send a None to the queue to tell the listener to finish.
1690 def main():
1691 queue = multiprocessing.Queue(-1)
1692 listener = multiprocessing.Process(target=listener_process,
1693 args=(queue, listener_configurer))
1694 listener.start()
1695 workers = []
1696 for i in range(10):
1697 worker = multiprocessing.Process(target=worker_process,
1698 args=(queue, worker_configurer))
1699 workers.append(worker)
1700 worker.start()
1701 for w in workers:
1702 w.join()
1703 queue.put_nowait(None)
1704 listener.join()
1705
1706 if __name__ == '__main__':
1707 main()
1708
1709
1710.. currentmodule:: logging
1711
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001712
Georg Brandl116aa622007-08-15 14:28:22 +00001713.. _network-logging:
1714
1715Sending and receiving logging events across a network
1716-----------------------------------------------------
1717
1718Let's say you want to send logging events across a network, and handle them at
1719the receiving end. A simple way of doing this is attaching a
1720:class:`SocketHandler` instance to the root logger at the sending end::
1721
1722 import logging, logging.handlers
1723
1724 rootLogger = logging.getLogger('')
1725 rootLogger.setLevel(logging.DEBUG)
1726 socketHandler = logging.handlers.SocketHandler('localhost',
1727 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1728 # don't bother with a formatter, since a socket handler sends the event as
1729 # an unformatted pickle
1730 rootLogger.addHandler(socketHandler)
1731
1732 # Now, we can log to the root logger, or any other logger. First the root...
1733 logging.info('Jackdaws love my big sphinx of quartz.')
1734
1735 # Now, define a couple of other loggers which might represent areas in your
1736 # application:
1737
1738 logger1 = logging.getLogger('myapp.area1')
1739 logger2 = logging.getLogger('myapp.area2')
1740
1741 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1742 logger1.info('How quickly daft jumping zebras vex.')
1743 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1744 logger2.error('The five boxing wizards jump quickly.')
1745
Alexandre Vassalottice261952008-05-12 02:31:37 +00001746At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001747module. Here is a basic working example::
1748
Georg Brandla35f4b92009-05-31 16:41:59 +00001749 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001750 import logging
1751 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001752 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001753 import struct
1754
1755
Alexandre Vassalottice261952008-05-12 02:31:37 +00001756 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001757 """Handler for a streaming logging request.
1758
1759 This basically logs the record using whatever logging policy is
1760 configured locally.
1761 """
1762
1763 def handle(self):
1764 """
1765 Handle multiple requests - each expected to be a 4-byte length,
1766 followed by the LogRecord in pickle format. Logs the record
1767 according to whatever policy is configured locally.
1768 """
Collin Winter46334482007-09-10 00:49:57 +00001769 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001770 chunk = self.connection.recv(4)
1771 if len(chunk) < 4:
1772 break
1773 slen = struct.unpack(">L", chunk)[0]
1774 chunk = self.connection.recv(slen)
1775 while len(chunk) < slen:
1776 chunk = chunk + self.connection.recv(slen - len(chunk))
1777 obj = self.unPickle(chunk)
1778 record = logging.makeLogRecord(obj)
1779 self.handleLogRecord(record)
1780
1781 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001782 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001783
1784 def handleLogRecord(self, record):
1785 # if a name is specified, we use the named logger rather than the one
1786 # implied by the record.
1787 if self.server.logname is not None:
1788 name = self.server.logname
1789 else:
1790 name = record.name
1791 logger = logging.getLogger(name)
1792 # N.B. EVERY record gets logged. This is because Logger.handle
1793 # is normally called AFTER logger-level filtering. If you want
1794 # to do filtering, do it at the client end to save wasting
1795 # cycles and network bandwidth!
1796 logger.handle(record)
1797
Alexandre Vassalottice261952008-05-12 02:31:37 +00001798 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001799 """simple TCP socket-based logging receiver suitable for testing.
1800 """
1801
1802 allow_reuse_address = 1
1803
1804 def __init__(self, host='localhost',
1805 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1806 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001807 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001808 self.abort = 0
1809 self.timeout = 1
1810 self.logname = None
1811
1812 def serve_until_stopped(self):
1813 import select
1814 abort = 0
1815 while not abort:
1816 rd, wr, ex = select.select([self.socket.fileno()],
1817 [], [],
1818 self.timeout)
1819 if rd:
1820 self.handle_request()
1821 abort = self.abort
1822
1823 def main():
1824 logging.basicConfig(
1825 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1826 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001827 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001828 tcpserver.serve_until_stopped()
1829
1830 if __name__ == "__main__":
1831 main()
1832
1833First run the server, and then the client. On the client side, nothing is
1834printed on the console; on the server side, you should see something like::
1835
1836 About to start TCP server...
1837 59 root INFO Jackdaws love my big sphinx of quartz.
1838 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1839 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1840 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1841 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1842
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001843Note that there are some security issues with pickle in some scenarios. If
1844these affect you, you can use an alternative serialization scheme by overriding
1845the :meth:`makePickle` method and implementing your alternative there, as
1846well as adapting the above script to use your alternative serialization.
1847
Vinay Sajip4039aff2010-09-11 10:25:28 +00001848.. _arbitrary-object-messages:
1849
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001850Using arbitrary objects as messages
1851-----------------------------------
1852
1853In the preceding sections and examples, it has been assumed that the message
1854passed when logging the event is a string. However, this is not the only
1855possibility. You can pass an arbitrary object as a message, and its
1856:meth:`__str__` method will be called when the logging system needs to convert
1857it to a string representation. In fact, if you want to, you can avoid
1858computing a string representation altogether - for example, the
1859:class:`SocketHandler` emits an event by pickling it and sending it over the
1860wire.
1861
Vinay Sajip55778922010-09-23 09:09:15 +00001862Dealing with handlers that block
1863--------------------------------
1864
1865.. currentmodule:: logging.handlers
1866
1867Sometimes you have to get your logging handlers to do their work without
1868blocking the thread you’re logging from. This is common in Web applications,
1869though of course it also occurs in other scenarios.
1870
1871A common culprit which demonstrates sluggish behaviour is the
1872:class:`SMTPHandler`: sending emails can take a long time, for a
1873number of reasons outside the developer’s control (for example, a poorly
1874performing mail or network infrastructure). But almost any network-based
1875handler can block: Even a :class:`SocketHandler` operation may do a
1876DNS query under the hood which is too slow (and this query can be deep in the
1877socket library code, below the Python layer, and outside your control).
1878
1879One solution is to use a two-part approach. For the first part, attach only a
1880:class:`QueueHandler` to those loggers which are accessed from
1881performance-critical threads. They simply write to their queue, which can be
1882sized to a large enough capacity or initialized with no upper bound to their
1883size. The write to the queue will typically be accepted quickly, though you
1884will probably need to catch the :ref:`queue.Full` exception as a precaution
1885in your code. If you are a library developer who has performance-critical
1886threads in their code, be sure to document this (together with a suggestion to
1887attach only ``QueueHandlers`` to your loggers) for the benefit of other
1888developers who will use your code.
1889
1890The second part of the solution is :class:`QueueListener`, which has been
1891designed as the counterpart to :class:`QueueHandler`. A
1892:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
1893and it fires up an internal thread which listens to its queue for LogRecords
1894sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
1895matter). The ``LogRecords`` are removed from the queue and passed to the
1896handlers for processing.
1897
1898The advantage of having a separate :class:`QueueListener` class is that you
1899can use the same instance to service multiple ``QueueHandlers``. This is more
1900resource-friendly than, say, having threaded versions of the existing handler
1901classes, which would eat up one thread per handler for no particular benefit.
1902
1903An example of using these two classes follows (imports omitted)::
1904
1905 que = queue.Queue(-1) # no limit on size
1906 queue_handler = QueueHandler(que)
1907 handler = logging.StreamHandler()
1908 listener = QueueListener(que, handler)
1909 root = logging.getLogger()
1910 root.addHandler(queue_handler)
1911 formatter = logging.Formatter('%(threadName)s: %(message)s')
1912 handler.setFormatter(formatter)
1913 listener.start()
1914 # The log output will display the thread which generated
1915 # the event (the main thread) rather than the internal
1916 # thread which monitors the internal queue. This is what
1917 # you want to happen.
1918 root.warning('Look out!')
1919 listener.stop()
1920
1921which, when run, will produce::
1922
1923 MainThread: Look out!
1924
1925
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001926Optimization
1927------------
1928
1929Formatting of message arguments is deferred until it cannot be avoided.
1930However, computing the arguments passed to the logging method can also be
1931expensive, and you may want to avoid doing it if the logger will just throw
1932away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1933method which takes a level argument and returns true if the event would be
1934created by the Logger for that level of call. You can write code like this::
1935
1936 if logger.isEnabledFor(logging.DEBUG):
1937 logger.debug("Message with %s, %s", expensive_func1(),
1938 expensive_func2())
1939
1940so that if the logger's threshold is set above ``DEBUG``, the calls to
1941:func:`expensive_func1` and :func:`expensive_func2` are never made.
1942
1943There are other optimizations which can be made for specific applications which
1944need more precise control over what logging information is collected. Here's a
1945list of things you can do to avoid processing during logging which you don't
1946need:
1947
1948+-----------------------------------------------+----------------------------------------+
1949| What you don't want to collect | How to avoid collecting it |
1950+===============================================+========================================+
1951| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1952+-----------------------------------------------+----------------------------------------+
1953| Threading information. | Set ``logging.logThreads`` to ``0``. |
1954+-----------------------------------------------+----------------------------------------+
1955| Process information. | Set ``logging.logProcesses`` to ``0``. |
1956+-----------------------------------------------+----------------------------------------+
1957
1958Also note that the core logging module only includes the basic handlers. If
1959you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1960take up any memory.
1961
1962.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001963
1964Handler Objects
1965---------------
1966
1967Handlers have the following attributes and methods. Note that :class:`Handler`
1968is never instantiated directly; this class acts as a base for more useful
1969subclasses. However, the :meth:`__init__` method in subclasses needs to call
1970:meth:`Handler.__init__`.
1971
1972
1973.. method:: Handler.__init__(level=NOTSET)
1974
1975 Initializes the :class:`Handler` instance by setting its level, setting the list
1976 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1977 serializing access to an I/O mechanism.
1978
1979
1980.. method:: Handler.createLock()
1981
1982 Initializes a thread lock which can be used to serialize access to underlying
1983 I/O functionality which may not be threadsafe.
1984
1985
1986.. method:: Handler.acquire()
1987
1988 Acquires the thread lock created with :meth:`createLock`.
1989
1990
1991.. method:: Handler.release()
1992
1993 Releases the thread lock acquired with :meth:`acquire`.
1994
1995
1996.. method:: Handler.setLevel(lvl)
1997
1998 Sets the threshold for this handler to *lvl*. Logging messages which are less
1999 severe than *lvl* will be ignored. When a handler is created, the level is set
2000 to :const:`NOTSET` (which causes all messages to be processed).
2001
2002
2003.. method:: Handler.setFormatter(form)
2004
2005 Sets the :class:`Formatter` for this handler to *form*.
2006
2007
2008.. method:: Handler.addFilter(filt)
2009
2010 Adds the specified filter *filt* to this handler.
2011
2012
2013.. method:: Handler.removeFilter(filt)
2014
2015 Removes the specified filter *filt* from this handler.
2016
2017
2018.. method:: Handler.filter(record)
2019
2020 Applies this handler's filters to the record and returns a true value if the
2021 record is to be processed.
2022
2023
2024.. method:: Handler.flush()
2025
2026 Ensure all logging output has been flushed. This version does nothing and is
2027 intended to be implemented by subclasses.
2028
2029
2030.. method:: Handler.close()
2031
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002032 Tidy up any resources used by the handler. This version does no output but
2033 removes the handler from an internal list of handlers which is closed when
2034 :func:`shutdown` is called. Subclasses should ensure that this gets called
2035 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002036
2037
2038.. method:: Handler.handle(record)
2039
2040 Conditionally emits the specified logging record, depending on filters which may
2041 have been added to the handler. Wraps the actual emission of the record with
2042 acquisition/release of the I/O thread lock.
2043
2044
2045.. method:: Handler.handleError(record)
2046
2047 This method should be called from handlers when an exception is encountered
2048 during an :meth:`emit` call. By default it does nothing, which means that
2049 exceptions get silently ignored. This is what is mostly wanted for a logging
2050 system - most users will not care about errors in the logging system, they are
2051 more interested in application errors. You could, however, replace this with a
2052 custom handler if you wish. The specified record is the one which was being
2053 processed when the exception occurred.
2054
2055
2056.. method:: Handler.format(record)
2057
2058 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2059 default formatter for the module.
2060
2061
2062.. method:: Handler.emit(record)
2063
2064 Do whatever it takes to actually log the specified logging record. This version
2065 is intended to be implemented by subclasses and so raises a
2066 :exc:`NotImplementedError`.
2067
2068
Vinay Sajipd31f3632010-06-29 15:31:15 +00002069.. _stream-handler:
2070
Georg Brandl116aa622007-08-15 14:28:22 +00002071StreamHandler
2072^^^^^^^^^^^^^
2073
2074The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2075sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2076file-like object (or, more precisely, any object which supports :meth:`write`
2077and :meth:`flush` methods).
2078
2079
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002080.. currentmodule:: logging
2081
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002082.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002083
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002084 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002085 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2086 will be used.
2087
2088
Benjamin Petersone41251e2008-04-25 01:59:09 +00002089 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002090
Benjamin Petersone41251e2008-04-25 01:59:09 +00002091 If a formatter is specified, it is used to format the record. The record
2092 is then written to the stream with a trailing newline. If exception
2093 information is present, it is formatted using
2094 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002095
2096
Benjamin Petersone41251e2008-04-25 01:59:09 +00002097 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002098
Benjamin Petersone41251e2008-04-25 01:59:09 +00002099 Flushes the stream by calling its :meth:`flush` method. Note that the
2100 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002101 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002102
2103
Vinay Sajipd31f3632010-06-29 15:31:15 +00002104.. _file-handler:
2105
Georg Brandl116aa622007-08-15 14:28:22 +00002106FileHandler
2107^^^^^^^^^^^
2108
2109The :class:`FileHandler` class, located in the core :mod:`logging` package,
2110sends logging output to a disk file. It inherits the output functionality from
2111:class:`StreamHandler`.
2112
2113
Vinay Sajipd31f3632010-06-29 15:31:15 +00002114.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002115
2116 Returns a new instance of the :class:`FileHandler` class. The specified file is
2117 opened and used as the stream for logging. If *mode* is not specified,
2118 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002119 with that encoding. If *delay* is true, then file opening is deferred until the
2120 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002121
2122
Benjamin Petersone41251e2008-04-25 01:59:09 +00002123 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002124
Benjamin Petersone41251e2008-04-25 01:59:09 +00002125 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002126
2127
Benjamin Petersone41251e2008-04-25 01:59:09 +00002128 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002129
Benjamin Petersone41251e2008-04-25 01:59:09 +00002130 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002131
Vinay Sajipd31f3632010-06-29 15:31:15 +00002132.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002133
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002134NullHandler
2135^^^^^^^^^^^
2136
2137.. versionadded:: 3.1
2138
2139The :class:`NullHandler` class, located in the core :mod:`logging` package,
2140does not do any formatting or output. It is essentially a "no-op" handler
2141for use by library developers.
2142
2143
2144.. class:: NullHandler()
2145
2146 Returns a new instance of the :class:`NullHandler` class.
2147
2148
2149 .. method:: emit(record)
2150
2151 This method does nothing.
2152
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002153 .. method:: handle(record)
2154
2155 This method does nothing.
2156
2157 .. method:: createLock()
2158
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002159 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002160 underlying I/O to which access needs to be serialized.
2161
2162
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002163See :ref:`library-config` for more information on how to use
2164:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002165
Vinay Sajipd31f3632010-06-29 15:31:15 +00002166.. _watched-file-handler:
2167
Georg Brandl116aa622007-08-15 14:28:22 +00002168WatchedFileHandler
2169^^^^^^^^^^^^^^^^^^
2170
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002171.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002172
Georg Brandl116aa622007-08-15 14:28:22 +00002173The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2174module, is a :class:`FileHandler` which watches the file it is logging to. If
2175the file changes, it is closed and reopened using the file name.
2176
2177A file change can happen because of usage of programs such as *newsyslog* and
2178*logrotate* which perform log file rotation. This handler, intended for use
2179under Unix/Linux, watches the file to see if it has changed since the last emit.
2180(A file is deemed to have changed if its device or inode have changed.) If the
2181file has changed, the old file stream is closed, and the file opened to get a
2182new stream.
2183
2184This handler is not appropriate for use under Windows, because under Windows
2185open log files cannot be moved or renamed - logging opens the files with
2186exclusive locks - and so there is no need for such a handler. Furthermore,
2187*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2188this value.
2189
2190
Christian Heimese7a15bb2008-01-24 16:21:45 +00002191.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002192
2193 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2194 file is opened and used as the stream for logging. If *mode* is not specified,
2195 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002196 with that encoding. If *delay* is true, then file opening is deferred until the
2197 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002198
2199
Benjamin Petersone41251e2008-04-25 01:59:09 +00002200 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002201
Benjamin Petersone41251e2008-04-25 01:59:09 +00002202 Outputs the record to the file, but first checks to see if the file has
2203 changed. If it has, the existing stream is flushed and closed and the
2204 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002205
Vinay Sajipd31f3632010-06-29 15:31:15 +00002206.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002207
2208RotatingFileHandler
2209^^^^^^^^^^^^^^^^^^^
2210
2211The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2212module, supports rotation of disk log files.
2213
2214
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002215.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002216
2217 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2218 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002219 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2220 with that encoding. If *delay* is true, then file opening is deferred until the
2221 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002222
2223 You can use the *maxBytes* and *backupCount* values to allow the file to
2224 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2225 the file is closed and a new file is silently opened for output. Rollover occurs
2226 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2227 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2228 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2229 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2230 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2231 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2232 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2233 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2234 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2235
2236
Benjamin Petersone41251e2008-04-25 01:59:09 +00002237 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002238
Benjamin Petersone41251e2008-04-25 01:59:09 +00002239 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002240
2241
Benjamin Petersone41251e2008-04-25 01:59:09 +00002242 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002243
Benjamin Petersone41251e2008-04-25 01:59:09 +00002244 Outputs the record to the file, catering for rollover as described
2245 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002246
Vinay Sajipd31f3632010-06-29 15:31:15 +00002247.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002248
2249TimedRotatingFileHandler
2250^^^^^^^^^^^^^^^^^^^^^^^^
2251
2252The :class:`TimedRotatingFileHandler` class, located in the
2253:mod:`logging.handlers` module, supports rotation of disk log files at certain
2254timed intervals.
2255
2256
Vinay Sajipd31f3632010-06-29 15:31:15 +00002257.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002258
2259 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2260 specified file is opened and used as the stream for logging. On rotating it also
2261 sets the filename suffix. Rotating happens based on the product of *when* and
2262 *interval*.
2263
2264 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002265 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002266
Christian Heimesb558a2e2008-03-02 22:46:37 +00002267 +----------------+-----------------------+
2268 | Value | Type of interval |
2269 +================+=======================+
2270 | ``'S'`` | Seconds |
2271 +----------------+-----------------------+
2272 | ``'M'`` | Minutes |
2273 +----------------+-----------------------+
2274 | ``'H'`` | Hours |
2275 +----------------+-----------------------+
2276 | ``'D'`` | Days |
2277 +----------------+-----------------------+
2278 | ``'W'`` | Week day (0=Monday) |
2279 +----------------+-----------------------+
2280 | ``'midnight'`` | Roll over at midnight |
2281 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002282
Christian Heimesb558a2e2008-03-02 22:46:37 +00002283 The system will save old log files by appending extensions to the filename.
2284 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002285 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002286 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002287
2288 When computing the next rollover time for the first time (when the handler
2289 is created), the last modification time of an existing log file, or else
2290 the current time, is used to compute when the next rotation will occur.
2291
Georg Brandl0c77a822008-06-10 16:37:50 +00002292 If the *utc* argument is true, times in UTC will be used; otherwise
2293 local time is used.
2294
2295 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002296 will be kept, and if more would be created when rollover occurs, the oldest
2297 one is deleted. The deletion logic uses the interval to determine which
2298 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002299
Vinay Sajipd31f3632010-06-29 15:31:15 +00002300 If *delay* is true, then file opening is deferred until the first call to
2301 :meth:`emit`.
2302
Georg Brandl116aa622007-08-15 14:28:22 +00002303
Benjamin Petersone41251e2008-04-25 01:59:09 +00002304 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002305
Benjamin Petersone41251e2008-04-25 01:59:09 +00002306 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002307
2308
Benjamin Petersone41251e2008-04-25 01:59:09 +00002309 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002310
Benjamin Petersone41251e2008-04-25 01:59:09 +00002311 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002312
2313
Vinay Sajipd31f3632010-06-29 15:31:15 +00002314.. _socket-handler:
2315
Georg Brandl116aa622007-08-15 14:28:22 +00002316SocketHandler
2317^^^^^^^^^^^^^
2318
2319The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2320sends logging output to a network socket. The base class uses a TCP socket.
2321
2322
2323.. class:: SocketHandler(host, port)
2324
2325 Returns a new instance of the :class:`SocketHandler` class intended to
2326 communicate with a remote machine whose address is given by *host* and *port*.
2327
2328
Benjamin Petersone41251e2008-04-25 01:59:09 +00002329 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002330
Benjamin Petersone41251e2008-04-25 01:59:09 +00002331 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002332
2333
Benjamin Petersone41251e2008-04-25 01:59:09 +00002334 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002335
Benjamin Petersone41251e2008-04-25 01:59:09 +00002336 Pickles the record's attribute dictionary and writes it to the socket in
2337 binary format. If there is an error with the socket, silently drops the
2338 packet. If the connection was previously lost, re-establishes the
2339 connection. To unpickle the record at the receiving end into a
2340 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002341
2342
Benjamin Petersone41251e2008-04-25 01:59:09 +00002343 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002344
Benjamin Petersone41251e2008-04-25 01:59:09 +00002345 Handles an error which has occurred during :meth:`emit`. The most likely
2346 cause is a lost connection. Closes the socket so that we can retry on the
2347 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002348
2349
Benjamin Petersone41251e2008-04-25 01:59:09 +00002350 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002351
Benjamin Petersone41251e2008-04-25 01:59:09 +00002352 This is a factory method which allows subclasses to define the precise
2353 type of socket they want. The default implementation creates a TCP socket
2354 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002355
2356
Benjamin Petersone41251e2008-04-25 01:59:09 +00002357 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002358
Benjamin Petersone41251e2008-04-25 01:59:09 +00002359 Pickles the record's attribute dictionary in binary format with a length
2360 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002361
Vinay Sajipd31f3632010-06-29 15:31:15 +00002362 Note that pickles aren't completely secure. If you are concerned about
2363 security, you may want to override this method to implement a more secure
2364 mechanism. For example, you can sign pickles using HMAC and then verify
2365 them on the receiving end, or alternatively you can disable unpickling of
2366 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002367
Benjamin Petersone41251e2008-04-25 01:59:09 +00002368 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002369
Benjamin Petersone41251e2008-04-25 01:59:09 +00002370 Send a pickled string *packet* to the socket. This function allows for
2371 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002372
2373
Vinay Sajipd31f3632010-06-29 15:31:15 +00002374.. _datagram-handler:
2375
Georg Brandl116aa622007-08-15 14:28:22 +00002376DatagramHandler
2377^^^^^^^^^^^^^^^
2378
2379The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2380module, inherits from :class:`SocketHandler` to support sending logging messages
2381over UDP sockets.
2382
2383
2384.. class:: DatagramHandler(host, port)
2385
2386 Returns a new instance of the :class:`DatagramHandler` class intended to
2387 communicate with a remote machine whose address is given by *host* and *port*.
2388
2389
Benjamin Petersone41251e2008-04-25 01:59:09 +00002390 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002391
Benjamin Petersone41251e2008-04-25 01:59:09 +00002392 Pickles the record's attribute dictionary and writes it to the socket in
2393 binary format. If there is an error with the socket, silently drops the
2394 packet. To unpickle the record at the receiving end into a
2395 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002396
2397
Benjamin Petersone41251e2008-04-25 01:59:09 +00002398 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002399
Benjamin Petersone41251e2008-04-25 01:59:09 +00002400 The factory method of :class:`SocketHandler` is here overridden to create
2401 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002402
2403
Benjamin Petersone41251e2008-04-25 01:59:09 +00002404 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002405
Benjamin Petersone41251e2008-04-25 01:59:09 +00002406 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002407
2408
Vinay Sajipd31f3632010-06-29 15:31:15 +00002409.. _syslog-handler:
2410
Georg Brandl116aa622007-08-15 14:28:22 +00002411SysLogHandler
2412^^^^^^^^^^^^^
2413
2414The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2415supports sending logging messages to a remote or local Unix syslog.
2416
2417
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002418.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002419
2420 Returns a new instance of the :class:`SysLogHandler` class intended to
2421 communicate with a remote Unix machine whose address is given by *address* in
2422 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002423 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002424 alternative to providing a ``(host, port)`` tuple is providing an address as a
2425 string, for example "/dev/log". In this case, a Unix domain socket is used to
2426 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002427 :const:`LOG_USER` is used. The type of socket opened depends on the
2428 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2429 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2430 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2431
Vinay Sajip972412d2010-09-23 20:31:24 +00002432 Note that if your server is not listening on UDP port 514,
2433 :class:`SysLogHandler` may appear not to work. In that case, check what
2434 address you should be using for a domain socket - it's system dependent.
2435 For example, on Linux it's usually "/dev/log" but on OS/X it's
2436 "/var/run/syslog". You'll need to check your platform and use the
2437 appropriate address (you may need to do this check at runtime if your
2438 application needs to run on several platforms). On Windows, you pretty
2439 much have to use the UDP option.
2440
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002441 .. versionchanged:: 3.2
2442 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002443
2444
Benjamin Petersone41251e2008-04-25 01:59:09 +00002445 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002446
Benjamin Petersone41251e2008-04-25 01:59:09 +00002447 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002448
2449
Benjamin Petersone41251e2008-04-25 01:59:09 +00002450 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002451
Benjamin Petersone41251e2008-04-25 01:59:09 +00002452 The record is formatted, and then sent to the syslog server. If exception
2453 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002454
2455
Benjamin Petersone41251e2008-04-25 01:59:09 +00002456 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002457
Benjamin Petersone41251e2008-04-25 01:59:09 +00002458 Encodes the facility and priority into an integer. You can pass in strings
2459 or integers - if strings are passed, internal mapping dictionaries are
2460 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002461
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002462 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2463 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002464
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002465 **Priorities**
2466
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002467 +--------------------------+---------------+
2468 | Name (string) | Symbolic value|
2469 +==========================+===============+
2470 | ``alert`` | LOG_ALERT |
2471 +--------------------------+---------------+
2472 | ``crit`` or ``critical`` | LOG_CRIT |
2473 +--------------------------+---------------+
2474 | ``debug`` | LOG_DEBUG |
2475 +--------------------------+---------------+
2476 | ``emerg`` or ``panic`` | LOG_EMERG |
2477 +--------------------------+---------------+
2478 | ``err`` or ``error`` | LOG_ERR |
2479 +--------------------------+---------------+
2480 | ``info`` | LOG_INFO |
2481 +--------------------------+---------------+
2482 | ``notice`` | LOG_NOTICE |
2483 +--------------------------+---------------+
2484 | ``warn`` or ``warning`` | LOG_WARNING |
2485 +--------------------------+---------------+
2486
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002487 **Facilities**
2488
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002489 +---------------+---------------+
2490 | Name (string) | Symbolic value|
2491 +===============+===============+
2492 | ``auth`` | LOG_AUTH |
2493 +---------------+---------------+
2494 | ``authpriv`` | LOG_AUTHPRIV |
2495 +---------------+---------------+
2496 | ``cron`` | LOG_CRON |
2497 +---------------+---------------+
2498 | ``daemon`` | LOG_DAEMON |
2499 +---------------+---------------+
2500 | ``ftp`` | LOG_FTP |
2501 +---------------+---------------+
2502 | ``kern`` | LOG_KERN |
2503 +---------------+---------------+
2504 | ``lpr`` | LOG_LPR |
2505 +---------------+---------------+
2506 | ``mail`` | LOG_MAIL |
2507 +---------------+---------------+
2508 | ``news`` | LOG_NEWS |
2509 +---------------+---------------+
2510 | ``syslog`` | LOG_SYSLOG |
2511 +---------------+---------------+
2512 | ``user`` | LOG_USER |
2513 +---------------+---------------+
2514 | ``uucp`` | LOG_UUCP |
2515 +---------------+---------------+
2516 | ``local0`` | LOG_LOCAL0 |
2517 +---------------+---------------+
2518 | ``local1`` | LOG_LOCAL1 |
2519 +---------------+---------------+
2520 | ``local2`` | LOG_LOCAL2 |
2521 +---------------+---------------+
2522 | ``local3`` | LOG_LOCAL3 |
2523 +---------------+---------------+
2524 | ``local4`` | LOG_LOCAL4 |
2525 +---------------+---------------+
2526 | ``local5`` | LOG_LOCAL5 |
2527 +---------------+---------------+
2528 | ``local6`` | LOG_LOCAL6 |
2529 +---------------+---------------+
2530 | ``local7`` | LOG_LOCAL7 |
2531 +---------------+---------------+
2532
2533 .. method:: mapPriority(levelname)
2534
2535 Maps a logging level name to a syslog priority name.
2536 You may need to override this if you are using custom levels, or
2537 if the default algorithm is not suitable for your needs. The
2538 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2539 ``CRITICAL`` to the equivalent syslog names, and all other level
2540 names to "warning".
2541
2542.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002543
2544NTEventLogHandler
2545^^^^^^^^^^^^^^^^^
2546
2547The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2548module, supports sending logging messages to a local Windows NT, Windows 2000 or
2549Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2550extensions for Python installed.
2551
2552
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002553.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002554
2555 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2556 used to define the application name as it appears in the event log. An
2557 appropriate registry entry is created using this name. The *dllname* should give
2558 the fully qualified pathname of a .dll or .exe which contains message
2559 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2560 - this is installed with the Win32 extensions and contains some basic
2561 placeholder message definitions. Note that use of these placeholders will make
2562 your event logs big, as the entire message source is held in the log. If you
2563 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2564 contains the message definitions you want to use in the event log). The
2565 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2566 defaults to ``'Application'``.
2567
2568
Benjamin Petersone41251e2008-04-25 01:59:09 +00002569 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002570
Benjamin Petersone41251e2008-04-25 01:59:09 +00002571 At this point, you can remove the application name from the registry as a
2572 source of event log entries. However, if you do this, you will not be able
2573 to see the events as you intended in the Event Log Viewer - it needs to be
2574 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002575 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002576
2577
Benjamin Petersone41251e2008-04-25 01:59:09 +00002578 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002579
Benjamin Petersone41251e2008-04-25 01:59:09 +00002580 Determines the message ID, event category and event type, and then logs
2581 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002582
2583
Benjamin Petersone41251e2008-04-25 01:59:09 +00002584 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002585
Benjamin Petersone41251e2008-04-25 01:59:09 +00002586 Returns the event category for the record. Override this if you want to
2587 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002588
2589
Benjamin Petersone41251e2008-04-25 01:59:09 +00002590 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002591
Benjamin Petersone41251e2008-04-25 01:59:09 +00002592 Returns the event type for the record. Override this if you want to
2593 specify your own types. This version does a mapping using the handler's
2594 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2595 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2596 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2597 your own levels, you will either need to override this method or place a
2598 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002599
2600
Benjamin Petersone41251e2008-04-25 01:59:09 +00002601 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002602
Benjamin Petersone41251e2008-04-25 01:59:09 +00002603 Returns the message ID for the record. If you are using your own messages,
2604 you could do this by having the *msg* passed to the logger being an ID
2605 rather than a format string. Then, in here, you could use a dictionary
2606 lookup to get the message ID. This version returns 1, which is the base
2607 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002608
Vinay Sajipd31f3632010-06-29 15:31:15 +00002609.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002610
2611SMTPHandler
2612^^^^^^^^^^^
2613
2614The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2615supports sending logging messages to an email address via SMTP.
2616
2617
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002618.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002619
2620 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2621 initialized with the from and to addresses and subject line of the email. The
2622 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2623 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2624 the standard SMTP port is used. If your SMTP server requires authentication, you
2625 can specify a (username, password) tuple for the *credentials* argument.
2626
Georg Brandl116aa622007-08-15 14:28:22 +00002627
Benjamin Petersone41251e2008-04-25 01:59:09 +00002628 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002629
Benjamin Petersone41251e2008-04-25 01:59:09 +00002630 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002631
2632
Benjamin Petersone41251e2008-04-25 01:59:09 +00002633 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002634
Benjamin Petersone41251e2008-04-25 01:59:09 +00002635 If you want to specify a subject line which is record-dependent, override
2636 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002637
Vinay Sajipd31f3632010-06-29 15:31:15 +00002638.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002639
2640MemoryHandler
2641^^^^^^^^^^^^^
2642
2643The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2644supports buffering of logging records in memory, periodically flushing them to a
2645:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2646event of a certain severity or greater is seen.
2647
2648:class:`MemoryHandler` is a subclass of the more general
2649:class:`BufferingHandler`, which is an abstract class. This buffers logging
2650records in memory. Whenever each record is added to the buffer, a check is made
2651by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2652should, then :meth:`flush` is expected to do the needful.
2653
2654
2655.. class:: BufferingHandler(capacity)
2656
2657 Initializes the handler with a buffer of the specified capacity.
2658
2659
Benjamin Petersone41251e2008-04-25 01:59:09 +00002660 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002661
Benjamin Petersone41251e2008-04-25 01:59:09 +00002662 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2663 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002664
2665
Benjamin Petersone41251e2008-04-25 01:59:09 +00002666 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002667
Benjamin Petersone41251e2008-04-25 01:59:09 +00002668 You can override this to implement custom flushing behavior. This version
2669 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002670
2671
Benjamin Petersone41251e2008-04-25 01:59:09 +00002672 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002673
Benjamin Petersone41251e2008-04-25 01:59:09 +00002674 Returns true if the buffer is up to capacity. This method can be
2675 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002676
2677
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002678.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002679
2680 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2681 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2682 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2683 set using :meth:`setTarget` before this handler does anything useful.
2684
2685
Benjamin Petersone41251e2008-04-25 01:59:09 +00002686 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002687
Benjamin Petersone41251e2008-04-25 01:59:09 +00002688 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2689 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002690
2691
Benjamin Petersone41251e2008-04-25 01:59:09 +00002692 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002693
Benjamin Petersone41251e2008-04-25 01:59:09 +00002694 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00002695 records to the target, if there is one. The buffer is also cleared when
2696 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002697
2698
Benjamin Petersone41251e2008-04-25 01:59:09 +00002699 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002700
Benjamin Petersone41251e2008-04-25 01:59:09 +00002701 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002702
2703
Benjamin Petersone41251e2008-04-25 01:59:09 +00002704 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002705
Benjamin Petersone41251e2008-04-25 01:59:09 +00002706 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002707
2708
Vinay Sajipd31f3632010-06-29 15:31:15 +00002709.. _http-handler:
2710
Georg Brandl116aa622007-08-15 14:28:22 +00002711HTTPHandler
2712^^^^^^^^^^^
2713
2714The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2715supports sending logging messages to a Web server, using either ``GET`` or
2716``POST`` semantics.
2717
2718
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002719.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002720
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002721 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
2722 of the form ``host:port``, should you need to use a specific port number.
2723 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
2724 connection will be used. If *credentials* is specified, it should be a
2725 2-tuple consisting of userid and password, which will be placed in an HTTP
2726 'Authorization' header using Basic authentication. If you specify
2727 credentials, you should also specify secure=True so that your userid and
2728 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00002729
2730
Benjamin Petersone41251e2008-04-25 01:59:09 +00002731 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002732
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002733 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002734
2735
Vinay Sajip121a1c42010-09-08 10:46:15 +00002736.. _queue-handler:
2737
2738
2739QueueHandler
2740^^^^^^^^^^^^
2741
2742The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
2743supports sending logging messages to a queue, such as those implemented in the
2744:mod:`queue` or :mod:`multiprocessing` modules.
2745
Vinay Sajip0637d492010-09-23 08:15:54 +00002746Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
2747to let handlers do their work on a separate thread from the one which does the
2748logging. This is important in Web applications and also other service
2749applications where threads servicing clients need to respond as quickly as
2750possible, while any potentially slow operations (such as sending an email via
2751:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002752
2753.. class:: QueueHandler(queue)
2754
2755 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00002756 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00002757 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00002758 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002759
2760
2761 .. method:: emit(record)
2762
Vinay Sajip0258ce82010-09-22 20:34:53 +00002763 Enqueues the result of preparing the LogRecord.
2764
2765 .. method:: prepare(record)
2766
2767 Prepares a record for queuing. The object returned by this
2768 method is enqueued.
2769
2770 The base implementation formats the record to merge the message
2771 and arguments, and removes unpickleable items from the record
2772 in-place.
2773
2774 You might want to override this method if you want to convert
2775 the record to a dict or JSON string, or send a modified copy
2776 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002777
2778 .. method:: enqueue(record)
2779
2780 Enqueues the record on the queue using ``put_nowait()``; you may
2781 want to override this if you want to use blocking behaviour, or a
2782 timeout, or a customised queue implementation.
2783
2784
2785.. versionadded:: 3.2
2786
2787The :class:`QueueHandler` class was not present in previous versions.
2788
Vinay Sajip0637d492010-09-23 08:15:54 +00002789.. queue-listener:
2790
2791QueueListener
2792^^^^^^^^^^^^^
2793
2794The :class:`QueueListener` class, located in the :mod:`logging.handlers`
2795module, supports receiving logging messages from a queue, such as those
2796implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
2797messages are received from a queue in an internal thread and passed, on
2798the same thread, to one or more handlers for processing.
2799
2800Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
2801to let handlers do their work on a separate thread from the one which does the
2802logging. This is important in Web applications and also other service
2803applications where threads servicing clients need to respond as quickly as
2804possible, while any potentially slow operations (such as sending an email via
2805:class:`SMTPHandler`) are done on a separate thread.
2806
2807.. class:: QueueListener(queue, *handlers)
2808
2809 Returns a new instance of the :class:`QueueListener` class. The instance is
2810 initialized with the queue to send messages to and a list of handlers which
2811 will handle entries placed on the queue. The queue can be any queue-
2812 like object; it's passed as-is to the :meth:`dequeue` method, which needs
2813 to know how to get messages from it.
2814
2815 .. method:: dequeue(block)
2816
2817 Dequeues a record and return it, optionally blocking.
2818
2819 The base implementation uses ``get()``. You may want to override this
2820 method if you want to use timeouts or work with custom queue
2821 implementations.
2822
2823 .. method:: prepare(record)
2824
2825 Prepare a record for handling.
2826
2827 This implementation just returns the passed-in record. You may want to
2828 override this method if you need to do any custom marshalling or
2829 manipulation of the record before passing it to the handlers.
2830
2831 .. method:: handle(record)
2832
2833 Handle a record.
2834
2835 This just loops through the handlers offering them the record
2836 to handle. The actual object passed to the handlers is that which
2837 is returned from :meth:`prepare`.
2838
2839 .. method:: start()
2840
2841 Starts the listener.
2842
2843 This starts up a background thread to monitor the queue for
2844 LogRecords to process.
2845
2846 .. method:: stop()
2847
2848 Stops the listener.
2849
2850 This asks the thread to terminate, and then waits for it to do so.
2851 Note that if you don't call this before your application exits, there
2852 may be some records still left on the queue, which won't be processed.
2853
2854.. versionadded:: 3.2
2855
2856The :class:`QueueListener` class was not present in previous versions.
2857
Vinay Sajip63891ed2010-09-13 20:02:39 +00002858.. _zeromq-handlers:
2859
Vinay Sajip0637d492010-09-23 08:15:54 +00002860Subclassing QueueHandler
2861^^^^^^^^^^^^^^^^^^^^^^^^
2862
Vinay Sajip63891ed2010-09-13 20:02:39 +00002863You can use a :class:`QueueHandler` subclass to send messages to other kinds
2864of queues, for example a ZeroMQ "publish" socket. In the example below,the
2865socket is created separately and passed to the handler (as its 'queue')::
2866
2867 import zmq # using pyzmq, the Python binding for ZeroMQ
2868 import json # for serializing records portably
2869
2870 ctx = zmq.Context()
2871 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
2872 sock.bind('tcp://*:5556') # or wherever
2873
2874 class ZeroMQSocketHandler(QueueHandler):
2875 def enqueue(self, record):
2876 data = json.dumps(record.__dict__)
2877 self.queue.send(data)
2878
Vinay Sajip0055c422010-09-14 09:42:39 +00002879 handler = ZeroMQSocketHandler(sock)
2880
2881
Vinay Sajip63891ed2010-09-13 20:02:39 +00002882Of course there are other ways of organizing this, for example passing in the
2883data needed by the handler to create the socket::
2884
2885 class ZeroMQSocketHandler(QueueHandler):
2886 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
2887 self.ctx = ctx or zmq.Context()
2888 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00002889 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00002890 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00002891
2892 def enqueue(self, record):
2893 data = json.dumps(record.__dict__)
2894 self.queue.send(data)
2895
Vinay Sajipde726922010-09-14 06:59:24 +00002896 def close(self):
2897 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00002898
Vinay Sajip0637d492010-09-23 08:15:54 +00002899Subclassing QueueListener
2900^^^^^^^^^^^^^^^^^^^^^^^^^
2901
2902You can also subclass :class:`QueueListener` to get messages from other kinds
2903of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
2904
2905 class ZeroMQSocketListener(QueueListener):
2906 def __init__(self, uri, *handlers, **kwargs):
2907 self.ctx = kwargs.get('ctx') or zmq.Context()
2908 socket = zmq.Socket(self.ctx, zmq.SUB)
2909 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
2910 socket.connect(uri)
2911
2912 def dequeue(self):
2913 msg = self.queue.recv()
2914 return logging.makeLogRecord(json.loads(msg))
2915
Christian Heimes8b0facf2007-12-04 19:30:01 +00002916.. _formatter-objects:
2917
Georg Brandl116aa622007-08-15 14:28:22 +00002918Formatter Objects
2919-----------------
2920
Benjamin Peterson75edad02009-01-01 15:05:06 +00002921.. currentmodule:: logging
2922
Georg Brandl116aa622007-08-15 14:28:22 +00002923:class:`Formatter`\ s have the following attributes and methods. They are
2924responsible for converting a :class:`LogRecord` to (usually) a string which can
2925be interpreted by either a human or an external system. The base
2926:class:`Formatter` allows a formatting string to be specified. If none is
2927supplied, the default value of ``'%(message)s'`` is used.
2928
2929A Formatter can be initialized with a format string which makes use of knowledge
2930of the :class:`LogRecord` attributes - such as the default value mentioned above
2931making use of the fact that the user's message and arguments are pre-formatted
2932into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002933standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00002934for more information on string formatting.
2935
2936Currently, the useful mapping keys in a :class:`LogRecord` are:
2937
2938+-------------------------+-----------------------------------------------+
2939| Format | Description |
2940+=========================+===============================================+
2941| ``%(name)s`` | Name of the logger (logging channel). |
2942+-------------------------+-----------------------------------------------+
2943| ``%(levelno)s`` | Numeric logging level for the message |
2944| | (:const:`DEBUG`, :const:`INFO`, |
2945| | :const:`WARNING`, :const:`ERROR`, |
2946| | :const:`CRITICAL`). |
2947+-------------------------+-----------------------------------------------+
2948| ``%(levelname)s`` | Text logging level for the message |
2949| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2950| | ``'ERROR'``, ``'CRITICAL'``). |
2951+-------------------------+-----------------------------------------------+
2952| ``%(pathname)s`` | Full pathname of the source file where the |
2953| | logging call was issued (if available). |
2954+-------------------------+-----------------------------------------------+
2955| ``%(filename)s`` | Filename portion of pathname. |
2956+-------------------------+-----------------------------------------------+
2957| ``%(module)s`` | Module (name portion of filename). |
2958+-------------------------+-----------------------------------------------+
2959| ``%(funcName)s`` | Name of function containing the logging call. |
2960+-------------------------+-----------------------------------------------+
2961| ``%(lineno)d`` | Source line number where the logging call was |
2962| | issued (if available). |
2963+-------------------------+-----------------------------------------------+
2964| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2965| | (as returned by :func:`time.time`). |
2966+-------------------------+-----------------------------------------------+
2967| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2968| | created, relative to the time the logging |
2969| | module was loaded. |
2970+-------------------------+-----------------------------------------------+
2971| ``%(asctime)s`` | Human-readable time when the |
2972| | :class:`LogRecord` was created. By default |
2973| | this is of the form "2003-07-08 16:49:45,896" |
2974| | (the numbers after the comma are millisecond |
2975| | portion of the time). |
2976+-------------------------+-----------------------------------------------+
2977| ``%(msecs)d`` | Millisecond portion of the time when the |
2978| | :class:`LogRecord` was created. |
2979+-------------------------+-----------------------------------------------+
2980| ``%(thread)d`` | Thread ID (if available). |
2981+-------------------------+-----------------------------------------------+
2982| ``%(threadName)s`` | Thread name (if available). |
2983+-------------------------+-----------------------------------------------+
2984| ``%(process)d`` | Process ID (if available). |
2985+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00002986| ``%(processName)s`` | Process name (if available). |
2987+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002988| ``%(message)s`` | The logged message, computed as ``msg % |
2989| | args``. |
2990+-------------------------+-----------------------------------------------+
2991
Georg Brandl116aa622007-08-15 14:28:22 +00002992
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002993.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002994
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002995 Returns a new instance of the :class:`Formatter` class. The instance is
2996 initialized with a format string for the message as a whole, as well as a
2997 format string for the date/time portion of a message. If no *fmt* is
2998 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
2999 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003000
Benjamin Petersone41251e2008-04-25 01:59:09 +00003001 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003002
Benjamin Petersone41251e2008-04-25 01:59:09 +00003003 The record's attribute dictionary is used as the operand to a string
3004 formatting operation. Returns the resulting string. Before formatting the
3005 dictionary, a couple of preparatory steps are carried out. The *message*
3006 attribute of the record is computed using *msg* % *args*. If the
3007 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3008 to format the event time. If there is exception information, it is
3009 formatted using :meth:`formatException` and appended to the message. Note
3010 that the formatted exception information is cached in attribute
3011 *exc_text*. This is useful because the exception information can be
3012 pickled and sent across the wire, but you should be careful if you have
3013 more than one :class:`Formatter` subclass which customizes the formatting
3014 of exception information. In this case, you will have to clear the cached
3015 value after a formatter has done its formatting, so that the next
3016 formatter to handle the event doesn't use the cached value but
3017 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003018
3019
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003020 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003021
Benjamin Petersone41251e2008-04-25 01:59:09 +00003022 This method should be called from :meth:`format` by a formatter which
3023 wants to make use of a formatted time. This method can be overridden in
3024 formatters to provide for any specific requirement, but the basic behavior
3025 is as follows: if *datefmt* (a string) is specified, it is used with
3026 :func:`time.strftime` to format the creation time of the
3027 record. Otherwise, the ISO8601 format is used. The resulting string is
3028 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003029
3030
Benjamin Petersone41251e2008-04-25 01:59:09 +00003031 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003032
Benjamin Petersone41251e2008-04-25 01:59:09 +00003033 Formats the specified exception information (a standard exception tuple as
3034 returned by :func:`sys.exc_info`) as a string. This default implementation
3035 just uses :func:`traceback.print_exception`. The resulting string is
3036 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003037
Vinay Sajipd31f3632010-06-29 15:31:15 +00003038.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003039
3040Filter Objects
3041--------------
3042
3043:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
3044more sophisticated filtering than is provided by levels. The base filter class
3045only allows events which are below a certain point in the logger hierarchy. For
3046example, a filter initialized with "A.B" will allow events logged by loggers
3047"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
3048initialized with the empty string, all events are passed.
3049
3050
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003051.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003052
3053 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3054 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003055 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003056
3057
Benjamin Petersone41251e2008-04-25 01:59:09 +00003058 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003059
Benjamin Petersone41251e2008-04-25 01:59:09 +00003060 Is the specified record to be logged? Returns zero for no, nonzero for
3061 yes. If deemed appropriate, the record may be modified in-place by this
3062 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003063
Vinay Sajip81010212010-08-19 19:17:41 +00003064Note that filters attached to handlers are consulted whenever an event is
3065emitted by the handler, whereas filters attached to loggers are consulted
3066whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3067etc.) This means that events which have been generated by descendant loggers
3068will not be filtered by a logger's filter setting, unless the filter has also
3069been applied to those descendant loggers.
3070
Vinay Sajipac007992010-09-17 12:45:26 +00003071Other uses for filters
3072^^^^^^^^^^^^^^^^^^^^^^
3073
3074Although filters are used primarily to filter records based on more
3075sophisticated criteria than levels, they get to see every record which is
3076processed by the handler or logger they're attached to: this can be useful if
3077you want to do things like counting how many records were processed by a
3078particular logger or handler, or adding, changing or removing attributes in
3079the LogRecord being processed. Obviously changing the LogRecord needs to be
3080done with some care, but it does allow the injection of contextual information
3081into logs (see :ref:`filters-contextual`).
3082
Vinay Sajipd31f3632010-06-29 15:31:15 +00003083.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003084
3085LogRecord Objects
3086-----------------
3087
Vinay Sajip4039aff2010-09-11 10:25:28 +00003088:class:`LogRecord` instances are created automatically by the :class:`Logger`
3089every time something is logged, and can be created manually via
3090:func:`makeLogRecord` (for example, from a pickled event received over the
3091wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003092
3093
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003094.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003095
Vinay Sajip4039aff2010-09-11 10:25:28 +00003096 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003097
Vinay Sajip4039aff2010-09-11 10:25:28 +00003098 The primary information is passed in :attr:`msg` and :attr:`args`, which
3099 are combined using ``msg % args`` to create the :attr:`message` field of the
3100 record.
3101
3102 .. attribute:: args
3103
3104 Tuple of arguments to be used in formatting :attr:`msg`.
3105
3106 .. attribute:: exc_info
3107
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003108 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003109 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003110
3111 .. attribute:: func
3112
3113 Name of the function of origin (i.e. in which the logging call was made).
3114
3115 .. attribute:: lineno
3116
3117 Line number in the source file of origin.
3118
3119 .. attribute:: lvl
3120
3121 Numeric logging level.
3122
3123 .. attribute:: message
3124
3125 Bound to the result of :meth:`getMessage` when
3126 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3127
3128 .. attribute:: msg
3129
3130 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3131 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3132
3133 .. attribute:: name
3134
3135 Name of the logger that emitted the record.
3136
3137 .. attribute:: pathname
3138
3139 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003140
Benjamin Petersone41251e2008-04-25 01:59:09 +00003141 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003142
Benjamin Petersone41251e2008-04-25 01:59:09 +00003143 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003144 user-supplied arguments with the message. If the user-supplied message
3145 argument to the logging call is not a string, :func:`str` is called on it to
3146 convert it to a string. This allows use of user-defined classes as
3147 messages, whose ``__str__`` method can return the actual format string to
3148 be used.
3149
3150 .. versionchanged:: 2.5
3151 *func* was added.
Benjamin Petersone41251e2008-04-25 01:59:09 +00003152
Vinay Sajipd31f3632010-06-29 15:31:15 +00003153.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003154
Christian Heimes04c420f2008-01-18 18:40:46 +00003155LoggerAdapter Objects
3156---------------------
3157
Christian Heimes04c420f2008-01-18 18:40:46 +00003158:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003159information into logging calls. For a usage example , see the section on
3160`adding contextual information to your logging output`__.
3161
3162__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00003163
3164.. class:: LoggerAdapter(logger, extra)
3165
3166 Returns an instance of :class:`LoggerAdapter` initialized with an
3167 underlying :class:`Logger` instance and a dict-like object.
3168
Benjamin Petersone41251e2008-04-25 01:59:09 +00003169 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003170
Benjamin Petersone41251e2008-04-25 01:59:09 +00003171 Modifies the message and/or keyword arguments passed to a logging call in
3172 order to insert contextual information. This implementation takes the object
3173 passed as *extra* to the constructor and adds it to *kwargs* using key
3174 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3175 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003176
Vinay Sajipc84f0162010-09-21 11:25:39 +00003177In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003178methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003179:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3180:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3181:meth:`hasHandlers`. These methods have the same signatures as their
3182counterparts in :class:`Logger`, so you can use the two types of instances
3183interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003184
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003185.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003186 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3187 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3188 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003189
Georg Brandl116aa622007-08-15 14:28:22 +00003190
3191Thread Safety
3192-------------
3193
3194The logging module is intended to be thread-safe without any special work
3195needing to be done by its clients. It achieves this though using threading
3196locks; there is one lock to serialize access to the module's shared data, and
3197each handler also creates a lock to serialize access to its underlying I/O.
3198
Benjamin Petersond23f8222009-04-05 19:13:16 +00003199If you are implementing asynchronous signal handlers using the :mod:`signal`
3200module, you may not be able to use logging from within such handlers. This is
3201because lock implementations in the :mod:`threading` module are not always
3202re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003203
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003204
3205Integration with the warnings module
3206------------------------------------
3207
3208The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3209with the :mod:`warnings` module.
3210
3211.. function:: captureWarnings(capture)
3212
3213 This function is used to turn the capture of warnings by logging on and
3214 off.
3215
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003216 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3217 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003218 formatted using :func:`warnings.formatwarning` and the resulting string
3219 logged to a logger named "py.warnings" with a severity of `WARNING`.
3220
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003221 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003222 will stop, and warnings will be redirected to their original destinations
3223 (i.e. those in effect before `captureWarnings(True)` was called).
3224
3225
Georg Brandl116aa622007-08-15 14:28:22 +00003226Configuration
3227-------------
3228
3229
3230.. _logging-config-api:
3231
3232Configuration functions
3233^^^^^^^^^^^^^^^^^^^^^^^
3234
Georg Brandl116aa622007-08-15 14:28:22 +00003235The following functions configure the logging module. They are located in the
3236:mod:`logging.config` module. Their use is optional --- you can configure the
3237logging module using these functions or by making calls to the main API (defined
3238in :mod:`logging` itself) and defining handlers which are declared either in
3239:mod:`logging` or :mod:`logging.handlers`.
3240
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003241.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003242
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003243 Takes the logging configuration from a dictionary. The contents of
3244 this dictionary are described in :ref:`logging-config-dictschema`
3245 below.
3246
3247 If an error is encountered during configuration, this function will
3248 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3249 or :exc:`ImportError` with a suitably descriptive message. The
3250 following is a (possibly incomplete) list of conditions which will
3251 raise an error:
3252
3253 * A ``level`` which is not a string or which is a string not
3254 corresponding to an actual logging level.
3255 * A ``propagate`` value which is not a boolean.
3256 * An id which does not have a corresponding destination.
3257 * A non-existent handler id found during an incremental call.
3258 * An invalid logger name.
3259 * Inability to resolve to an internal or external object.
3260
3261 Parsing is performed by the :class:`DictConfigurator` class, whose
3262 constructor is passed the dictionary used for configuration, and
3263 has a :meth:`configure` method. The :mod:`logging.config` module
3264 has a callable attribute :attr:`dictConfigClass`
3265 which is initially set to :class:`DictConfigurator`.
3266 You can replace the value of :attr:`dictConfigClass` with a
3267 suitable implementation of your own.
3268
3269 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3270 the specified dictionary, and then calls the :meth:`configure` method on
3271 the returned object to put the configuration into effect::
3272
3273 def dictConfig(config):
3274 dictConfigClass(config).configure()
3275
3276 For example, a subclass of :class:`DictConfigurator` could call
3277 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3278 set up custom prefixes which would be usable in the subsequent
3279 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3280 this new subclass, and then :func:`dictConfig` could be called exactly as
3281 in the default, uncustomized state.
3282
3283.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003284
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003285 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003286 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003287 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003288 configurations (if the developer provides a mechanism to present the choices
3289 and load the chosen configuration). Defaults to be passed to the ConfigParser
3290 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003291
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003292
3293.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003294
3295 Starts up a socket server on the specified port, and listens for new
3296 configurations. If no port is specified, the module's default
3297 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3298 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3299 :class:`Thread` instance on which you can call :meth:`start` to start the
3300 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003301 call :func:`stopListening`.
3302
3303 To send a configuration to the socket, read in the configuration file and
3304 send it to the socket as a string of bytes preceded by a four-byte length
3305 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003306
3307
3308.. function:: stopListening()
3309
Christian Heimes8b0facf2007-12-04 19:30:01 +00003310 Stops the listening server which was created with a call to :func:`listen`.
3311 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003312 :func:`listen`.
3313
3314
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003315.. _logging-config-dictschema:
3316
3317Configuration dictionary schema
3318^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3319
3320Describing a logging configuration requires listing the various
3321objects to create and the connections between them; for example, you
3322may create a handler named "console" and then say that the logger
3323named "startup" will send its messages to the "console" handler.
3324These objects aren't limited to those provided by the :mod:`logging`
3325module because you might write your own formatter or handler class.
3326The parameters to these classes may also need to include external
3327objects such as ``sys.stderr``. The syntax for describing these
3328objects and connections is defined in :ref:`logging-config-dict-connections`
3329below.
3330
3331Dictionary Schema Details
3332"""""""""""""""""""""""""
3333
3334The dictionary passed to :func:`dictConfig` must contain the following
3335keys:
3336
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003337* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003338 version. The only valid value at present is 1, but having this key
3339 allows the schema to evolve while still preserving backwards
3340 compatibility.
3341
3342All other keys are optional, but if present they will be interpreted
3343as described below. In all cases below where a 'configuring dict' is
3344mentioned, it will be checked for the special ``'()'`` key to see if a
3345custom instantiation is required. If so, the mechanism described in
3346:ref:`logging-config-dict-userdef` below is used to create an instance;
3347otherwise, the context is used to determine what to instantiate.
3348
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003349* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003350 key is a formatter id and each value is a dict describing how to
3351 configure the corresponding Formatter instance.
3352
3353 The configuring dict is searched for keys ``format`` and ``datefmt``
3354 (with defaults of ``None``) and these are used to construct a
3355 :class:`logging.Formatter` instance.
3356
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003357* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003358 is a filter id and each value is a dict describing how to configure
3359 the corresponding Filter instance.
3360
3361 The configuring dict is searched for the key ``name`` (defaulting to the
3362 empty string) and this is used to construct a :class:`logging.Filter`
3363 instance.
3364
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003365* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003366 key is a handler id and each value is a dict describing how to
3367 configure the corresponding Handler instance.
3368
3369 The configuring dict is searched for the following keys:
3370
3371 * ``class`` (mandatory). This is the fully qualified name of the
3372 handler class.
3373
3374 * ``level`` (optional). The level of the handler.
3375
3376 * ``formatter`` (optional). The id of the formatter for this
3377 handler.
3378
3379 * ``filters`` (optional). A list of ids of the filters for this
3380 handler.
3381
3382 All *other* keys are passed through as keyword arguments to the
3383 handler's constructor. For example, given the snippet::
3384
3385 handlers:
3386 console:
3387 class : logging.StreamHandler
3388 formatter: brief
3389 level : INFO
3390 filters: [allow_foo]
3391 stream : ext://sys.stdout
3392 file:
3393 class : logging.handlers.RotatingFileHandler
3394 formatter: precise
3395 filename: logconfig.log
3396 maxBytes: 1024
3397 backupCount: 3
3398
3399 the handler with id ``console`` is instantiated as a
3400 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3401 stream. The handler with id ``file`` is instantiated as a
3402 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3403 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3404
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003405* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003406 is a logger name and each value is a dict describing how to
3407 configure the corresponding Logger instance.
3408
3409 The configuring dict is searched for the following keys:
3410
3411 * ``level`` (optional). The level of the logger.
3412
3413 * ``propagate`` (optional). The propagation setting of the logger.
3414
3415 * ``filters`` (optional). A list of ids of the filters for this
3416 logger.
3417
3418 * ``handlers`` (optional). A list of ids of the handlers for this
3419 logger.
3420
3421 The specified loggers will be configured according to the level,
3422 propagation, filters and handlers specified.
3423
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003424* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003425 Processing of the configuration will be as for any logger, except
3426 that the ``propagate`` setting will not be applicable.
3427
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003428* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003429 incremental to the existing configuration. This value defaults to
3430 ``False``, which means that the specified configuration replaces the
3431 existing configuration with the same semantics as used by the
3432 existing :func:`fileConfig` API.
3433
3434 If the specified value is ``True``, the configuration is processed
3435 as described in the section on :ref:`logging-config-dict-incremental`.
3436
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003437* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003438 disabled. This setting mirrors the parameter of the same name in
3439 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003440 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003441
3442.. _logging-config-dict-incremental:
3443
3444Incremental Configuration
3445"""""""""""""""""""""""""
3446
3447It is difficult to provide complete flexibility for incremental
3448configuration. For example, because objects such as filters
3449and formatters are anonymous, once a configuration is set up, it is
3450not possible to refer to such anonymous objects when augmenting a
3451configuration.
3452
3453Furthermore, there is not a compelling case for arbitrarily altering
3454the object graph of loggers, handlers, filters, formatters at
3455run-time, once a configuration is set up; the verbosity of loggers and
3456handlers can be controlled just by setting levels (and, in the case of
3457loggers, propagation flags). Changing the object graph arbitrarily in
3458a safe way is problematic in a multi-threaded environment; while not
3459impossible, the benefits are not worth the complexity it adds to the
3460implementation.
3461
3462Thus, when the ``incremental`` key of a configuration dict is present
3463and is ``True``, the system will completely ignore any ``formatters`` and
3464``filters`` entries, and process only the ``level``
3465settings in the ``handlers`` entries, and the ``level`` and
3466``propagate`` settings in the ``loggers`` and ``root`` entries.
3467
3468Using a value in the configuration dict lets configurations to be sent
3469over the wire as pickled dicts to a socket listener. Thus, the logging
3470verbosity of a long-running application can be altered over time with
3471no need to stop and restart the application.
3472
3473.. _logging-config-dict-connections:
3474
3475Object connections
3476""""""""""""""""""
3477
3478The schema describes a set of logging objects - loggers,
3479handlers, formatters, filters - which are connected to each other in
3480an object graph. Thus, the schema needs to represent connections
3481between the objects. For example, say that, once configured, a
3482particular logger has attached to it a particular handler. For the
3483purposes of this discussion, we can say that the logger represents the
3484source, and the handler the destination, of a connection between the
3485two. Of course in the configured objects this is represented by the
3486logger holding a reference to the handler. In the configuration dict,
3487this is done by giving each destination object an id which identifies
3488it unambiguously, and then using the id in the source object's
3489configuration to indicate that a connection exists between the source
3490and the destination object with that id.
3491
3492So, for example, consider the following YAML snippet::
3493
3494 formatters:
3495 brief:
3496 # configuration for formatter with id 'brief' goes here
3497 precise:
3498 # configuration for formatter with id 'precise' goes here
3499 handlers:
3500 h1: #This is an id
3501 # configuration of handler with id 'h1' goes here
3502 formatter: brief
3503 h2: #This is another id
3504 # configuration of handler with id 'h2' goes here
3505 formatter: precise
3506 loggers:
3507 foo.bar.baz:
3508 # other configuration for logger 'foo.bar.baz'
3509 handlers: [h1, h2]
3510
3511(Note: YAML used here because it's a little more readable than the
3512equivalent Python source form for the dictionary.)
3513
3514The ids for loggers are the logger names which would be used
3515programmatically to obtain a reference to those loggers, e.g.
3516``foo.bar.baz``. The ids for Formatters and Filters can be any string
3517value (such as ``brief``, ``precise`` above) and they are transient,
3518in that they are only meaningful for processing the configuration
3519dictionary and used to determine connections between objects, and are
3520not persisted anywhere when the configuration call is complete.
3521
3522The above snippet indicates that logger named ``foo.bar.baz`` should
3523have two handlers attached to it, which are described by the handler
3524ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3525``brief``, and the formatter for ``h2`` is that described by id
3526``precise``.
3527
3528
3529.. _logging-config-dict-userdef:
3530
3531User-defined objects
3532""""""""""""""""""""
3533
3534The schema supports user-defined objects for handlers, filters and
3535formatters. (Loggers do not need to have different types for
3536different instances, so there is no support in this configuration
3537schema for user-defined logger classes.)
3538
3539Objects to be configured are described by dictionaries
3540which detail their configuration. In some places, the logging system
3541will be able to infer from the context how an object is to be
3542instantiated, but when a user-defined object is to be instantiated,
3543the system will not know how to do this. In order to provide complete
3544flexibility for user-defined object instantiation, the user needs
3545to provide a 'factory' - a callable which is called with a
3546configuration dictionary and which returns the instantiated object.
3547This is signalled by an absolute import path to the factory being
3548made available under the special key ``'()'``. Here's a concrete
3549example::
3550
3551 formatters:
3552 brief:
3553 format: '%(message)s'
3554 default:
3555 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3556 datefmt: '%Y-%m-%d %H:%M:%S'
3557 custom:
3558 (): my.package.customFormatterFactory
3559 bar: baz
3560 spam: 99.9
3561 answer: 42
3562
3563The above YAML snippet defines three formatters. The first, with id
3564``brief``, is a standard :class:`logging.Formatter` instance with the
3565specified format string. The second, with id ``default``, has a
3566longer format and also defines the time format explicitly, and will
3567result in a :class:`logging.Formatter` initialized with those two format
3568strings. Shown in Python source form, the ``brief`` and ``default``
3569formatters have configuration sub-dictionaries::
3570
3571 {
3572 'format' : '%(message)s'
3573 }
3574
3575and::
3576
3577 {
3578 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3579 'datefmt' : '%Y-%m-%d %H:%M:%S'
3580 }
3581
3582respectively, and as these dictionaries do not contain the special key
3583``'()'``, the instantiation is inferred from the context: as a result,
3584standard :class:`logging.Formatter` instances are created. The
3585configuration sub-dictionary for the third formatter, with id
3586``custom``, is::
3587
3588 {
3589 '()' : 'my.package.customFormatterFactory',
3590 'bar' : 'baz',
3591 'spam' : 99.9,
3592 'answer' : 42
3593 }
3594
3595and this contains the special key ``'()'``, which means that
3596user-defined instantiation is wanted. In this case, the specified
3597factory callable will be used. If it is an actual callable it will be
3598used directly - otherwise, if you specify a string (as in the example)
3599the actual callable will be located using normal import mechanisms.
3600The callable will be called with the **remaining** items in the
3601configuration sub-dictionary as keyword arguments. In the above
3602example, the formatter with id ``custom`` will be assumed to be
3603returned by the call::
3604
3605 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3606
3607The key ``'()'`` has been used as the special key because it is not a
3608valid keyword parameter name, and so will not clash with the names of
3609the keyword arguments used in the call. The ``'()'`` also serves as a
3610mnemonic that the corresponding value is a callable.
3611
3612
3613.. _logging-config-dict-externalobj:
3614
3615Access to external objects
3616""""""""""""""""""""""""""
3617
3618There are times where a configuration needs to refer to objects
3619external to the configuration, for example ``sys.stderr``. If the
3620configuration dict is constructed using Python code, this is
3621straightforward, but a problem arises when the configuration is
3622provided via a text file (e.g. JSON, YAML). In a text file, there is
3623no standard way to distinguish ``sys.stderr`` from the literal string
3624``'sys.stderr'``. To facilitate this distinction, the configuration
3625system looks for certain special prefixes in string values and
3626treat them specially. For example, if the literal string
3627``'ext://sys.stderr'`` is provided as a value in the configuration,
3628then the ``ext://`` will be stripped off and the remainder of the
3629value processed using normal import mechanisms.
3630
3631The handling of such prefixes is done in a way analogous to protocol
3632handling: there is a generic mechanism to look for prefixes which
3633match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3634whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3635in a prefix-dependent manner and the result of the processing replaces
3636the string value. If the prefix is not recognised, then the string
3637value will be left as-is.
3638
3639
3640.. _logging-config-dict-internalobj:
3641
3642Access to internal objects
3643""""""""""""""""""""""""""
3644
3645As well as external objects, there is sometimes also a need to refer
3646to objects in the configuration. This will be done implicitly by the
3647configuration system for things that it knows about. For example, the
3648string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3649automatically be converted to the value ``logging.DEBUG``, and the
3650``handlers``, ``filters`` and ``formatter`` entries will take an
3651object id and resolve to the appropriate destination object.
3652
3653However, a more generic mechanism is needed for user-defined
3654objects which are not known to the :mod:`logging` module. For
3655example, consider :class:`logging.handlers.MemoryHandler`, which takes
3656a ``target`` argument which is another handler to delegate to. Since
3657the system already knows about this class, then in the configuration,
3658the given ``target`` just needs to be the object id of the relevant
3659target handler, and the system will resolve to the handler from the
3660id. If, however, a user defines a ``my.package.MyHandler`` which has
3661an ``alternate`` handler, the configuration system would not know that
3662the ``alternate`` referred to a handler. To cater for this, a generic
3663resolution system allows the user to specify::
3664
3665 handlers:
3666 file:
3667 # configuration of file handler goes here
3668
3669 custom:
3670 (): my.package.MyHandler
3671 alternate: cfg://handlers.file
3672
3673The literal string ``'cfg://handlers.file'`` will be resolved in an
3674analogous way to strings with the ``ext://`` prefix, but looking
3675in the configuration itself rather than the import namespace. The
3676mechanism allows access by dot or by index, in a similar way to
3677that provided by ``str.format``. Thus, given the following snippet::
3678
3679 handlers:
3680 email:
3681 class: logging.handlers.SMTPHandler
3682 mailhost: localhost
3683 fromaddr: my_app@domain.tld
3684 toaddrs:
3685 - support_team@domain.tld
3686 - dev_team@domain.tld
3687 subject: Houston, we have a problem.
3688
3689in the configuration, the string ``'cfg://handlers'`` would resolve to
3690the dict with key ``handlers``, the string ``'cfg://handlers.email``
3691would resolve to the dict with key ``email`` in the ``handlers`` dict,
3692and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3693resolve to ``'dev_team.domain.tld'`` and the string
3694``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3695``'support_team@domain.tld'``. The ``subject`` value could be accessed
3696using either ``'cfg://handlers.email.subject'`` or, equivalently,
3697``'cfg://handlers.email[subject]'``. The latter form only needs to be
3698used if the key contains spaces or non-alphanumeric characters. If an
3699index value consists only of decimal digits, access will be attempted
3700using the corresponding integer value, falling back to the string
3701value if needed.
3702
3703Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3704resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3705If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3706the system will attempt to retrieve the value from
3707``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3708to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3709fails.
3710
Georg Brandl116aa622007-08-15 14:28:22 +00003711.. _logging-config-fileformat:
3712
3713Configuration file format
3714^^^^^^^^^^^^^^^^^^^^^^^^^
3715
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003716The configuration file format understood by :func:`fileConfig` is based on
3717:mod:`configparser` functionality. The file must contain sections called
3718``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3719entities of each type which are defined in the file. For each such entity, there
3720is a separate section which identifies how that entity is configured. Thus, for
3721a logger named ``log01`` in the ``[loggers]`` section, the relevant
3722configuration details are held in a section ``[logger_log01]``. Similarly, a
3723handler called ``hand01`` in the ``[handlers]`` section will have its
3724configuration held in a section called ``[handler_hand01]``, while a formatter
3725called ``form01`` in the ``[formatters]`` section will have its configuration
3726specified in a section called ``[formatter_form01]``. The root logger
3727configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003728
3729Examples of these sections in the file are given below. ::
3730
3731 [loggers]
3732 keys=root,log02,log03,log04,log05,log06,log07
3733
3734 [handlers]
3735 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3736
3737 [formatters]
3738 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3739
3740The root logger must specify a level and a list of handlers. An example of a
3741root logger section is given below. ::
3742
3743 [logger_root]
3744 level=NOTSET
3745 handlers=hand01
3746
3747The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3748``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3749logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3750package's namespace.
3751
3752The ``handlers`` entry is a comma-separated list of handler names, which must
3753appear in the ``[handlers]`` section. These names must appear in the
3754``[handlers]`` section and have corresponding sections in the configuration
3755file.
3756
3757For loggers other than the root logger, some additional information is required.
3758This is illustrated by the following example. ::
3759
3760 [logger_parser]
3761 level=DEBUG
3762 handlers=hand01
3763 propagate=1
3764 qualname=compiler.parser
3765
3766The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3767except that if a non-root logger's level is specified as ``NOTSET``, the system
3768consults loggers higher up the hierarchy to determine the effective level of the
3769logger. The ``propagate`` entry is set to 1 to indicate that messages must
3770propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3771indicate that messages are **not** propagated to handlers up the hierarchy. The
3772``qualname`` entry is the hierarchical channel name of the logger, that is to
3773say the name used by the application to get the logger.
3774
3775Sections which specify handler configuration are exemplified by the following.
3776::
3777
3778 [handler_hand01]
3779 class=StreamHandler
3780 level=NOTSET
3781 formatter=form01
3782 args=(sys.stdout,)
3783
3784The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3785in the ``logging`` package's namespace). The ``level`` is interpreted as for
3786loggers, and ``NOTSET`` is taken to mean "log everything".
3787
3788The ``formatter`` entry indicates the key name of the formatter for this
3789handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3790If a name is specified, it must appear in the ``[formatters]`` section and have
3791a corresponding section in the configuration file.
3792
3793The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3794package's namespace, is the list of arguments to the constructor for the handler
3795class. Refer to the constructors for the relevant handlers, or to the examples
3796below, to see how typical entries are constructed. ::
3797
3798 [handler_hand02]
3799 class=FileHandler
3800 level=DEBUG
3801 formatter=form02
3802 args=('python.log', 'w')
3803
3804 [handler_hand03]
3805 class=handlers.SocketHandler
3806 level=INFO
3807 formatter=form03
3808 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3809
3810 [handler_hand04]
3811 class=handlers.DatagramHandler
3812 level=WARN
3813 formatter=form04
3814 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3815
3816 [handler_hand05]
3817 class=handlers.SysLogHandler
3818 level=ERROR
3819 formatter=form05
3820 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3821
3822 [handler_hand06]
3823 class=handlers.NTEventLogHandler
3824 level=CRITICAL
3825 formatter=form06
3826 args=('Python Application', '', 'Application')
3827
3828 [handler_hand07]
3829 class=handlers.SMTPHandler
3830 level=WARN
3831 formatter=form07
3832 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3833
3834 [handler_hand08]
3835 class=handlers.MemoryHandler
3836 level=NOTSET
3837 formatter=form08
3838 target=
3839 args=(10, ERROR)
3840
3841 [handler_hand09]
3842 class=handlers.HTTPHandler
3843 level=NOTSET
3844 formatter=form09
3845 args=('localhost:9022', '/log', 'GET')
3846
3847Sections which specify formatter configuration are typified by the following. ::
3848
3849 [formatter_form01]
3850 format=F1 %(asctime)s %(levelname)s %(message)s
3851 datefmt=
3852 class=logging.Formatter
3853
3854The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003855the :func:`strftime`\ -compatible date/time format string. If empty, the
3856package substitutes ISO8601 format date/times, which is almost equivalent to
3857specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3858also specifies milliseconds, which are appended to the result of using the above
3859format string, with a comma separator. An example time in ISO8601 format is
3860``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00003861
3862The ``class`` entry is optional. It indicates the name of the formatter's class
3863(as a dotted module and class name.) This option is useful for instantiating a
3864:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3865exception tracebacks in an expanded or condensed format.
3866
Christian Heimes8b0facf2007-12-04 19:30:01 +00003867
3868Configuration server example
3869^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3870
3871Here is an example of a module using the logging configuration server::
3872
3873 import logging
3874 import logging.config
3875 import time
3876 import os
3877
3878 # read initial config file
3879 logging.config.fileConfig("logging.conf")
3880
3881 # create and start listener on port 9999
3882 t = logging.config.listen(9999)
3883 t.start()
3884
3885 logger = logging.getLogger("simpleExample")
3886
3887 try:
3888 # loop through logging calls to see the difference
3889 # new configurations make, until Ctrl+C is pressed
3890 while True:
3891 logger.debug("debug message")
3892 logger.info("info message")
3893 logger.warn("warn message")
3894 logger.error("error message")
3895 logger.critical("critical message")
3896 time.sleep(5)
3897 except KeyboardInterrupt:
3898 # cleanup
3899 logging.config.stopListening()
3900 t.join()
3901
3902And here is a script that takes a filename and sends that file to the server,
3903properly preceded with the binary-encoded length, as the new logging
3904configuration::
3905
3906 #!/usr/bin/env python
3907 import socket, sys, struct
3908
3909 data_to_send = open(sys.argv[1], "r").read()
3910
3911 HOST = 'localhost'
3912 PORT = 9999
3913 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00003914 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003915 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00003916 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003917 s.send(struct.pack(">L", len(data_to_send)))
3918 s.send(data_to_send)
3919 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00003920 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003921
3922
3923More examples
3924-------------
3925
3926Multiple handlers and formatters
3927^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3928
3929Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3930or maximum quota for the number of handlers you may add. Sometimes it will be
3931beneficial for an application to log all messages of all severities to a text
3932file while simultaneously logging errors or above to the console. To set this
3933up, simply configure the appropriate handlers. The logging calls in the
3934application code will remain unchanged. Here is a slight modification to the
3935previous simple module-based configuration example::
3936
3937 import logging
3938
3939 logger = logging.getLogger("simple_example")
3940 logger.setLevel(logging.DEBUG)
3941 # create file handler which logs even debug messages
3942 fh = logging.FileHandler("spam.log")
3943 fh.setLevel(logging.DEBUG)
3944 # create console handler with a higher log level
3945 ch = logging.StreamHandler()
3946 ch.setLevel(logging.ERROR)
3947 # create formatter and add it to the handlers
3948 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3949 ch.setFormatter(formatter)
3950 fh.setFormatter(formatter)
3951 # add the handlers to logger
3952 logger.addHandler(ch)
3953 logger.addHandler(fh)
3954
3955 # "application" code
3956 logger.debug("debug message")
3957 logger.info("info message")
3958 logger.warn("warn message")
3959 logger.error("error message")
3960 logger.critical("critical message")
3961
3962Notice that the "application" code does not care about multiple handlers. All
3963that changed was the addition and configuration of a new handler named *fh*.
3964
3965The ability to create new handlers with higher- or lower-severity filters can be
3966very helpful when writing and testing an application. Instead of using many
3967``print`` statements for debugging, use ``logger.debug``: Unlike the print
3968statements, which you will have to delete or comment out later, the logger.debug
3969statements can remain intact in the source code and remain dormant until you
3970need them again. At that time, the only change that needs to happen is to
3971modify the severity level of the logger and/or handler to debug.
3972
3973
3974Using logging in multiple modules
3975^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3976
3977It was mentioned above that multiple calls to
3978``logging.getLogger('someLogger')`` return a reference to the same logger
3979object. This is true not only within the same module, but also across modules
3980as long as it is in the same Python interpreter process. It is true for
3981references to the same object; additionally, application code can define and
3982configure a parent logger in one module and create (but not configure) a child
3983logger in a separate module, and all logger calls to the child will pass up to
3984the parent. Here is a main module::
3985
3986 import logging
3987 import auxiliary_module
3988
3989 # create logger with "spam_application"
3990 logger = logging.getLogger("spam_application")
3991 logger.setLevel(logging.DEBUG)
3992 # create file handler which logs even debug messages
3993 fh = logging.FileHandler("spam.log")
3994 fh.setLevel(logging.DEBUG)
3995 # create console handler with a higher log level
3996 ch = logging.StreamHandler()
3997 ch.setLevel(logging.ERROR)
3998 # create formatter and add it to the handlers
3999 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4000 fh.setFormatter(formatter)
4001 ch.setFormatter(formatter)
4002 # add the handlers to the logger
4003 logger.addHandler(fh)
4004 logger.addHandler(ch)
4005
4006 logger.info("creating an instance of auxiliary_module.Auxiliary")
4007 a = auxiliary_module.Auxiliary()
4008 logger.info("created an instance of auxiliary_module.Auxiliary")
4009 logger.info("calling auxiliary_module.Auxiliary.do_something")
4010 a.do_something()
4011 logger.info("finished auxiliary_module.Auxiliary.do_something")
4012 logger.info("calling auxiliary_module.some_function()")
4013 auxiliary_module.some_function()
4014 logger.info("done with auxiliary_module.some_function()")
4015
4016Here is the auxiliary module::
4017
4018 import logging
4019
4020 # create logger
4021 module_logger = logging.getLogger("spam_application.auxiliary")
4022
4023 class Auxiliary:
4024 def __init__(self):
4025 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4026 self.logger.info("creating an instance of Auxiliary")
4027 def do_something(self):
4028 self.logger.info("doing something")
4029 a = 1 + 1
4030 self.logger.info("done doing something")
4031
4032 def some_function():
4033 module_logger.info("received a call to \"some_function\"")
4034
4035The output looks like this::
4036
Christian Heimes043d6f62008-01-07 17:19:16 +00004037 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004038 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004039 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004040 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004041 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004042 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004043 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004044 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004045 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004046 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004047 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004048 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004049 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004050 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004051 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004052 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004053 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004054 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004055 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004056 done with auxiliary_module.some_function()
4057