blob: e7af4e35656a509647c1625b959462c6a12c5d97 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
17Logging is performed by calling methods on instances of the :class:`Logger`
18class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +000019conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +000020separators. For example, a logger named "scan" is the parent of loggers
21"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
22and indicate the area of an application in which a logged message originates.
23
24Logged messages also have levels of importance associated with them. The default
25levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
26:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
27importance of a logged message by calling an appropriate method of
28:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
29:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
30constrained to use these levels: you can specify your own and use a more general
31:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
32
Christian Heimes8b0facf2007-12-04 19:30:01 +000033
34Logging tutorial
35----------------
36
37The key benefit of having the logging API provided by a standard library module
38is that all Python modules can participate in logging, so your application log
39can include messages from third-party modules.
40
41It is, of course, possible to log messages with different verbosity levels or to
42different destinations. Support for writing log messages to files, HTTP
43GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Christian Heimesc3f30c42008-02-22 16:37:40 +000044mechanisms are all supported by the standard module. You can also create your
Christian Heimes8b0facf2007-12-04 19:30:01 +000045own log destination class if you have special requirements not met by any of the
46built-in classes.
47
48Simple examples
49^^^^^^^^^^^^^^^
50
51.. sectionauthor:: Doug Hellmann
52.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
53
54Most applications are probably going to want to log to a file, so let's start
55with that case. Using the :func:`basicConfig` function, we can set up the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056default handler so that debug messages are written to a file (in the example,
57we assume that you have the appropriate permissions to create a file called
58*example.log* in the current directory)::
Christian Heimes8b0facf2007-12-04 19:30:01 +000059
60 import logging
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000061 LOG_FILENAME = 'example.log'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Christian Heimes8b0facf2007-12-04 19:30:01 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smith5c01a8d2009-06-04 18:20:51 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Christian Heimes8b0facf2007-12-04 19:30:01 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000080 LOG_FILENAME = 'logging_rotatingfile_example.out'
Christian Heimes8b0facf2007-12-04 19:30:01 +000081
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
Georg Brandlf6945182008-02-01 11:56:49 +0000100 print(filename)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000105 logging_rotatingfile_example.out
106 logging_rotatingfile_example.out.1
107 logging_rotatingfile_example.out.2
108 logging_rotatingfile_example.out.3
109 logging_rotatingfile_example.out.4
110 logging_rotatingfile_example.out.5
Christian Heimes8b0facf2007-12-04 19:30:01 +0000111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112The most current file is always :file:`logging_rotatingfile_example.out`,
Christian Heimes8b0facf2007-12-04 19:30:01 +0000113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smith5c01a8d2009-06-04 18:20:51 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipb6d065f2009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Christian Heimesdcca98d2008-02-25 13:19:43 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000249name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000270requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
294defines the interface that all handlers should have and establishes some
295default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000303instantiate formatter classes, although you could likely subclass the formatter
304if your application needs special behavior. The constructor takes two optional
305arguments: a message format string and a date format string. If there is no
306message format string, the default is to use the raw message. If there is no
307date format string, the default date format is::
308
309 %Y-%m-%d %H:%M:%S
310
311with the milliseconds tacked on at the end.
312
313The message format string uses ``%(<dictionary key>)s`` styled string
314substitution; the possible keys are documented in :ref:`formatter-objects`.
315
316The following message format string will log the time in a human-readable
317format, the severity of the message, and the contents of the message, in that
318order::
319
320 "%(asctime)s - %(levelname)s - %(message)s"
321
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000322Formatters use a user-configurable function to convert the creation time of a
323record to a tuple. By default, :func:`time.localtime` is used; to change this
324for a particular formatter instance, set the ``converter`` attribute of the
325instance to a function with the same signature as :func:`time.localtime` or
326:func:`time.gmtime`. To change it for all formatters, for example if you want
327all logging times to be shown in GMT, set the ``converter`` attribute in the
328Formatter class (to ``time.gmtime`` for GMT display).
329
Christian Heimes8b0facf2007-12-04 19:30:01 +0000330
331Configuring Logging
332^^^^^^^^^^^^^^^^^^^
333
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000334Programmers can configure logging in three ways:
335
3361. Creating loggers, handlers, and formatters explicitly using Python
337 code that calls the configuration methods listed above.
3382. Creating a logging config file and reading it using the :func:`fileConfig`
339 function.
3403. Creating a dictionary of configuration information and passing it
341 to the :func:`dictConfig` function.
342
343The following example configures a very simple logger, a console
344handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000345
346 import logging
347
348 # create logger
349 logger = logging.getLogger("simple_example")
350 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000351
Christian Heimes8b0facf2007-12-04 19:30:01 +0000352 # create console handler and set level to debug
353 ch = logging.StreamHandler()
354 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000355
Christian Heimes8b0facf2007-12-04 19:30:01 +0000356 # create formatter
357 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000358
Christian Heimes8b0facf2007-12-04 19:30:01 +0000359 # add formatter to ch
360 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000361
Christian Heimes8b0facf2007-12-04 19:30:01 +0000362 # add ch to logger
363 logger.addHandler(ch)
364
365 # "application" code
366 logger.debug("debug message")
367 logger.info("info message")
368 logger.warn("warn message")
369 logger.error("error message")
370 logger.critical("critical message")
371
372Running this module from the command line produces the following output::
373
374 $ python simple_logging_module.py
375 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
376 2005-03-19 15:10:26,620 - simple_example - INFO - info message
377 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
378 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
379 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
380
381The following Python module creates a logger, handler, and formatter nearly
382identical to those in the example listed above, with the only difference being
383the names of the objects::
384
385 import logging
386 import logging.config
387
388 logging.config.fileConfig("logging.conf")
389
390 # create logger
391 logger = logging.getLogger("simpleExample")
392
393 # "application" code
394 logger.debug("debug message")
395 logger.info("info message")
396 logger.warn("warn message")
397 logger.error("error message")
398 logger.critical("critical message")
399
400Here is the logging.conf file::
401
402 [loggers]
403 keys=root,simpleExample
404
405 [handlers]
406 keys=consoleHandler
407
408 [formatters]
409 keys=simpleFormatter
410
411 [logger_root]
412 level=DEBUG
413 handlers=consoleHandler
414
415 [logger_simpleExample]
416 level=DEBUG
417 handlers=consoleHandler
418 qualname=simpleExample
419 propagate=0
420
421 [handler_consoleHandler]
422 class=StreamHandler
423 level=DEBUG
424 formatter=simpleFormatter
425 args=(sys.stdout,)
426
427 [formatter_simpleFormatter]
428 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
429 datefmt=
430
431The output is nearly identical to that of the non-config-file-based example::
432
433 $ python simple_logging_config.py
434 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
435 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
436 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
437 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
438 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
439
440You can see that the config file approach has a few advantages over the Python
441code approach, mainly separation of configuration and code and the ability of
442noncoders to easily modify the logging properties.
443
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000444Note that the class names referenced in config files need to be either relative
445to the logging module, or absolute values which can be resolved using normal
446import mechanisms. Thus, you could use either `handlers.WatchedFileHandler`
447(relative to the logging module) or `mypackage.mymodule.MyHandler` (for a
448class defined in package `mypackage` and module `mymodule`, where `mypackage`
449is available on the Python import path).
450
Benjamin Peterson56894b52010-06-28 00:16:12 +0000451In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000452dictionaries to hold configuration information. This provides a superset of the
453functionality of the config-file-based approach outlined above, and is the
454recommended configuration method for new applications and deployments. Because
455a Python dictionary is used to hold configuration information, and since you
456can populate that dictionary using different means, you have more options for
457configuration. For example, you can use a configuration file in JSON format,
458or, if you have access to YAML processing functionality, a file in YAML
459format, to populate the configuration dictionary. Or, of course, you can
460construct the dictionary in Python code, receive it in pickled form over a
461socket, or use whatever approach makes sense for your application.
462
463Here's an example of the same configuration as above, in YAML format for
464the new dictionary-based approach::
465
466 version: 1
467 formatters:
468 simple:
469 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
470 handlers:
471 console:
472 class: logging.StreamHandler
473 level: DEBUG
474 formatter: simple
475 stream: ext://sys.stdout
476 loggers:
477 simpleExample:
478 level: DEBUG
479 handlers: [console]
480 propagate: no
481 root:
482 level: DEBUG
483 handlers: [console]
484
485For more information about logging using a dictionary, see
486:ref:`logging-config-api`.
487
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000488.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000489
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000490Configuring Logging for a Library
491^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
492
493When developing a library which uses logging, some consideration needs to be
494given to its configuration. If the using application does not use logging, and
495library code makes logging calls, then a one-off message "No handlers could be
496found for logger X.Y.Z" is printed to the console. This message is intended
497to catch mistakes in logging configuration, but will confuse an application
498developer who is not aware of logging by the library.
499
500In addition to documenting how a library uses logging, a good way to configure
501library logging so that it does not cause a spurious message is to add a
502handler which does nothing. This avoids the message being printed, since a
503handler will be found: it just doesn't produce any output. If the library user
504configures logging for application use, presumably that configuration will add
505some handlers, and if levels are suitably configured then logging calls made
506in library code will send output to those handlers, as normal.
507
508A do-nothing handler can be simply defined as follows::
509
510 import logging
511
512 class NullHandler(logging.Handler):
513 def emit(self, record):
514 pass
515
516An instance of this handler should be added to the top-level logger of the
517logging namespace used by the library. If all logging by a library *foo* is
518done using loggers with names matching "foo.x.y", then the code::
519
520 import logging
521
522 h = NullHandler()
523 logging.getLogger("foo").addHandler(h)
524
525should have the desired effect. If an organisation produces a number of
526libraries, then the logger name specified can be "orgname.foo" rather than
527just "foo".
528
Georg Brandlf9734072008-12-07 15:30:06 +0000529.. versionadded:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +0000530 The :class:`NullHandler` class was not present in previous versions, but is
531 now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000532
533
Christian Heimes8b0facf2007-12-04 19:30:01 +0000534
535Logging Levels
536--------------
537
Georg Brandl116aa622007-08-15 14:28:22 +0000538The numeric values of logging levels are given in the following table. These are
539primarily of interest if you want to define your own levels, and need them to
540have specific values relative to the predefined levels. If you define a level
541with the same numeric value, it overwrites the predefined value; the predefined
542name is lost.
543
544+--------------+---------------+
545| Level | Numeric value |
546+==============+===============+
547| ``CRITICAL`` | 50 |
548+--------------+---------------+
549| ``ERROR`` | 40 |
550+--------------+---------------+
551| ``WARNING`` | 30 |
552+--------------+---------------+
553| ``INFO`` | 20 |
554+--------------+---------------+
555| ``DEBUG`` | 10 |
556+--------------+---------------+
557| ``NOTSET`` | 0 |
558+--------------+---------------+
559
560Levels can also be associated with loggers, being set either by the developer or
561through loading a saved logging configuration. When a logging method is called
562on a logger, the logger compares its own level with the level associated with
563the method call. If the logger's level is higher than the method call's, no
564logging message is actually generated. This is the basic mechanism controlling
565the verbosity of logging output.
566
567Logging messages are encoded as instances of the :class:`LogRecord` class. When
568a logger decides to actually log an event, a :class:`LogRecord` instance is
569created from the logging message.
570
571Logging messages are subjected to a dispatch mechanism through the use of
572:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
573class. Handlers are responsible for ensuring that a logged message (in the form
574of a :class:`LogRecord`) ends up in a particular location (or set of locations)
575which is useful for the target audience for that message (such as end users,
576support desk staff, system administrators, developers). Handlers are passed
577:class:`LogRecord` instances intended for particular destinations. Each logger
578can have zero, one or more handlers associated with it (via the
579:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
580directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000581of the logger* are called to dispatch the message (unless the *propagate* flag
582for a logger is set to a false value, at which point the passing to ancestor
583handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585Just as for loggers, handlers can have levels associated with them. A handler's
586level acts as a filter in the same way as a logger's level does. If a handler
587decides to actually dispatch an event, the :meth:`emit` method is used to send
588the message to its destination. Most user-defined subclasses of :class:`Handler`
589will need to override this :meth:`emit`.
590
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000591Useful Handlers
592---------------
593
Georg Brandl116aa622007-08-15 14:28:22 +0000594In addition to the base :class:`Handler` class, many useful subclasses are
595provided:
596
Vinay Sajip121a1c42010-09-08 10:46:15 +0000597#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000598 objects).
599
Vinay Sajip121a1c42010-09-08 10:46:15 +0000600#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000602.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000603
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000604#. :class:`BaseRotatingHandler` is the base class for handlers that
605 rotate log files at a certain point. It is not meant to be instantiated
606 directly. Instead, use :class:`RotatingFileHandler` or
607 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000608
Vinay Sajip121a1c42010-09-08 10:46:15 +0000609#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000610 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000611
Vinay Sajip121a1c42010-09-08 10:46:15 +0000612#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000613 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Vinay Sajip121a1c42010-09-08 10:46:15 +0000615#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000616 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000617
Vinay Sajip121a1c42010-09-08 10:46:15 +0000618#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000619 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000620
Vinay Sajip121a1c42010-09-08 10:46:15 +0000621#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000622 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Vinay Sajip121a1c42010-09-08 10:46:15 +0000624#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000625 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000626
Vinay Sajip121a1c42010-09-08 10:46:15 +0000627#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000628 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000629
Vinay Sajip121a1c42010-09-08 10:46:15 +0000630#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000631 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Vinay Sajip121a1c42010-09-08 10:46:15 +0000633#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000634 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000636#. :class:`WatchedFileHandler` instances watch the file they are
637 logging to. If the file changes, it is closed and reopened using the file
638 name. This handler is only useful on Unix-like systems; Windows does not
639 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000640
Vinay Sajip121a1c42010-09-08 10:46:15 +0000641#. :class:`QueueHandler` instances send messages to a queue, such as
642 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
643
Vinay Sajip30bf1222009-01-10 19:23:34 +0000644.. currentmodule:: logging
645
Georg Brandlf9734072008-12-07 15:30:06 +0000646#. :class:`NullHandler` instances do nothing with error messages. They are used
647 by library developers who want to use logging, but want to avoid the "No
648 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000649 the library user has not configured logging. See :ref:`library-config` for
650 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000651
652.. versionadded:: 3.1
653
654The :class:`NullHandler` class was not present in previous versions.
655
Vinay Sajip121a1c42010-09-08 10:46:15 +0000656.. versionadded:: 3.2
657
658The :class:`QueueHandler` class was not present in previous versions.
659
Vinay Sajipa17775f2008-12-30 07:32:59 +0000660The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
661classes are defined in the core logging package. The other handlers are
662defined in a sub- module, :mod:`logging.handlers`. (There is also another
663sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665Logged messages are formatted for presentation through instances of the
666:class:`Formatter` class. They are initialized with a format string suitable for
667use with the % operator and a dictionary.
668
669For formatting multiple messages in a batch, instances of
670:class:`BufferingFormatter` can be used. In addition to the format string (which
671is applied to each message in the batch), there is provision for header and
672trailer format strings.
673
674When filtering based on logger level and/or handler level is not enough,
675instances of :class:`Filter` can be added to both :class:`Logger` and
676:class:`Handler` instances (through their :meth:`addFilter` method). Before
677deciding to process a message further, both loggers and handlers consult all
678their filters for permission. If any filter returns a false value, the message
679is not processed further.
680
681The basic :class:`Filter` functionality allows filtering by specific logger
682name. If this feature is used, messages sent to the named logger and its
683children are allowed through the filter, and all others dropped.
684
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000685Module-Level Functions
686----------------------
687
Georg Brandl116aa622007-08-15 14:28:22 +0000688In addition to the classes described above, there are a number of module- level
689functions.
690
691
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000692.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000694 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000695 logger which is the root logger of the hierarchy. If specified, the name is
696 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
697 Choice of these names is entirely up to the developer who is using logging.
698
699 All calls to this function with a given name return the same logger instance.
700 This means that logger instances never need to be passed between different parts
701 of an application.
702
703
704.. function:: getLoggerClass()
705
706 Return either the standard :class:`Logger` class, or the last class passed to
707 :func:`setLoggerClass`. This function may be called from within a new class
708 definition, to ensure that installing a customised :class:`Logger` class will
709 not undo customisations already applied by other code. For example::
710
711 class MyLogger(logging.getLoggerClass()):
712 # ... override behaviour here
713
714
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000715.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
718 message format string, and the *args* are the arguments which are merged into
719 *msg* using the string formatting operator. (Note that this means that you can
720 use keywords in the format string, together with a single dictionary argument.)
721
722 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
723 which, if it does not evaluate as false, causes exception information to be
724 added to the logging message. If an exception tuple (in the format returned by
725 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
726 is called to get the exception information.
727
728 The other optional keyword argument is *extra* which can be used to pass a
729 dictionary which is used to populate the __dict__ of the LogRecord created for
730 the logging event with user-defined attributes. These custom attributes can then
731 be used as you like. For example, they could be incorporated into logged
732 messages. For example::
733
734 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
735 logging.basicConfig(format=FORMAT)
736 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
737 logging.warning("Protocol problem: %s", "connection reset", extra=d)
738
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000739 would print something like ::
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
742
743 The keys in the dictionary passed in *extra* should not clash with the keys used
744 by the logging system. (See the :class:`Formatter` documentation for more
745 information on which keys are used by the logging system.)
746
747 If you choose to use these attributes in logged messages, you need to exercise
748 some care. In the above example, for instance, the :class:`Formatter` has been
749 set up with a format string which expects 'clientip' and 'user' in the attribute
750 dictionary of the LogRecord. If these are missing, the message will not be
751 logged because a string formatting exception will occur. So in this case, you
752 always need to pass the *extra* dictionary with these keys.
753
754 While this might be annoying, this feature is intended for use in specialized
755 circumstances, such as multi-threaded servers where the same code executes in
756 many contexts, and interesting conditions which arise are dependent on this
757 context (such as remote client IP address and authenticated user name, in the
758 above example). In such circumstances, it is likely that specialized
759 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
760
Georg Brandl116aa622007-08-15 14:28:22 +0000761
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000762.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000763
764 Logs a message with level :const:`INFO` on the root logger. The arguments are
765 interpreted as for :func:`debug`.
766
767
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000768.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000769
770 Logs a message with level :const:`WARNING` on the root logger. The arguments are
771 interpreted as for :func:`debug`.
772
773
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000774.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776 Logs a message with level :const:`ERROR` on the root logger. The arguments are
777 interpreted as for :func:`debug`.
778
779
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000780.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000781
782 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
783 are interpreted as for :func:`debug`.
784
785
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000786.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788 Logs a message with level :const:`ERROR` on the root logger. The arguments are
789 interpreted as for :func:`debug`. Exception info is added to the logging
790 message. This function should only be called from an exception handler.
791
792
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000793.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795 Logs a message with level *level* on the root logger. The other arguments are
796 interpreted as for :func:`debug`.
797
798
799.. function:: disable(lvl)
800
801 Provides an overriding level *lvl* for all loggers which takes precedence over
802 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000803 output down across the whole application, this function can be useful. Its
804 effect is to disable all logging calls of severity *lvl* and below, so that
805 if you call it with a value of INFO, then all INFO and DEBUG events would be
806 discarded, whereas those of severity WARNING and above would be processed
807 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000808
809
810.. function:: addLevelName(lvl, levelName)
811
812 Associates level *lvl* with text *levelName* in an internal dictionary, which is
813 used to map numeric levels to a textual representation, for example when a
814 :class:`Formatter` formats a message. This function can also be used to define
815 your own levels. The only constraints are that all levels used must be
816 registered using this function, levels should be positive integers and they
817 should increase in increasing order of severity.
818
819
820.. function:: getLevelName(lvl)
821
822 Returns the textual representation of logging level *lvl*. If the level is one
823 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
824 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
825 have associated levels with names using :func:`addLevelName` then the name you
826 have associated with *lvl* is returned. If a numeric value corresponding to one
827 of the defined levels is passed in, the corresponding string representation is
828 returned. Otherwise, the string "Level %s" % lvl is returned.
829
830
831.. function:: makeLogRecord(attrdict)
832
833 Creates and returns a new :class:`LogRecord` instance whose attributes are
834 defined by *attrdict*. This function is useful for taking a pickled
835 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
836 it as a :class:`LogRecord` instance at the receiving end.
837
838
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000839.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841 Does basic configuration for the logging system by creating a
842 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000843 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000844 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
845 if no handlers are defined for the root logger.
846
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000847 This function does nothing if the root logger already has handlers
848 configured for it.
849
Georg Brandl116aa622007-08-15 14:28:22 +0000850 The following keyword arguments are supported.
851
852 +--------------+---------------------------------------------+
853 | Format | Description |
854 +==============+=============================================+
855 | ``filename`` | Specifies that a FileHandler be created, |
856 | | using the specified filename, rather than a |
857 | | StreamHandler. |
858 +--------------+---------------------------------------------+
859 | ``filemode`` | Specifies the mode to open the file, if |
860 | | filename is specified (if filemode is |
861 | | unspecified, it defaults to 'a'). |
862 +--------------+---------------------------------------------+
863 | ``format`` | Use the specified format string for the |
864 | | handler. |
865 +--------------+---------------------------------------------+
866 | ``datefmt`` | Use the specified date/time format. |
867 +--------------+---------------------------------------------+
868 | ``level`` | Set the root logger level to the specified |
869 | | level. |
870 +--------------+---------------------------------------------+
871 | ``stream`` | Use the specified stream to initialize the |
872 | | StreamHandler. Note that this argument is |
873 | | incompatible with 'filename' - if both are |
874 | | present, 'stream' is ignored. |
875 +--------------+---------------------------------------------+
876
877
878.. function:: shutdown()
879
880 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000881 closing all handlers. This should be called at application exit and no
882 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000883
884
885.. function:: setLoggerClass(klass)
886
887 Tells the logging system to use the class *klass* when instantiating a logger.
888 The class should define :meth:`__init__` such that only a name argument is
889 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
890 function is typically called before any loggers are instantiated by applications
891 which need to use custom logger behavior.
892
893
894.. seealso::
895
896 :pep:`282` - A Logging System
897 The proposal which described this feature for inclusion in the Python standard
898 library.
899
Christian Heimes255f53b2007-12-08 15:33:56 +0000900 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000901 This is the original source for the :mod:`logging` package. The version of the
902 package available from this site is suitable for use with Python 1.5.2, 2.1.x
903 and 2.2.x, which do not include the :mod:`logging` package in the standard
904 library.
905
906
907Logger Objects
908--------------
909
910Loggers have the following attributes and methods. Note that Loggers are never
911instantiated directly, but always through the module-level function
912``logging.getLogger(name)``.
913
914
915.. attribute:: Logger.propagate
916
917 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000918 its child loggers to the handlers of higher level (ancestor) loggers. The
919 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921
922.. method:: Logger.setLevel(lvl)
923
924 Sets the threshold for this logger to *lvl*. Logging messages which are less
925 severe than *lvl* will be ignored. When a logger is created, the level is set to
926 :const:`NOTSET` (which causes all messages to be processed when the logger is
927 the root logger, or delegation to the parent when the logger is a non-root
928 logger). Note that the root logger is created with level :const:`WARNING`.
929
930 The term "delegation to the parent" means that if a logger has a level of
931 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
932 a level other than NOTSET is found, or the root is reached.
933
934 If an ancestor is found with a level other than NOTSET, then that ancestor's
935 level is treated as the effective level of the logger where the ancestor search
936 began, and is used to determine how a logging event is handled.
937
938 If the root is reached, and it has a level of NOTSET, then all messages will be
939 processed. Otherwise, the root's level will be used as the effective level.
940
941
942.. method:: Logger.isEnabledFor(lvl)
943
944 Indicates if a message of severity *lvl* would be processed by this logger.
945 This method checks first the module-level level set by
946 ``logging.disable(lvl)`` and then the logger's effective level as determined
947 by :meth:`getEffectiveLevel`.
948
949
950.. method:: Logger.getEffectiveLevel()
951
952 Indicates the effective level for this logger. If a value other than
953 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
954 the hierarchy is traversed towards the root until a value other than
955 :const:`NOTSET` is found, and that value is returned.
956
957
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000958.. method:: Logger.getChild(suffix)
959
960 Returns a logger which is a descendant to this logger, as determined by the suffix.
961 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
962 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
963 convenience method, useful when the parent logger is named using e.g. ``__name__``
964 rather than a literal string.
965
966 .. versionadded:: 3.2
967
Georg Brandl67b21b72010-08-17 15:07:14 +0000968
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000969.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000970
971 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
972 message format string, and the *args* are the arguments which are merged into
973 *msg* using the string formatting operator. (Note that this means that you can
974 use keywords in the format string, together with a single dictionary argument.)
975
976 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
977 which, if it does not evaluate as false, causes exception information to be
978 added to the logging message. If an exception tuple (in the format returned by
979 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
980 is called to get the exception information.
981
982 The other optional keyword argument is *extra* which can be used to pass a
983 dictionary which is used to populate the __dict__ of the LogRecord created for
984 the logging event with user-defined attributes. These custom attributes can then
985 be used as you like. For example, they could be incorporated into logged
986 messages. For example::
987
988 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
989 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000990 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +0000991 logger = logging.getLogger("tcpserver")
992 logger.warning("Protocol problem: %s", "connection reset", extra=d)
993
994 would print something like ::
995
996 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
997
998 The keys in the dictionary passed in *extra* should not clash with the keys used
999 by the logging system. (See the :class:`Formatter` documentation for more
1000 information on which keys are used by the logging system.)
1001
1002 If you choose to use these attributes in logged messages, you need to exercise
1003 some care. In the above example, for instance, the :class:`Formatter` has been
1004 set up with a format string which expects 'clientip' and 'user' in the attribute
1005 dictionary of the LogRecord. If these are missing, the message will not be
1006 logged because a string formatting exception will occur. So in this case, you
1007 always need to pass the *extra* dictionary with these keys.
1008
1009 While this might be annoying, this feature is intended for use in specialized
1010 circumstances, such as multi-threaded servers where the same code executes in
1011 many contexts, and interesting conditions which arise are dependent on this
1012 context (such as remote client IP address and authenticated user name, in the
1013 above example). In such circumstances, it is likely that specialized
1014 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1015
Georg Brandl116aa622007-08-15 14:28:22 +00001016
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001017.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019 Logs a message with level :const:`INFO` on this logger. The arguments are
1020 interpreted as for :meth:`debug`.
1021
1022
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001023.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001024
1025 Logs a message with level :const:`WARNING` on this logger. The arguments are
1026 interpreted as for :meth:`debug`.
1027
1028
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001029.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031 Logs a message with level :const:`ERROR` on this logger. The arguments are
1032 interpreted as for :meth:`debug`.
1033
1034
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001035.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1038 interpreted as for :meth:`debug`.
1039
1040
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001041.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043 Logs a message with integer level *lvl* on this logger. The other arguments are
1044 interpreted as for :meth:`debug`.
1045
1046
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001047.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049 Logs a message with level :const:`ERROR` on this logger. The arguments are
1050 interpreted as for :meth:`debug`. Exception info is added to the logging
1051 message. This method should only be called from an exception handler.
1052
1053
1054.. method:: Logger.addFilter(filt)
1055
1056 Adds the specified filter *filt* to this logger.
1057
1058
1059.. method:: Logger.removeFilter(filt)
1060
1061 Removes the specified filter *filt* from this logger.
1062
1063
1064.. method:: Logger.filter(record)
1065
1066 Applies this logger's filters to the record and returns a true value if the
1067 record is to be processed.
1068
1069
1070.. method:: Logger.addHandler(hdlr)
1071
1072 Adds the specified handler *hdlr* to this logger.
1073
1074
1075.. method:: Logger.removeHandler(hdlr)
1076
1077 Removes the specified handler *hdlr* from this logger.
1078
1079
1080.. method:: Logger.findCaller()
1081
1082 Finds the caller's source filename and line number. Returns the filename, line
1083 number and function name as a 3-element tuple.
1084
Georg Brandl116aa622007-08-15 14:28:22 +00001085
1086.. method:: Logger.handle(record)
1087
1088 Handles a record by passing it to all handlers associated with this logger and
1089 its ancestors (until a false value of *propagate* is found). This method is used
1090 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001091 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001092
1093
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001094.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096 This is a factory method which can be overridden in subclasses to create
1097 specialized :class:`LogRecord` instances.
1098
Georg Brandl116aa622007-08-15 14:28:22 +00001099
1100.. _minimal-example:
1101
1102Basic example
1103-------------
1104
Georg Brandl116aa622007-08-15 14:28:22 +00001105The :mod:`logging` package provides a lot of flexibility, and its configuration
1106can appear daunting. This section demonstrates that simple use of the logging
1107package is possible.
1108
1109The simplest example shows logging to the console::
1110
1111 import logging
1112
1113 logging.debug('A debug message')
1114 logging.info('Some information')
1115 logging.warning('A shot across the bows')
1116
1117If you run the above script, you'll see this::
1118
1119 WARNING:root:A shot across the bows
1120
1121Because no particular logger was specified, the system used the root logger. The
1122debug and info messages didn't appear because by default, the root logger is
1123configured to only handle messages with a severity of WARNING or above. The
1124message format is also a configuration default, as is the output destination of
1125the messages - ``sys.stderr``. The severity level, the message format and
1126destination can be easily changed, as shown in the example below::
1127
1128 import logging
1129
1130 logging.basicConfig(level=logging.DEBUG,
1131 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001132 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001133 filemode='w')
1134 logging.debug('A debug message')
1135 logging.info('Some information')
1136 logging.warning('A shot across the bows')
1137
1138The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001139which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001140something like the following::
1141
1142 2004-07-02 13:00:08,743 DEBUG A debug message
1143 2004-07-02 13:00:08,743 INFO Some information
1144 2004-07-02 13:00:08,743 WARNING A shot across the bows
1145
1146This time, all messages with a severity of DEBUG or above were handled, and the
1147format of the messages was also changed, and output went to the specified file
1148rather than the console.
1149
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001150.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001151
1152Formatting uses the old Python string formatting - see section
1153:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001154specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1155documentation.
1156
1157+-------------------+-----------------------------------------------+
1158| Format | Description |
1159+===================+===============================================+
1160| ``%(name)s`` | Name of the logger (logging channel). |
1161+-------------------+-----------------------------------------------+
1162| ``%(levelname)s`` | Text logging level for the message |
1163| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1164| | ``'ERROR'``, ``'CRITICAL'``). |
1165+-------------------+-----------------------------------------------+
1166| ``%(asctime)s`` | Human-readable time when the |
1167| | :class:`LogRecord` was created. By default |
1168| | this is of the form "2003-07-08 16:49:45,896" |
1169| | (the numbers after the comma are millisecond |
1170| | portion of the time). |
1171+-------------------+-----------------------------------------------+
1172| ``%(message)s`` | The logged message. |
1173+-------------------+-----------------------------------------------+
1174
1175To change the date/time format, you can pass an additional keyword parameter,
1176*datefmt*, as in the following::
1177
1178 import logging
1179
1180 logging.basicConfig(level=logging.DEBUG,
1181 format='%(asctime)s %(levelname)-8s %(message)s',
1182 datefmt='%a, %d %b %Y %H:%M:%S',
1183 filename='/temp/myapp.log',
1184 filemode='w')
1185 logging.debug('A debug message')
1186 logging.info('Some information')
1187 logging.warning('A shot across the bows')
1188
1189which would result in output like ::
1190
1191 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1192 Fri, 02 Jul 2004 13:06:18 INFO Some information
1193 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1194
1195The date format string follows the requirements of :func:`strftime` - see the
1196documentation for the :mod:`time` module.
1197
1198If, instead of sending logging output to the console or a file, you'd rather use
1199a file-like object which you have created separately, you can pass it to
1200:func:`basicConfig` using the *stream* keyword argument. Note that if both
1201*stream* and *filename* keyword arguments are passed, the *stream* argument is
1202ignored.
1203
1204Of course, you can put variable information in your output. To do this, simply
1205have the message be a format string and pass in additional arguments containing
1206the variable information, as in the following example::
1207
1208 import logging
1209
1210 logging.basicConfig(level=logging.DEBUG,
1211 format='%(asctime)s %(levelname)-8s %(message)s',
1212 datefmt='%a, %d %b %Y %H:%M:%S',
1213 filename='/temp/myapp.log',
1214 filemode='w')
1215 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1216
1217which would result in ::
1218
1219 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1220
1221
1222.. _multiple-destinations:
1223
1224Logging to multiple destinations
1225--------------------------------
1226
1227Let's say you want to log to console and file with different message formats and
1228in differing circumstances. Say you want to log messages with levels of DEBUG
1229and higher to file, and those messages at level INFO and higher to the console.
1230Let's also assume that the file should contain timestamps, but the console
1231messages should not. Here's how you can achieve this::
1232
1233 import logging
1234
1235 # set up logging to file - see previous section for more details
1236 logging.basicConfig(level=logging.DEBUG,
1237 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1238 datefmt='%m-%d %H:%M',
1239 filename='/temp/myapp.log',
1240 filemode='w')
1241 # define a Handler which writes INFO messages or higher to the sys.stderr
1242 console = logging.StreamHandler()
1243 console.setLevel(logging.INFO)
1244 # set a format which is simpler for console use
1245 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1246 # tell the handler to use this format
1247 console.setFormatter(formatter)
1248 # add the handler to the root logger
1249 logging.getLogger('').addHandler(console)
1250
1251 # Now, we can log to the root logger, or any other logger. First the root...
1252 logging.info('Jackdaws love my big sphinx of quartz.')
1253
1254 # Now, define a couple of other loggers which might represent areas in your
1255 # application:
1256
1257 logger1 = logging.getLogger('myapp.area1')
1258 logger2 = logging.getLogger('myapp.area2')
1259
1260 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1261 logger1.info('How quickly daft jumping zebras vex.')
1262 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1263 logger2.error('The five boxing wizards jump quickly.')
1264
1265When you run this, on the console you will see ::
1266
1267 root : INFO Jackdaws love my big sphinx of quartz.
1268 myapp.area1 : INFO How quickly daft jumping zebras vex.
1269 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1270 myapp.area2 : ERROR The five boxing wizards jump quickly.
1271
1272and in the file you will see something like ::
1273
1274 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1275 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1276 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1277 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1278 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1279
1280As you can see, the DEBUG message only shows up in the file. The other messages
1281are sent to both destinations.
1282
1283This example uses console and file handlers, but you can use any number and
1284combination of handlers you choose.
1285
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001286.. _logging-exceptions:
1287
1288Exceptions raised during logging
1289--------------------------------
1290
1291The logging package is designed to swallow exceptions which occur while logging
1292in production. This is so that errors which occur while handling logging events
1293- such as logging misconfiguration, network or other similar errors - do not
1294cause the application using logging to terminate prematurely.
1295
1296:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1297swallowed. Other exceptions which occur during the :meth:`emit` method of a
1298:class:`Handler` subclass are passed to its :meth:`handleError` method.
1299
1300The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001301to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1302traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001303
Georg Brandlef871f62010-03-12 10:06:40 +00001304**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001305during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001306occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001307usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001308
Christian Heimes790c8232008-01-07 21:14:23 +00001309.. _context-info:
1310
1311Adding contextual information to your logging output
1312----------------------------------------------------
1313
1314Sometimes you want logging output to contain contextual information in
1315addition to the parameters passed to the logging call. For example, in a
1316networked application, it may be desirable to log client-specific information
1317in the log (e.g. remote client's username, or IP address). Although you could
1318use the *extra* parameter to achieve this, it's not always convenient to pass
1319the information in this way. While it might be tempting to create
1320:class:`Logger` instances on a per-connection basis, this is not a good idea
1321because these instances are not garbage collected. While this is not a problem
1322in practice, when the number of :class:`Logger` instances is dependent on the
1323level of granularity you want to use in logging an application, it could
1324be hard to manage if the number of :class:`Logger` instances becomes
1325effectively unbounded.
1326
Vinay Sajipc31be632010-09-06 22:18:20 +00001327
1328Using LoggerAdapters to impart contextual information
1329^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1330
Christian Heimes04c420f2008-01-18 18:40:46 +00001331An easy way in which you can pass contextual information to be output along
1332with logging event information is to use the :class:`LoggerAdapter` class.
1333This class is designed to look like a :class:`Logger`, so that you can call
1334:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1335:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1336same signatures as their counterparts in :class:`Logger`, so you can use the
1337two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001338
Christian Heimes04c420f2008-01-18 18:40:46 +00001339When you create an instance of :class:`LoggerAdapter`, you pass it a
1340:class:`Logger` instance and a dict-like object which contains your contextual
1341information. When you call one of the logging methods on an instance of
1342:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1343:class:`Logger` passed to its constructor, and arranges to pass the contextual
1344information in the delegated call. Here's a snippet from the code of
1345:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001346
Christian Heimes04c420f2008-01-18 18:40:46 +00001347 def debug(self, msg, *args, **kwargs):
1348 """
1349 Delegate a debug call to the underlying logger, after adding
1350 contextual information from this adapter instance.
1351 """
1352 msg, kwargs = self.process(msg, kwargs)
1353 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001354
Christian Heimes04c420f2008-01-18 18:40:46 +00001355The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1356information is added to the logging output. It's passed the message and
1357keyword arguments of the logging call, and it passes back (potentially)
1358modified versions of these to use in the call to the underlying logger. The
1359default implementation of this method leaves the message alone, but inserts
1360an "extra" key in the keyword argument whose value is the dict-like object
1361passed to the constructor. Of course, if you had passed an "extra" keyword
1362argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001363
Christian Heimes04c420f2008-01-18 18:40:46 +00001364The advantage of using "extra" is that the values in the dict-like object are
1365merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1366customized strings with your :class:`Formatter` instances which know about
1367the keys of the dict-like object. If you need a different method, e.g. if you
1368want to prepend or append the contextual information to the message string,
1369you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1370to do what you need. Here's an example script which uses this class, which
1371also illustrates what dict-like behaviour is needed from an arbitrary
1372"dict-like" object for use in the constructor::
1373
Christian Heimes587c2bf2008-01-19 16:21:02 +00001374 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001375
Christian Heimes587c2bf2008-01-19 16:21:02 +00001376 class ConnInfo:
1377 """
1378 An example class which shows how an arbitrary class can be used as
1379 the 'extra' context information repository passed to a LoggerAdapter.
1380 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001381
Christian Heimes587c2bf2008-01-19 16:21:02 +00001382 def __getitem__(self, name):
1383 """
1384 To allow this instance to look like a dict.
1385 """
1386 from random import choice
1387 if name == "ip":
1388 result = choice(["127.0.0.1", "192.168.0.1"])
1389 elif name == "user":
1390 result = choice(["jim", "fred", "sheila"])
1391 else:
1392 result = self.__dict__.get(name, "?")
1393 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001394
Christian Heimes587c2bf2008-01-19 16:21:02 +00001395 def __iter__(self):
1396 """
1397 To allow iteration over keys, which will be merged into
1398 the LogRecord dict before formatting and output.
1399 """
1400 keys = ["ip", "user"]
1401 keys.extend(self.__dict__.keys())
1402 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001403
Christian Heimes587c2bf2008-01-19 16:21:02 +00001404 if __name__ == "__main__":
1405 from random import choice
1406 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1407 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1408 { "ip" : "123.231.231.123", "user" : "sheila" })
1409 logging.basicConfig(level=logging.DEBUG,
1410 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1411 a1.debug("A debug message")
1412 a1.info("An info message with %s", "some parameters")
1413 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1414 for x in range(10):
1415 lvl = choice(levels)
1416 lvlname = logging.getLevelName(lvl)
1417 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001418
1419When this script is run, the output should look something like this::
1420
Christian Heimes587c2bf2008-01-19 16:21:02 +00001421 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1422 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1423 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
1424 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
1425 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
1426 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
1427 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
1428 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
1429 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
1430 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
1431 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
1432 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 +00001433
Christian Heimes790c8232008-01-07 21:14:23 +00001434
Vinay Sajipc31be632010-09-06 22:18:20 +00001435Using Filters to impart contextual information
1436^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1437
1438You can also add contextual information to log output using a user-defined
1439:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1440passed to them, including adding additional attributes which can then be output
1441using a suitable format string, or if needed a custom :class:`Formatter`.
1442
1443For example in a web application, the request being processed (or at least,
1444the interesting parts of it) can be stored in a threadlocal
1445(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1446add, say, information from the request - say, the remote IP address and remote
1447user's username - to the ``LogRecord``, using the attribute names 'ip' and
1448'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1449string can be used to get similar output to that shown above. Here's an example
1450script::
1451
1452 import logging
1453 from random import choice
1454
1455 class ContextFilter(logging.Filter):
1456 """
1457 This is a filter which injects contextual information into the log.
1458
1459 Rather than use actual contextual information, we just use random
1460 data in this demo.
1461 """
1462
1463 USERS = ['jim', 'fred', 'sheila']
1464 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1465
1466 def filter(self, record):
1467
1468 record.ip = choice(ContextFilter.IPS)
1469 record.user = choice(ContextFilter.USERS)
1470 return True
1471
1472 if __name__ == "__main__":
1473 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1474 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1475 { "ip" : "123.231.231.123", "user" : "sheila" })
1476 logging.basicConfig(level=logging.DEBUG,
1477 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1478 a1 = logging.getLogger("a.b.c")
1479 a2 = logging.getLogger("d.e.f")
1480
1481 f = ContextFilter()
1482 a1.addFilter(f)
1483 a2.addFilter(f)
1484 a1.debug("A debug message")
1485 a1.info("An info message with %s", "some parameters")
1486 for x in range(10):
1487 lvl = choice(levels)
1488 lvlname = logging.getLevelName(lvl)
1489 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1490
1491which, when run, produces something like::
1492
1493 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1494 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1495 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
1496 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
1497 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
1498 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
1499 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
1500 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
1501 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
1502 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
1503 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
1504 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
1505
1506
Vinay Sajipd31f3632010-06-29 15:31:15 +00001507.. _multiple-processes:
1508
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001509Logging to a single file from multiple processes
1510------------------------------------------------
1511
1512Although logging is thread-safe, and logging to a single file from multiple
1513threads in a single process *is* supported, logging to a single file from
1514*multiple processes* is *not* supported, because there is no standard way to
1515serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001516need to log to a single file from multiple processes, one way of doing this is
1517to have all the processes log to a :class:`SocketHandler`, and have a separate
1518process which implements a socket server which reads from the socket and logs
1519to file. (If you prefer, you can dedicate one thread in one of the existing
1520processes to perform this function.) The following section documents this
1521approach in more detail and includes a working socket receiver which can be
1522used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001523
Vinay Sajip5a92b132009-08-15 23:35:08 +00001524If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001525:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001526:class:`Lock` class from this module to serialize access to the file from
1527your processes. The existing :class:`FileHandler` and subclasses do not make
1528use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001529Note that at present, the :mod:`multiprocessing` module does not provide
1530working lock functionality on all platforms (see
1531http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001532
Vinay Sajip121a1c42010-09-08 10:46:15 +00001533.. currentmodule:: logging.handlers
1534
1535Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1536all logging events to one of the processes in your multi-process application.
1537The following example script demonstrates how you can do this; in the example
1538a separate listener process listens for events sent by other processes and logs
1539them according to its own logging configuration. Although the example only
1540demonstrates one way of doing it (for example, you may want to use a listener
1541thread rather than a separate listener process - the implementation would be
1542analogous) it does allow for completely different logging configurations for
1543the listener and the other processes in your application, and can be used as
1544the basis for code meeting your own specific requirements::
1545
1546 # You'll need these imports in your own code
1547 import logging
1548 import logging.handlers
1549 import multiprocessing
1550
1551 # Next two import lines for this demo only
1552 from random import choice, random
1553 import time
1554
1555 #
1556 # Because you'll want to define the logging configurations for listener and workers, the
1557 # listener and worker process functions take a configurer parameter which is a callable
1558 # for configuring logging for that process. These functions are also passed the queue,
1559 # which they use for communication.
1560 #
1561 # In practice, you can configure the listener however you want, but note that in this
1562 # simple example, the listener does not apply level or filter logic to received records.
1563 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1564 # sending events which would be filtered out between processes.
1565 #
1566 # The size of the rotated files is made small so you can see the results easily.
1567 def listener_configurer():
1568 root = logging.getLogger()
1569 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
1570 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1571 h.setFormatter(f)
1572 root.addHandler(h)
1573
1574 # This is the listener process top-level loop: wait for logging events
1575 # (LogRecords)on the queue and handle them, quit when you get a None for a
1576 # LogRecord.
1577 def listener_process(queue, configurer):
1578 configurer()
1579 while True:
1580 try:
1581 record = queue.get()
1582 if record is None: # We send this as a sentinel to tell the listener to quit.
1583 break
1584 logger = logging.getLogger(record.name)
1585 logger.handle(record) # No level or filter logic applied - just do it!
1586 except (KeyboardInterrupt, SystemExit):
1587 raise
1588 except:
1589 import sys, traceback
1590 print >> sys.stderr, 'Whoops! Problem:'
1591 traceback.print_exc(file=sys.stderr)
1592
1593 # Arrays used for random selections in this demo
1594
1595 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1596 logging.ERROR, logging.CRITICAL]
1597
1598 LOGGERS = ['a.b.c', 'd.e.f']
1599
1600 MESSAGES = [
1601 'Random message #1',
1602 'Random message #2',
1603 'Random message #3',
1604 ]
1605
1606 # The worker configuration is done at the start of the worker process run.
1607 # Note that on Windows you can't rely on fork semantics, so each process
1608 # will run the logging configuration code when it starts.
1609 def worker_configurer(queue):
1610 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1611 root = logging.getLogger()
1612 root.addHandler(h)
1613 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
1614
1615 # This is the worker process top-level loop, which just logs ten events with
1616 # random intervening delays before terminating.
1617 # The print messages are just so you know it's doing something!
1618 def worker_process(queue, configurer):
1619 configurer(queue)
1620 name = multiprocessing.current_process().name
1621 print('Worker started: %s' % name)
1622 for i in range(10):
1623 time.sleep(random())
1624 logger = logging.getLogger(choice(LOGGERS))
1625 level = choice(LEVELS)
1626 message = choice(MESSAGES)
1627 logger.log(level, message)
1628 print('Worker finished: %s' % name)
1629
1630 # Here's where the demo gets orchestrated. Create the queue, create and start
1631 # the listener, create ten workers and start them, wait for them to finish,
1632 # then send a None to the queue to tell the listener to finish.
1633 def main():
1634 queue = multiprocessing.Queue(-1)
1635 listener = multiprocessing.Process(target=listener_process,
1636 args=(queue, listener_configurer))
1637 listener.start()
1638 workers = []
1639 for i in range(10):
1640 worker = multiprocessing.Process(target=worker_process,
1641 args=(queue, worker_configurer))
1642 workers.append(worker)
1643 worker.start()
1644 for w in workers:
1645 w.join()
1646 queue.put_nowait(None)
1647 listener.join()
1648
1649 if __name__ == '__main__':
1650 main()
1651
1652
1653.. currentmodule:: logging
1654
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001655
Georg Brandl116aa622007-08-15 14:28:22 +00001656.. _network-logging:
1657
1658Sending and receiving logging events across a network
1659-----------------------------------------------------
1660
1661Let's say you want to send logging events across a network, and handle them at
1662the receiving end. A simple way of doing this is attaching a
1663:class:`SocketHandler` instance to the root logger at the sending end::
1664
1665 import logging, logging.handlers
1666
1667 rootLogger = logging.getLogger('')
1668 rootLogger.setLevel(logging.DEBUG)
1669 socketHandler = logging.handlers.SocketHandler('localhost',
1670 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1671 # don't bother with a formatter, since a socket handler sends the event as
1672 # an unformatted pickle
1673 rootLogger.addHandler(socketHandler)
1674
1675 # Now, we can log to the root logger, or any other logger. First the root...
1676 logging.info('Jackdaws love my big sphinx of quartz.')
1677
1678 # Now, define a couple of other loggers which might represent areas in your
1679 # application:
1680
1681 logger1 = logging.getLogger('myapp.area1')
1682 logger2 = logging.getLogger('myapp.area2')
1683
1684 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1685 logger1.info('How quickly daft jumping zebras vex.')
1686 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1687 logger2.error('The five boxing wizards jump quickly.')
1688
Alexandre Vassalottice261952008-05-12 02:31:37 +00001689At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001690module. Here is a basic working example::
1691
Georg Brandla35f4b92009-05-31 16:41:59 +00001692 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001693 import logging
1694 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001695 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001696 import struct
1697
1698
Alexandre Vassalottice261952008-05-12 02:31:37 +00001699 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001700 """Handler for a streaming logging request.
1701
1702 This basically logs the record using whatever logging policy is
1703 configured locally.
1704 """
1705
1706 def handle(self):
1707 """
1708 Handle multiple requests - each expected to be a 4-byte length,
1709 followed by the LogRecord in pickle format. Logs the record
1710 according to whatever policy is configured locally.
1711 """
Collin Winter46334482007-09-10 00:49:57 +00001712 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001713 chunk = self.connection.recv(4)
1714 if len(chunk) < 4:
1715 break
1716 slen = struct.unpack(">L", chunk)[0]
1717 chunk = self.connection.recv(slen)
1718 while len(chunk) < slen:
1719 chunk = chunk + self.connection.recv(slen - len(chunk))
1720 obj = self.unPickle(chunk)
1721 record = logging.makeLogRecord(obj)
1722 self.handleLogRecord(record)
1723
1724 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001725 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001726
1727 def handleLogRecord(self, record):
1728 # if a name is specified, we use the named logger rather than the one
1729 # implied by the record.
1730 if self.server.logname is not None:
1731 name = self.server.logname
1732 else:
1733 name = record.name
1734 logger = logging.getLogger(name)
1735 # N.B. EVERY record gets logged. This is because Logger.handle
1736 # is normally called AFTER logger-level filtering. If you want
1737 # to do filtering, do it at the client end to save wasting
1738 # cycles and network bandwidth!
1739 logger.handle(record)
1740
Alexandre Vassalottice261952008-05-12 02:31:37 +00001741 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001742 """simple TCP socket-based logging receiver suitable for testing.
1743 """
1744
1745 allow_reuse_address = 1
1746
1747 def __init__(self, host='localhost',
1748 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1749 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001750 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001751 self.abort = 0
1752 self.timeout = 1
1753 self.logname = None
1754
1755 def serve_until_stopped(self):
1756 import select
1757 abort = 0
1758 while not abort:
1759 rd, wr, ex = select.select([self.socket.fileno()],
1760 [], [],
1761 self.timeout)
1762 if rd:
1763 self.handle_request()
1764 abort = self.abort
1765
1766 def main():
1767 logging.basicConfig(
1768 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1769 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001770 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001771 tcpserver.serve_until_stopped()
1772
1773 if __name__ == "__main__":
1774 main()
1775
1776First run the server, and then the client. On the client side, nothing is
1777printed on the console; on the server side, you should see something like::
1778
1779 About to start TCP server...
1780 59 root INFO Jackdaws love my big sphinx of quartz.
1781 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1782 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1783 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1784 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1785
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001786Note that there are some security issues with pickle in some scenarios. If
1787these affect you, you can use an alternative serialization scheme by overriding
1788the :meth:`makePickle` method and implementing your alternative there, as
1789well as adapting the above script to use your alternative serialization.
1790
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001791Using arbitrary objects as messages
1792-----------------------------------
1793
1794In the preceding sections and examples, it has been assumed that the message
1795passed when logging the event is a string. However, this is not the only
1796possibility. You can pass an arbitrary object as a message, and its
1797:meth:`__str__` method will be called when the logging system needs to convert
1798it to a string representation. In fact, if you want to, you can avoid
1799computing a string representation altogether - for example, the
1800:class:`SocketHandler` emits an event by pickling it and sending it over the
1801wire.
1802
1803Optimization
1804------------
1805
1806Formatting of message arguments is deferred until it cannot be avoided.
1807However, computing the arguments passed to the logging method can also be
1808expensive, and you may want to avoid doing it if the logger will just throw
1809away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1810method which takes a level argument and returns true if the event would be
1811created by the Logger for that level of call. You can write code like this::
1812
1813 if logger.isEnabledFor(logging.DEBUG):
1814 logger.debug("Message with %s, %s", expensive_func1(),
1815 expensive_func2())
1816
1817so that if the logger's threshold is set above ``DEBUG``, the calls to
1818:func:`expensive_func1` and :func:`expensive_func2` are never made.
1819
1820There are other optimizations which can be made for specific applications which
1821need more precise control over what logging information is collected. Here's a
1822list of things you can do to avoid processing during logging which you don't
1823need:
1824
1825+-----------------------------------------------+----------------------------------------+
1826| What you don't want to collect | How to avoid collecting it |
1827+===============================================+========================================+
1828| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1829+-----------------------------------------------+----------------------------------------+
1830| Threading information. | Set ``logging.logThreads`` to ``0``. |
1831+-----------------------------------------------+----------------------------------------+
1832| Process information. | Set ``logging.logProcesses`` to ``0``. |
1833+-----------------------------------------------+----------------------------------------+
1834
1835Also note that the core logging module only includes the basic handlers. If
1836you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1837take up any memory.
1838
1839.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001840
1841Handler Objects
1842---------------
1843
1844Handlers have the following attributes and methods. Note that :class:`Handler`
1845is never instantiated directly; this class acts as a base for more useful
1846subclasses. However, the :meth:`__init__` method in subclasses needs to call
1847:meth:`Handler.__init__`.
1848
1849
1850.. method:: Handler.__init__(level=NOTSET)
1851
1852 Initializes the :class:`Handler` instance by setting its level, setting the list
1853 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1854 serializing access to an I/O mechanism.
1855
1856
1857.. method:: Handler.createLock()
1858
1859 Initializes a thread lock which can be used to serialize access to underlying
1860 I/O functionality which may not be threadsafe.
1861
1862
1863.. method:: Handler.acquire()
1864
1865 Acquires the thread lock created with :meth:`createLock`.
1866
1867
1868.. method:: Handler.release()
1869
1870 Releases the thread lock acquired with :meth:`acquire`.
1871
1872
1873.. method:: Handler.setLevel(lvl)
1874
1875 Sets the threshold for this handler to *lvl*. Logging messages which are less
1876 severe than *lvl* will be ignored. When a handler is created, the level is set
1877 to :const:`NOTSET` (which causes all messages to be processed).
1878
1879
1880.. method:: Handler.setFormatter(form)
1881
1882 Sets the :class:`Formatter` for this handler to *form*.
1883
1884
1885.. method:: Handler.addFilter(filt)
1886
1887 Adds the specified filter *filt* to this handler.
1888
1889
1890.. method:: Handler.removeFilter(filt)
1891
1892 Removes the specified filter *filt* from this handler.
1893
1894
1895.. method:: Handler.filter(record)
1896
1897 Applies this handler's filters to the record and returns a true value if the
1898 record is to be processed.
1899
1900
1901.. method:: Handler.flush()
1902
1903 Ensure all logging output has been flushed. This version does nothing and is
1904 intended to be implemented by subclasses.
1905
1906
1907.. method:: Handler.close()
1908
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001909 Tidy up any resources used by the handler. This version does no output but
1910 removes the handler from an internal list of handlers which is closed when
1911 :func:`shutdown` is called. Subclasses should ensure that this gets called
1912 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001913
1914
1915.. method:: Handler.handle(record)
1916
1917 Conditionally emits the specified logging record, depending on filters which may
1918 have been added to the handler. Wraps the actual emission of the record with
1919 acquisition/release of the I/O thread lock.
1920
1921
1922.. method:: Handler.handleError(record)
1923
1924 This method should be called from handlers when an exception is encountered
1925 during an :meth:`emit` call. By default it does nothing, which means that
1926 exceptions get silently ignored. This is what is mostly wanted for a logging
1927 system - most users will not care about errors in the logging system, they are
1928 more interested in application errors. You could, however, replace this with a
1929 custom handler if you wish. The specified record is the one which was being
1930 processed when the exception occurred.
1931
1932
1933.. method:: Handler.format(record)
1934
1935 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1936 default formatter for the module.
1937
1938
1939.. method:: Handler.emit(record)
1940
1941 Do whatever it takes to actually log the specified logging record. This version
1942 is intended to be implemented by subclasses and so raises a
1943 :exc:`NotImplementedError`.
1944
1945
Vinay Sajipd31f3632010-06-29 15:31:15 +00001946.. _stream-handler:
1947
Georg Brandl116aa622007-08-15 14:28:22 +00001948StreamHandler
1949^^^^^^^^^^^^^
1950
1951The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1952sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1953file-like object (or, more precisely, any object which supports :meth:`write`
1954and :meth:`flush` methods).
1955
1956
Benjamin Peterson1baf4652009-12-31 03:11:23 +00001957.. currentmodule:: logging
1958
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001959.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001960
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001961 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00001962 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1963 will be used.
1964
1965
Benjamin Petersone41251e2008-04-25 01:59:09 +00001966 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00001967
Benjamin Petersone41251e2008-04-25 01:59:09 +00001968 If a formatter is specified, it is used to format the record. The record
1969 is then written to the stream with a trailing newline. If exception
1970 information is present, it is formatted using
1971 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00001972
1973
Benjamin Petersone41251e2008-04-25 01:59:09 +00001974 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00001975
Benjamin Petersone41251e2008-04-25 01:59:09 +00001976 Flushes the stream by calling its :meth:`flush` method. Note that the
1977 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001978 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00001979
1980
Vinay Sajipd31f3632010-06-29 15:31:15 +00001981.. _file-handler:
1982
Georg Brandl116aa622007-08-15 14:28:22 +00001983FileHandler
1984^^^^^^^^^^^
1985
1986The :class:`FileHandler` class, located in the core :mod:`logging` package,
1987sends logging output to a disk file. It inherits the output functionality from
1988:class:`StreamHandler`.
1989
1990
Vinay Sajipd31f3632010-06-29 15:31:15 +00001991.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001992
1993 Returns a new instance of the :class:`FileHandler` class. The specified file is
1994 opened and used as the stream for logging. If *mode* is not specified,
1995 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00001996 with that encoding. If *delay* is true, then file opening is deferred until the
1997 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00001998
1999
Benjamin Petersone41251e2008-04-25 01:59:09 +00002000 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002001
Benjamin Petersone41251e2008-04-25 01:59:09 +00002002 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002003
2004
Benjamin Petersone41251e2008-04-25 01:59:09 +00002005 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002006
Benjamin Petersone41251e2008-04-25 01:59:09 +00002007 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002008
Vinay Sajipd31f3632010-06-29 15:31:15 +00002009.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002010
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002011NullHandler
2012^^^^^^^^^^^
2013
2014.. versionadded:: 3.1
2015
2016The :class:`NullHandler` class, located in the core :mod:`logging` package,
2017does not do any formatting or output. It is essentially a "no-op" handler
2018for use by library developers.
2019
2020
2021.. class:: NullHandler()
2022
2023 Returns a new instance of the :class:`NullHandler` class.
2024
2025
2026 .. method:: emit(record)
2027
2028 This method does nothing.
2029
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002030See :ref:`library-config` for more information on how to use
2031:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002032
Vinay Sajipd31f3632010-06-29 15:31:15 +00002033.. _watched-file-handler:
2034
Georg Brandl116aa622007-08-15 14:28:22 +00002035WatchedFileHandler
2036^^^^^^^^^^^^^^^^^^
2037
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002038.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002039
Georg Brandl116aa622007-08-15 14:28:22 +00002040The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2041module, is a :class:`FileHandler` which watches the file it is logging to. If
2042the file changes, it is closed and reopened using the file name.
2043
2044A file change can happen because of usage of programs such as *newsyslog* and
2045*logrotate* which perform log file rotation. This handler, intended for use
2046under Unix/Linux, watches the file to see if it has changed since the last emit.
2047(A file is deemed to have changed if its device or inode have changed.) If the
2048file has changed, the old file stream is closed, and the file opened to get a
2049new stream.
2050
2051This handler is not appropriate for use under Windows, because under Windows
2052open log files cannot be moved or renamed - logging opens the files with
2053exclusive locks - and so there is no need for such a handler. Furthermore,
2054*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2055this value.
2056
2057
Christian Heimese7a15bb2008-01-24 16:21:45 +00002058.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002059
2060 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2061 file is opened and used as the stream for logging. If *mode* is not specified,
2062 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002063 with that encoding. If *delay* is true, then file opening is deferred until the
2064 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002065
2066
Benjamin Petersone41251e2008-04-25 01:59:09 +00002067 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002068
Benjamin Petersone41251e2008-04-25 01:59:09 +00002069 Outputs the record to the file, but first checks to see if the file has
2070 changed. If it has, the existing stream is flushed and closed and the
2071 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002072
Vinay Sajipd31f3632010-06-29 15:31:15 +00002073.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002074
2075RotatingFileHandler
2076^^^^^^^^^^^^^^^^^^^
2077
2078The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2079module, supports rotation of disk log files.
2080
2081
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002082.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002083
2084 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2085 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002086 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2087 with that encoding. If *delay* is true, then file opening is deferred until the
2088 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002089
2090 You can use the *maxBytes* and *backupCount* values to allow the file to
2091 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2092 the file is closed and a new file is silently opened for output. Rollover occurs
2093 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2094 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2095 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2096 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2097 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2098 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2099 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2100 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2101 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2102
2103
Benjamin Petersone41251e2008-04-25 01:59:09 +00002104 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002105
Benjamin Petersone41251e2008-04-25 01:59:09 +00002106 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002107
2108
Benjamin Petersone41251e2008-04-25 01:59:09 +00002109 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002110
Benjamin Petersone41251e2008-04-25 01:59:09 +00002111 Outputs the record to the file, catering for rollover as described
2112 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002113
Vinay Sajipd31f3632010-06-29 15:31:15 +00002114.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002115
2116TimedRotatingFileHandler
2117^^^^^^^^^^^^^^^^^^^^^^^^
2118
2119The :class:`TimedRotatingFileHandler` class, located in the
2120:mod:`logging.handlers` module, supports rotation of disk log files at certain
2121timed intervals.
2122
2123
Vinay Sajipd31f3632010-06-29 15:31:15 +00002124.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002125
2126 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2127 specified file is opened and used as the stream for logging. On rotating it also
2128 sets the filename suffix. Rotating happens based on the product of *when* and
2129 *interval*.
2130
2131 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002132 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002133
Christian Heimesb558a2e2008-03-02 22:46:37 +00002134 +----------------+-----------------------+
2135 | Value | Type of interval |
2136 +================+=======================+
2137 | ``'S'`` | Seconds |
2138 +----------------+-----------------------+
2139 | ``'M'`` | Minutes |
2140 +----------------+-----------------------+
2141 | ``'H'`` | Hours |
2142 +----------------+-----------------------+
2143 | ``'D'`` | Days |
2144 +----------------+-----------------------+
2145 | ``'W'`` | Week day (0=Monday) |
2146 +----------------+-----------------------+
2147 | ``'midnight'`` | Roll over at midnight |
2148 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002149
Christian Heimesb558a2e2008-03-02 22:46:37 +00002150 The system will save old log files by appending extensions to the filename.
2151 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002152 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002153 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002154
2155 When computing the next rollover time for the first time (when the handler
2156 is created), the last modification time of an existing log file, or else
2157 the current time, is used to compute when the next rotation will occur.
2158
Georg Brandl0c77a822008-06-10 16:37:50 +00002159 If the *utc* argument is true, times in UTC will be used; otherwise
2160 local time is used.
2161
2162 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002163 will be kept, and if more would be created when rollover occurs, the oldest
2164 one is deleted. The deletion logic uses the interval to determine which
2165 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002166
Vinay Sajipd31f3632010-06-29 15:31:15 +00002167 If *delay* is true, then file opening is deferred until the first call to
2168 :meth:`emit`.
2169
Georg Brandl116aa622007-08-15 14:28:22 +00002170
Benjamin Petersone41251e2008-04-25 01:59:09 +00002171 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002172
Benjamin Petersone41251e2008-04-25 01:59:09 +00002173 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002174
2175
Benjamin Petersone41251e2008-04-25 01:59:09 +00002176 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002177
Benjamin Petersone41251e2008-04-25 01:59:09 +00002178 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002179
2180
Vinay Sajipd31f3632010-06-29 15:31:15 +00002181.. _socket-handler:
2182
Georg Brandl116aa622007-08-15 14:28:22 +00002183SocketHandler
2184^^^^^^^^^^^^^
2185
2186The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2187sends logging output to a network socket. The base class uses a TCP socket.
2188
2189
2190.. class:: SocketHandler(host, port)
2191
2192 Returns a new instance of the :class:`SocketHandler` class intended to
2193 communicate with a remote machine whose address is given by *host* and *port*.
2194
2195
Benjamin Petersone41251e2008-04-25 01:59:09 +00002196 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002197
Benjamin Petersone41251e2008-04-25 01:59:09 +00002198 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002199
2200
Benjamin Petersone41251e2008-04-25 01:59:09 +00002201 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002202
Benjamin Petersone41251e2008-04-25 01:59:09 +00002203 Pickles the record's attribute dictionary and writes it to the socket in
2204 binary format. If there is an error with the socket, silently drops the
2205 packet. If the connection was previously lost, re-establishes the
2206 connection. To unpickle the record at the receiving end into a
2207 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002208
2209
Benjamin Petersone41251e2008-04-25 01:59:09 +00002210 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002211
Benjamin Petersone41251e2008-04-25 01:59:09 +00002212 Handles an error which has occurred during :meth:`emit`. The most likely
2213 cause is a lost connection. Closes the socket so that we can retry on the
2214 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002215
2216
Benjamin Petersone41251e2008-04-25 01:59:09 +00002217 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002218
Benjamin Petersone41251e2008-04-25 01:59:09 +00002219 This is a factory method which allows subclasses to define the precise
2220 type of socket they want. The default implementation creates a TCP socket
2221 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002222
2223
Benjamin Petersone41251e2008-04-25 01:59:09 +00002224 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002225
Benjamin Petersone41251e2008-04-25 01:59:09 +00002226 Pickles the record's attribute dictionary in binary format with a length
2227 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002228
Vinay Sajipd31f3632010-06-29 15:31:15 +00002229 Note that pickles aren't completely secure. If you are concerned about
2230 security, you may want to override this method to implement a more secure
2231 mechanism. For example, you can sign pickles using HMAC and then verify
2232 them on the receiving end, or alternatively you can disable unpickling of
2233 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002234
Benjamin Petersone41251e2008-04-25 01:59:09 +00002235 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002236
Benjamin Petersone41251e2008-04-25 01:59:09 +00002237 Send a pickled string *packet* to the socket. This function allows for
2238 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002239
2240
Vinay Sajipd31f3632010-06-29 15:31:15 +00002241.. _datagram-handler:
2242
Georg Brandl116aa622007-08-15 14:28:22 +00002243DatagramHandler
2244^^^^^^^^^^^^^^^
2245
2246The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2247module, inherits from :class:`SocketHandler` to support sending logging messages
2248over UDP sockets.
2249
2250
2251.. class:: DatagramHandler(host, port)
2252
2253 Returns a new instance of the :class:`DatagramHandler` class intended to
2254 communicate with a remote machine whose address is given by *host* and *port*.
2255
2256
Benjamin Petersone41251e2008-04-25 01:59:09 +00002257 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002258
Benjamin Petersone41251e2008-04-25 01:59:09 +00002259 Pickles the record's attribute dictionary and writes it to the socket in
2260 binary format. If there is an error with the socket, silently drops the
2261 packet. To unpickle the record at the receiving end into a
2262 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002263
2264
Benjamin Petersone41251e2008-04-25 01:59:09 +00002265 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002266
Benjamin Petersone41251e2008-04-25 01:59:09 +00002267 The factory method of :class:`SocketHandler` is here overridden to create
2268 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002269
2270
Benjamin Petersone41251e2008-04-25 01:59:09 +00002271 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002272
Benjamin Petersone41251e2008-04-25 01:59:09 +00002273 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002274
2275
Vinay Sajipd31f3632010-06-29 15:31:15 +00002276.. _syslog-handler:
2277
Georg Brandl116aa622007-08-15 14:28:22 +00002278SysLogHandler
2279^^^^^^^^^^^^^
2280
2281The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2282supports sending logging messages to a remote or local Unix syslog.
2283
2284
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002285.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002286
2287 Returns a new instance of the :class:`SysLogHandler` class intended to
2288 communicate with a remote Unix machine whose address is given by *address* in
2289 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002290 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002291 alternative to providing a ``(host, port)`` tuple is providing an address as a
2292 string, for example "/dev/log". In this case, a Unix domain socket is used to
2293 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002294 :const:`LOG_USER` is used. The type of socket opened depends on the
2295 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2296 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2297 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2298
2299 .. versionchanged:: 3.2
2300 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002301
2302
Benjamin Petersone41251e2008-04-25 01:59:09 +00002303 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002304
Benjamin Petersone41251e2008-04-25 01:59:09 +00002305 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002306
2307
Benjamin Petersone41251e2008-04-25 01:59:09 +00002308 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002309
Benjamin Petersone41251e2008-04-25 01:59:09 +00002310 The record is formatted, and then sent to the syslog server. If exception
2311 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002312
2313
Benjamin Petersone41251e2008-04-25 01:59:09 +00002314 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002315
Benjamin Petersone41251e2008-04-25 01:59:09 +00002316 Encodes the facility and priority into an integer. You can pass in strings
2317 or integers - if strings are passed, internal mapping dictionaries are
2318 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002319
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002320 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2321 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002322
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002323 **Priorities**
2324
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002325 +--------------------------+---------------+
2326 | Name (string) | Symbolic value|
2327 +==========================+===============+
2328 | ``alert`` | LOG_ALERT |
2329 +--------------------------+---------------+
2330 | ``crit`` or ``critical`` | LOG_CRIT |
2331 +--------------------------+---------------+
2332 | ``debug`` | LOG_DEBUG |
2333 +--------------------------+---------------+
2334 | ``emerg`` or ``panic`` | LOG_EMERG |
2335 +--------------------------+---------------+
2336 | ``err`` or ``error`` | LOG_ERR |
2337 +--------------------------+---------------+
2338 | ``info`` | LOG_INFO |
2339 +--------------------------+---------------+
2340 | ``notice`` | LOG_NOTICE |
2341 +--------------------------+---------------+
2342 | ``warn`` or ``warning`` | LOG_WARNING |
2343 +--------------------------+---------------+
2344
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002345 **Facilities**
2346
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002347 +---------------+---------------+
2348 | Name (string) | Symbolic value|
2349 +===============+===============+
2350 | ``auth`` | LOG_AUTH |
2351 +---------------+---------------+
2352 | ``authpriv`` | LOG_AUTHPRIV |
2353 +---------------+---------------+
2354 | ``cron`` | LOG_CRON |
2355 +---------------+---------------+
2356 | ``daemon`` | LOG_DAEMON |
2357 +---------------+---------------+
2358 | ``ftp`` | LOG_FTP |
2359 +---------------+---------------+
2360 | ``kern`` | LOG_KERN |
2361 +---------------+---------------+
2362 | ``lpr`` | LOG_LPR |
2363 +---------------+---------------+
2364 | ``mail`` | LOG_MAIL |
2365 +---------------+---------------+
2366 | ``news`` | LOG_NEWS |
2367 +---------------+---------------+
2368 | ``syslog`` | LOG_SYSLOG |
2369 +---------------+---------------+
2370 | ``user`` | LOG_USER |
2371 +---------------+---------------+
2372 | ``uucp`` | LOG_UUCP |
2373 +---------------+---------------+
2374 | ``local0`` | LOG_LOCAL0 |
2375 +---------------+---------------+
2376 | ``local1`` | LOG_LOCAL1 |
2377 +---------------+---------------+
2378 | ``local2`` | LOG_LOCAL2 |
2379 +---------------+---------------+
2380 | ``local3`` | LOG_LOCAL3 |
2381 +---------------+---------------+
2382 | ``local4`` | LOG_LOCAL4 |
2383 +---------------+---------------+
2384 | ``local5`` | LOG_LOCAL5 |
2385 +---------------+---------------+
2386 | ``local6`` | LOG_LOCAL6 |
2387 +---------------+---------------+
2388 | ``local7`` | LOG_LOCAL7 |
2389 +---------------+---------------+
2390
2391 .. method:: mapPriority(levelname)
2392
2393 Maps a logging level name to a syslog priority name.
2394 You may need to override this if you are using custom levels, or
2395 if the default algorithm is not suitable for your needs. The
2396 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2397 ``CRITICAL`` to the equivalent syslog names, and all other level
2398 names to "warning".
2399
2400.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002401
2402NTEventLogHandler
2403^^^^^^^^^^^^^^^^^
2404
2405The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2406module, supports sending logging messages to a local Windows NT, Windows 2000 or
2407Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2408extensions for Python installed.
2409
2410
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002411.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002412
2413 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2414 used to define the application name as it appears in the event log. An
2415 appropriate registry entry is created using this name. The *dllname* should give
2416 the fully qualified pathname of a .dll or .exe which contains message
2417 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2418 - this is installed with the Win32 extensions and contains some basic
2419 placeholder message definitions. Note that use of these placeholders will make
2420 your event logs big, as the entire message source is held in the log. If you
2421 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2422 contains the message definitions you want to use in the event log). The
2423 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2424 defaults to ``'Application'``.
2425
2426
Benjamin Petersone41251e2008-04-25 01:59:09 +00002427 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002428
Benjamin Petersone41251e2008-04-25 01:59:09 +00002429 At this point, you can remove the application name from the registry as a
2430 source of event log entries. However, if you do this, you will not be able
2431 to see the events as you intended in the Event Log Viewer - it needs to be
2432 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002433 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002434
2435
Benjamin Petersone41251e2008-04-25 01:59:09 +00002436 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002437
Benjamin Petersone41251e2008-04-25 01:59:09 +00002438 Determines the message ID, event category and event type, and then logs
2439 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002440
2441
Benjamin Petersone41251e2008-04-25 01:59:09 +00002442 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002443
Benjamin Petersone41251e2008-04-25 01:59:09 +00002444 Returns the event category for the record. Override this if you want to
2445 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002446
2447
Benjamin Petersone41251e2008-04-25 01:59:09 +00002448 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002449
Benjamin Petersone41251e2008-04-25 01:59:09 +00002450 Returns the event type for the record. Override this if you want to
2451 specify your own types. This version does a mapping using the handler's
2452 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2453 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2454 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2455 your own levels, you will either need to override this method or place a
2456 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002457
2458
Benjamin Petersone41251e2008-04-25 01:59:09 +00002459 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002460
Benjamin Petersone41251e2008-04-25 01:59:09 +00002461 Returns the message ID for the record. If you are using your own messages,
2462 you could do this by having the *msg* passed to the logger being an ID
2463 rather than a format string. Then, in here, you could use a dictionary
2464 lookup to get the message ID. This version returns 1, which is the base
2465 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002466
Vinay Sajipd31f3632010-06-29 15:31:15 +00002467.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002468
2469SMTPHandler
2470^^^^^^^^^^^
2471
2472The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2473supports sending logging messages to an email address via SMTP.
2474
2475
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002476.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002477
2478 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2479 initialized with the from and to addresses and subject line of the email. The
2480 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2481 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2482 the standard SMTP port is used. If your SMTP server requires authentication, you
2483 can specify a (username, password) tuple for the *credentials* argument.
2484
Georg Brandl116aa622007-08-15 14:28:22 +00002485
Benjamin Petersone41251e2008-04-25 01:59:09 +00002486 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002487
Benjamin Petersone41251e2008-04-25 01:59:09 +00002488 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002489
2490
Benjamin Petersone41251e2008-04-25 01:59:09 +00002491 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002492
Benjamin Petersone41251e2008-04-25 01:59:09 +00002493 If you want to specify a subject line which is record-dependent, override
2494 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002495
Vinay Sajipd31f3632010-06-29 15:31:15 +00002496.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002497
2498MemoryHandler
2499^^^^^^^^^^^^^
2500
2501The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2502supports buffering of logging records in memory, periodically flushing them to a
2503:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2504event of a certain severity or greater is seen.
2505
2506:class:`MemoryHandler` is a subclass of the more general
2507:class:`BufferingHandler`, which is an abstract class. This buffers logging
2508records in memory. Whenever each record is added to the buffer, a check is made
2509by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2510should, then :meth:`flush` is expected to do the needful.
2511
2512
2513.. class:: BufferingHandler(capacity)
2514
2515 Initializes the handler with a buffer of the specified capacity.
2516
2517
Benjamin Petersone41251e2008-04-25 01:59:09 +00002518 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002519
Benjamin Petersone41251e2008-04-25 01:59:09 +00002520 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2521 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002522
2523
Benjamin Petersone41251e2008-04-25 01:59:09 +00002524 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002525
Benjamin Petersone41251e2008-04-25 01:59:09 +00002526 You can override this to implement custom flushing behavior. This version
2527 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002528
2529
Benjamin Petersone41251e2008-04-25 01:59:09 +00002530 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002531
Benjamin Petersone41251e2008-04-25 01:59:09 +00002532 Returns true if the buffer is up to capacity. This method can be
2533 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002534
2535
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002536.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002537
2538 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2539 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2540 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2541 set using :meth:`setTarget` before this handler does anything useful.
2542
2543
Benjamin Petersone41251e2008-04-25 01:59:09 +00002544 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002545
Benjamin Petersone41251e2008-04-25 01:59:09 +00002546 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2547 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002548
2549
Benjamin Petersone41251e2008-04-25 01:59:09 +00002550 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002551
Benjamin Petersone41251e2008-04-25 01:59:09 +00002552 For a :class:`MemoryHandler`, flushing means just sending the buffered
2553 records to the target, if there is one. Override if you want different
2554 behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002555
2556
Benjamin Petersone41251e2008-04-25 01:59:09 +00002557 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002558
Benjamin Petersone41251e2008-04-25 01:59:09 +00002559 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002560
2561
Benjamin Petersone41251e2008-04-25 01:59:09 +00002562 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002563
Benjamin Petersone41251e2008-04-25 01:59:09 +00002564 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002565
2566
Vinay Sajipd31f3632010-06-29 15:31:15 +00002567.. _http-handler:
2568
Georg Brandl116aa622007-08-15 14:28:22 +00002569HTTPHandler
2570^^^^^^^^^^^
2571
2572The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2573supports sending logging messages to a Web server, using either ``GET`` or
2574``POST`` semantics.
2575
2576
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002577.. class:: HTTPHandler(host, url, method='GET')
Georg Brandl116aa622007-08-15 14:28:22 +00002578
2579 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2580 initialized with a host address, url and HTTP method. The *host* can be of the
2581 form ``host:port``, should you need to use a specific port number. If no
2582 *method* is specified, ``GET`` is used.
2583
2584
Benjamin Petersone41251e2008-04-25 01:59:09 +00002585 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002586
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002587 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002588
2589
Vinay Sajip121a1c42010-09-08 10:46:15 +00002590.. _queue-handler:
2591
2592
2593QueueHandler
2594^^^^^^^^^^^^
2595
2596The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
2597supports sending logging messages to a queue, such as those implemented in the
2598:mod:`queue` or :mod:`multiprocessing` modules.
2599
2600
2601.. class:: QueueHandler(queue)
2602
2603 Returns a new instance of the :class:`QueueHandler` class. The instance is
2604 initialized with the queue to send messages to.
2605
2606
2607 .. method:: emit(record)
2608
2609 Sends the record to the handler's queue.
2610
2611 .. method:: enqueue(record)
2612
2613 Enqueues the record on the queue using ``put_nowait()``; you may
2614 want to override this if you want to use blocking behaviour, or a
2615 timeout, or a customised queue implementation.
2616
2617
2618.. versionadded:: 3.2
2619
2620The :class:`QueueHandler` class was not present in previous versions.
2621
2622
Christian Heimes8b0facf2007-12-04 19:30:01 +00002623.. _formatter-objects:
2624
Georg Brandl116aa622007-08-15 14:28:22 +00002625Formatter Objects
2626-----------------
2627
Benjamin Peterson75edad02009-01-01 15:05:06 +00002628.. currentmodule:: logging
2629
Georg Brandl116aa622007-08-15 14:28:22 +00002630:class:`Formatter`\ s have the following attributes and methods. They are
2631responsible for converting a :class:`LogRecord` to (usually) a string which can
2632be interpreted by either a human or an external system. The base
2633:class:`Formatter` allows a formatting string to be specified. If none is
2634supplied, the default value of ``'%(message)s'`` is used.
2635
2636A Formatter can be initialized with a format string which makes use of knowledge
2637of the :class:`LogRecord` attributes - such as the default value mentioned above
2638making use of the fact that the user's message and arguments are pre-formatted
2639into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002640standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00002641for more information on string formatting.
2642
2643Currently, the useful mapping keys in a :class:`LogRecord` are:
2644
2645+-------------------------+-----------------------------------------------+
2646| Format | Description |
2647+=========================+===============================================+
2648| ``%(name)s`` | Name of the logger (logging channel). |
2649+-------------------------+-----------------------------------------------+
2650| ``%(levelno)s`` | Numeric logging level for the message |
2651| | (:const:`DEBUG`, :const:`INFO`, |
2652| | :const:`WARNING`, :const:`ERROR`, |
2653| | :const:`CRITICAL`). |
2654+-------------------------+-----------------------------------------------+
2655| ``%(levelname)s`` | Text logging level for the message |
2656| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2657| | ``'ERROR'``, ``'CRITICAL'``). |
2658+-------------------------+-----------------------------------------------+
2659| ``%(pathname)s`` | Full pathname of the source file where the |
2660| | logging call was issued (if available). |
2661+-------------------------+-----------------------------------------------+
2662| ``%(filename)s`` | Filename portion of pathname. |
2663+-------------------------+-----------------------------------------------+
2664| ``%(module)s`` | Module (name portion of filename). |
2665+-------------------------+-----------------------------------------------+
2666| ``%(funcName)s`` | Name of function containing the logging call. |
2667+-------------------------+-----------------------------------------------+
2668| ``%(lineno)d`` | Source line number where the logging call was |
2669| | issued (if available). |
2670+-------------------------+-----------------------------------------------+
2671| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2672| | (as returned by :func:`time.time`). |
2673+-------------------------+-----------------------------------------------+
2674| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2675| | created, relative to the time the logging |
2676| | module was loaded. |
2677+-------------------------+-----------------------------------------------+
2678| ``%(asctime)s`` | Human-readable time when the |
2679| | :class:`LogRecord` was created. By default |
2680| | this is of the form "2003-07-08 16:49:45,896" |
2681| | (the numbers after the comma are millisecond |
2682| | portion of the time). |
2683+-------------------------+-----------------------------------------------+
2684| ``%(msecs)d`` | Millisecond portion of the time when the |
2685| | :class:`LogRecord` was created. |
2686+-------------------------+-----------------------------------------------+
2687| ``%(thread)d`` | Thread ID (if available). |
2688+-------------------------+-----------------------------------------------+
2689| ``%(threadName)s`` | Thread name (if available). |
2690+-------------------------+-----------------------------------------------+
2691| ``%(process)d`` | Process ID (if available). |
2692+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00002693| ``%(processName)s`` | Process name (if available). |
2694+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002695| ``%(message)s`` | The logged message, computed as ``msg % |
2696| | args``. |
2697+-------------------------+-----------------------------------------------+
2698
Georg Brandl116aa622007-08-15 14:28:22 +00002699
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002700.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002701
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002702 Returns a new instance of the :class:`Formatter` class. The instance is
2703 initialized with a format string for the message as a whole, as well as a
2704 format string for the date/time portion of a message. If no *fmt* is
2705 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
2706 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00002707
2708
Benjamin Petersone41251e2008-04-25 01:59:09 +00002709 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002710
Benjamin Petersone41251e2008-04-25 01:59:09 +00002711 The record's attribute dictionary is used as the operand to a string
2712 formatting operation. Returns the resulting string. Before formatting the
2713 dictionary, a couple of preparatory steps are carried out. The *message*
2714 attribute of the record is computed using *msg* % *args*. If the
2715 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2716 to format the event time. If there is exception information, it is
2717 formatted using :meth:`formatException` and appended to the message. Note
2718 that the formatted exception information is cached in attribute
2719 *exc_text*. This is useful because the exception information can be
2720 pickled and sent across the wire, but you should be careful if you have
2721 more than one :class:`Formatter` subclass which customizes the formatting
2722 of exception information. In this case, you will have to clear the cached
2723 value after a formatter has done its formatting, so that the next
2724 formatter to handle the event doesn't use the cached value but
2725 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00002726
2727
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002728 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002729
Benjamin Petersone41251e2008-04-25 01:59:09 +00002730 This method should be called from :meth:`format` by a formatter which
2731 wants to make use of a formatted time. This method can be overridden in
2732 formatters to provide for any specific requirement, but the basic behavior
2733 is as follows: if *datefmt* (a string) is specified, it is used with
2734 :func:`time.strftime` to format the creation time of the
2735 record. Otherwise, the ISO8601 format is used. The resulting string is
2736 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00002737
2738
Benjamin Petersone41251e2008-04-25 01:59:09 +00002739 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00002740
Benjamin Petersone41251e2008-04-25 01:59:09 +00002741 Formats the specified exception information (a standard exception tuple as
2742 returned by :func:`sys.exc_info`) as a string. This default implementation
2743 just uses :func:`traceback.print_exception`. The resulting string is
2744 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00002745
Vinay Sajipd31f3632010-06-29 15:31:15 +00002746.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00002747
2748Filter Objects
2749--------------
2750
2751:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
2752more sophisticated filtering than is provided by levels. The base filter class
2753only allows events which are below a certain point in the logger hierarchy. For
2754example, a filter initialized with "A.B" will allow events logged by loggers
2755"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2756initialized with the empty string, all events are passed.
2757
2758
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002759.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00002760
2761 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2762 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002763 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00002764
2765
Benjamin Petersone41251e2008-04-25 01:59:09 +00002766 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002767
Benjamin Petersone41251e2008-04-25 01:59:09 +00002768 Is the specified record to be logged? Returns zero for no, nonzero for
2769 yes. If deemed appropriate, the record may be modified in-place by this
2770 method.
Georg Brandl116aa622007-08-15 14:28:22 +00002771
Vinay Sajip81010212010-08-19 19:17:41 +00002772Note that filters attached to handlers are consulted whenever an event is
2773emitted by the handler, whereas filters attached to loggers are consulted
2774whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
2775etc.) This means that events which have been generated by descendant loggers
2776will not be filtered by a logger's filter setting, unless the filter has also
2777been applied to those descendant loggers.
2778
Vinay Sajipd31f3632010-06-29 15:31:15 +00002779.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00002780
2781LogRecord Objects
2782-----------------
2783
2784:class:`LogRecord` instances are created every time something is logged. They
2785contain all the information pertinent to the event being logged. The main
2786information passed in is in msg and args, which are combined using msg % args to
2787create the message field of the record. The record also includes information
2788such as when the record was created, the source line where the logging call was
2789made, and any exception information to be logged.
2790
2791
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002792.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002793
2794 Returns an instance of :class:`LogRecord` initialized with interesting
2795 information. The *name* is the logger name; *lvl* is the numeric level;
2796 *pathname* is the absolute pathname of the source file in which the logging
2797 call was made; *lineno* is the line number in that file where the logging
2798 call is found; *msg* is the user-supplied message (a format string); *args*
2799 is the tuple which, together with *msg*, makes up the user message; and
2800 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2801 (or :const:`None`, if no exception information is available). The *func* is
2802 the name of the function from which the logging call was made. If not
2803 specified, it defaults to ``None``.
2804
Georg Brandl116aa622007-08-15 14:28:22 +00002805
Benjamin Petersone41251e2008-04-25 01:59:09 +00002806 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00002807
Benjamin Petersone41251e2008-04-25 01:59:09 +00002808 Returns the message for this :class:`LogRecord` instance after merging any
2809 user-supplied arguments with the message.
2810
Vinay Sajipd31f3632010-06-29 15:31:15 +00002811.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00002812
Christian Heimes04c420f2008-01-18 18:40:46 +00002813LoggerAdapter Objects
2814---------------------
2815
Christian Heimes04c420f2008-01-18 18:40:46 +00002816:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00002817information into logging calls. For a usage example , see the section on
2818`adding contextual information to your logging output`__.
2819
2820__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00002821
2822.. class:: LoggerAdapter(logger, extra)
2823
2824 Returns an instance of :class:`LoggerAdapter` initialized with an
2825 underlying :class:`Logger` instance and a dict-like object.
2826
Benjamin Petersone41251e2008-04-25 01:59:09 +00002827 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00002828
Benjamin Petersone41251e2008-04-25 01:59:09 +00002829 Modifies the message and/or keyword arguments passed to a logging call in
2830 order to insert contextual information. This implementation takes the object
2831 passed as *extra* to the constructor and adds it to *kwargs* using key
2832 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2833 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00002834
2835In addition to the above, :class:`LoggerAdapter` supports all the logging
2836methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2837:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2838methods have the same signatures as their counterparts in :class:`Logger`, so
2839you can use the two types of instances interchangeably.
2840
Ezio Melotti4d5195b2010-04-20 10:57:44 +00002841.. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00002842 The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This
2843 method delegates to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002844
Georg Brandl116aa622007-08-15 14:28:22 +00002845
2846Thread Safety
2847-------------
2848
2849The logging module is intended to be thread-safe without any special work
2850needing to be done by its clients. It achieves this though using threading
2851locks; there is one lock to serialize access to the module's shared data, and
2852each handler also creates a lock to serialize access to its underlying I/O.
2853
Benjamin Petersond23f8222009-04-05 19:13:16 +00002854If you are implementing asynchronous signal handlers using the :mod:`signal`
2855module, you may not be able to use logging from within such handlers. This is
2856because lock implementations in the :mod:`threading` module are not always
2857re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00002858
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002859
2860Integration with the warnings module
2861------------------------------------
2862
2863The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2864with the :mod:`warnings` module.
2865
2866.. function:: captureWarnings(capture)
2867
2868 This function is used to turn the capture of warnings by logging on and
2869 off.
2870
2871 If `capture` is `True`, warnings issued by the :mod:`warnings` module
2872 will be redirected to the logging system. Specifically, a warning will be
2873 formatted using :func:`warnings.formatwarning` and the resulting string
2874 logged to a logger named "py.warnings" with a severity of `WARNING`.
2875
2876 If `capture` is `False`, the redirection of warnings to the logging system
2877 will stop, and warnings will be redirected to their original destinations
2878 (i.e. those in effect before `captureWarnings(True)` was called).
2879
2880
Georg Brandl116aa622007-08-15 14:28:22 +00002881Configuration
2882-------------
2883
2884
2885.. _logging-config-api:
2886
2887Configuration functions
2888^^^^^^^^^^^^^^^^^^^^^^^
2889
Georg Brandl116aa622007-08-15 14:28:22 +00002890The following functions configure the logging module. They are located in the
2891:mod:`logging.config` module. Their use is optional --- you can configure the
2892logging module using these functions or by making calls to the main API (defined
2893in :mod:`logging` itself) and defining handlers which are declared either in
2894:mod:`logging` or :mod:`logging.handlers`.
2895
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002896.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00002897
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002898 Takes the logging configuration from a dictionary. The contents of
2899 this dictionary are described in :ref:`logging-config-dictschema`
2900 below.
2901
2902 If an error is encountered during configuration, this function will
2903 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2904 or :exc:`ImportError` with a suitably descriptive message. The
2905 following is a (possibly incomplete) list of conditions which will
2906 raise an error:
2907
2908 * A ``level`` which is not a string or which is a string not
2909 corresponding to an actual logging level.
2910 * A ``propagate`` value which is not a boolean.
2911 * An id which does not have a corresponding destination.
2912 * A non-existent handler id found during an incremental call.
2913 * An invalid logger name.
2914 * Inability to resolve to an internal or external object.
2915
2916 Parsing is performed by the :class:`DictConfigurator` class, whose
2917 constructor is passed the dictionary used for configuration, and
2918 has a :meth:`configure` method. The :mod:`logging.config` module
2919 has a callable attribute :attr:`dictConfigClass`
2920 which is initially set to :class:`DictConfigurator`.
2921 You can replace the value of :attr:`dictConfigClass` with a
2922 suitable implementation of your own.
2923
2924 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2925 the specified dictionary, and then calls the :meth:`configure` method on
2926 the returned object to put the configuration into effect::
2927
2928 def dictConfig(config):
2929 dictConfigClass(config).configure()
2930
2931 For example, a subclass of :class:`DictConfigurator` could call
2932 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2933 set up custom prefixes which would be usable in the subsequent
2934 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2935 this new subclass, and then :func:`dictConfig` could be called exactly as
2936 in the default, uncustomized state.
2937
2938.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00002939
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00002940 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002941 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002942 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00002943 configurations (if the developer provides a mechanism to present the choices
2944 and load the chosen configuration). Defaults to be passed to the ConfigParser
2945 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00002946
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002947
2948.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00002949
2950 Starts up a socket server on the specified port, and listens for new
2951 configurations. If no port is specified, the module's default
2952 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2953 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2954 :class:`Thread` instance on which you can call :meth:`start` to start the
2955 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00002956 call :func:`stopListening`.
2957
2958 To send a configuration to the socket, read in the configuration file and
2959 send it to the socket as a string of bytes preceded by a four-byte length
2960 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002961
2962
2963.. function:: stopListening()
2964
Christian Heimes8b0facf2007-12-04 19:30:01 +00002965 Stops the listening server which was created with a call to :func:`listen`.
2966 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00002967 :func:`listen`.
2968
2969
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002970.. _logging-config-dictschema:
2971
2972Configuration dictionary schema
2973^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2974
2975Describing a logging configuration requires listing the various
2976objects to create and the connections between them; for example, you
2977may create a handler named "console" and then say that the logger
2978named "startup" will send its messages to the "console" handler.
2979These objects aren't limited to those provided by the :mod:`logging`
2980module because you might write your own formatter or handler class.
2981The parameters to these classes may also need to include external
2982objects such as ``sys.stderr``. The syntax for describing these
2983objects and connections is defined in :ref:`logging-config-dict-connections`
2984below.
2985
2986Dictionary Schema Details
2987"""""""""""""""""""""""""
2988
2989The dictionary passed to :func:`dictConfig` must contain the following
2990keys:
2991
2992* `version` - to be set to an integer value representing the schema
2993 version. The only valid value at present is 1, but having this key
2994 allows the schema to evolve while still preserving backwards
2995 compatibility.
2996
2997All other keys are optional, but if present they will be interpreted
2998as described below. In all cases below where a 'configuring dict' is
2999mentioned, it will be checked for the special ``'()'`` key to see if a
3000custom instantiation is required. If so, the mechanism described in
3001:ref:`logging-config-dict-userdef` below is used to create an instance;
3002otherwise, the context is used to determine what to instantiate.
3003
3004* `formatters` - the corresponding value will be a dict in which each
3005 key is a formatter id and each value is a dict describing how to
3006 configure the corresponding Formatter instance.
3007
3008 The configuring dict is searched for keys ``format`` and ``datefmt``
3009 (with defaults of ``None``) and these are used to construct a
3010 :class:`logging.Formatter` instance.
3011
3012* `filters` - the corresponding value will be a dict in which each key
3013 is a filter id and each value is a dict describing how to configure
3014 the corresponding Filter instance.
3015
3016 The configuring dict is searched for the key ``name`` (defaulting to the
3017 empty string) and this is used to construct a :class:`logging.Filter`
3018 instance.
3019
3020* `handlers` - the corresponding value will be a dict in which each
3021 key is a handler id and each value is a dict describing how to
3022 configure the corresponding Handler instance.
3023
3024 The configuring dict is searched for the following keys:
3025
3026 * ``class`` (mandatory). This is the fully qualified name of the
3027 handler class.
3028
3029 * ``level`` (optional). The level of the handler.
3030
3031 * ``formatter`` (optional). The id of the formatter for this
3032 handler.
3033
3034 * ``filters`` (optional). A list of ids of the filters for this
3035 handler.
3036
3037 All *other* keys are passed through as keyword arguments to the
3038 handler's constructor. For example, given the snippet::
3039
3040 handlers:
3041 console:
3042 class : logging.StreamHandler
3043 formatter: brief
3044 level : INFO
3045 filters: [allow_foo]
3046 stream : ext://sys.stdout
3047 file:
3048 class : logging.handlers.RotatingFileHandler
3049 formatter: precise
3050 filename: logconfig.log
3051 maxBytes: 1024
3052 backupCount: 3
3053
3054 the handler with id ``console`` is instantiated as a
3055 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3056 stream. The handler with id ``file`` is instantiated as a
3057 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3058 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3059
3060* `loggers` - the corresponding value will be a dict in which each key
3061 is a logger name and each value is a dict describing how to
3062 configure the corresponding Logger instance.
3063
3064 The configuring dict is searched for the following keys:
3065
3066 * ``level`` (optional). The level of the logger.
3067
3068 * ``propagate`` (optional). The propagation setting of the logger.
3069
3070 * ``filters`` (optional). A list of ids of the filters for this
3071 logger.
3072
3073 * ``handlers`` (optional). A list of ids of the handlers for this
3074 logger.
3075
3076 The specified loggers will be configured according to the level,
3077 propagation, filters and handlers specified.
3078
3079* `root` - this will be the configuration for the root logger.
3080 Processing of the configuration will be as for any logger, except
3081 that the ``propagate`` setting will not be applicable.
3082
3083* `incremental` - whether the configuration is to be interpreted as
3084 incremental to the existing configuration. This value defaults to
3085 ``False``, which means that the specified configuration replaces the
3086 existing configuration with the same semantics as used by the
3087 existing :func:`fileConfig` API.
3088
3089 If the specified value is ``True``, the configuration is processed
3090 as described in the section on :ref:`logging-config-dict-incremental`.
3091
3092* `disable_existing_loggers` - whether any existing loggers are to be
3093 disabled. This setting mirrors the parameter of the same name in
3094 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
3095 This value is ignored if `incremental` is ``True``.
3096
3097.. _logging-config-dict-incremental:
3098
3099Incremental Configuration
3100"""""""""""""""""""""""""
3101
3102It is difficult to provide complete flexibility for incremental
3103configuration. For example, because objects such as filters
3104and formatters are anonymous, once a configuration is set up, it is
3105not possible to refer to such anonymous objects when augmenting a
3106configuration.
3107
3108Furthermore, there is not a compelling case for arbitrarily altering
3109the object graph of loggers, handlers, filters, formatters at
3110run-time, once a configuration is set up; the verbosity of loggers and
3111handlers can be controlled just by setting levels (and, in the case of
3112loggers, propagation flags). Changing the object graph arbitrarily in
3113a safe way is problematic in a multi-threaded environment; while not
3114impossible, the benefits are not worth the complexity it adds to the
3115implementation.
3116
3117Thus, when the ``incremental`` key of a configuration dict is present
3118and is ``True``, the system will completely ignore any ``formatters`` and
3119``filters`` entries, and process only the ``level``
3120settings in the ``handlers`` entries, and the ``level`` and
3121``propagate`` settings in the ``loggers`` and ``root`` entries.
3122
3123Using a value in the configuration dict lets configurations to be sent
3124over the wire as pickled dicts to a socket listener. Thus, the logging
3125verbosity of a long-running application can be altered over time with
3126no need to stop and restart the application.
3127
3128.. _logging-config-dict-connections:
3129
3130Object connections
3131""""""""""""""""""
3132
3133The schema describes a set of logging objects - loggers,
3134handlers, formatters, filters - which are connected to each other in
3135an object graph. Thus, the schema needs to represent connections
3136between the objects. For example, say that, once configured, a
3137particular logger has attached to it a particular handler. For the
3138purposes of this discussion, we can say that the logger represents the
3139source, and the handler the destination, of a connection between the
3140two. Of course in the configured objects this is represented by the
3141logger holding a reference to the handler. In the configuration dict,
3142this is done by giving each destination object an id which identifies
3143it unambiguously, and then using the id in the source object's
3144configuration to indicate that a connection exists between the source
3145and the destination object with that id.
3146
3147So, for example, consider the following YAML snippet::
3148
3149 formatters:
3150 brief:
3151 # configuration for formatter with id 'brief' goes here
3152 precise:
3153 # configuration for formatter with id 'precise' goes here
3154 handlers:
3155 h1: #This is an id
3156 # configuration of handler with id 'h1' goes here
3157 formatter: brief
3158 h2: #This is another id
3159 # configuration of handler with id 'h2' goes here
3160 formatter: precise
3161 loggers:
3162 foo.bar.baz:
3163 # other configuration for logger 'foo.bar.baz'
3164 handlers: [h1, h2]
3165
3166(Note: YAML used here because it's a little more readable than the
3167equivalent Python source form for the dictionary.)
3168
3169The ids for loggers are the logger names which would be used
3170programmatically to obtain a reference to those loggers, e.g.
3171``foo.bar.baz``. The ids for Formatters and Filters can be any string
3172value (such as ``brief``, ``precise`` above) and they are transient,
3173in that they are only meaningful for processing the configuration
3174dictionary and used to determine connections between objects, and are
3175not persisted anywhere when the configuration call is complete.
3176
3177The above snippet indicates that logger named ``foo.bar.baz`` should
3178have two handlers attached to it, which are described by the handler
3179ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3180``brief``, and the formatter for ``h2`` is that described by id
3181``precise``.
3182
3183
3184.. _logging-config-dict-userdef:
3185
3186User-defined objects
3187""""""""""""""""""""
3188
3189The schema supports user-defined objects for handlers, filters and
3190formatters. (Loggers do not need to have different types for
3191different instances, so there is no support in this configuration
3192schema for user-defined logger classes.)
3193
3194Objects to be configured are described by dictionaries
3195which detail their configuration. In some places, the logging system
3196will be able to infer from the context how an object is to be
3197instantiated, but when a user-defined object is to be instantiated,
3198the system will not know how to do this. In order to provide complete
3199flexibility for user-defined object instantiation, the user needs
3200to provide a 'factory' - a callable which is called with a
3201configuration dictionary and which returns the instantiated object.
3202This is signalled by an absolute import path to the factory being
3203made available under the special key ``'()'``. Here's a concrete
3204example::
3205
3206 formatters:
3207 brief:
3208 format: '%(message)s'
3209 default:
3210 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3211 datefmt: '%Y-%m-%d %H:%M:%S'
3212 custom:
3213 (): my.package.customFormatterFactory
3214 bar: baz
3215 spam: 99.9
3216 answer: 42
3217
3218The above YAML snippet defines three formatters. The first, with id
3219``brief``, is a standard :class:`logging.Formatter` instance with the
3220specified format string. The second, with id ``default``, has a
3221longer format and also defines the time format explicitly, and will
3222result in a :class:`logging.Formatter` initialized with those two format
3223strings. Shown in Python source form, the ``brief`` and ``default``
3224formatters have configuration sub-dictionaries::
3225
3226 {
3227 'format' : '%(message)s'
3228 }
3229
3230and::
3231
3232 {
3233 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3234 'datefmt' : '%Y-%m-%d %H:%M:%S'
3235 }
3236
3237respectively, and as these dictionaries do not contain the special key
3238``'()'``, the instantiation is inferred from the context: as a result,
3239standard :class:`logging.Formatter` instances are created. The
3240configuration sub-dictionary for the third formatter, with id
3241``custom``, is::
3242
3243 {
3244 '()' : 'my.package.customFormatterFactory',
3245 'bar' : 'baz',
3246 'spam' : 99.9,
3247 'answer' : 42
3248 }
3249
3250and this contains the special key ``'()'``, which means that
3251user-defined instantiation is wanted. In this case, the specified
3252factory callable will be used. If it is an actual callable it will be
3253used directly - otherwise, if you specify a string (as in the example)
3254the actual callable will be located using normal import mechanisms.
3255The callable will be called with the **remaining** items in the
3256configuration sub-dictionary as keyword arguments. In the above
3257example, the formatter with id ``custom`` will be assumed to be
3258returned by the call::
3259
3260 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3261
3262The key ``'()'`` has been used as the special key because it is not a
3263valid keyword parameter name, and so will not clash with the names of
3264the keyword arguments used in the call. The ``'()'`` also serves as a
3265mnemonic that the corresponding value is a callable.
3266
3267
3268.. _logging-config-dict-externalobj:
3269
3270Access to external objects
3271""""""""""""""""""""""""""
3272
3273There are times where a configuration needs to refer to objects
3274external to the configuration, for example ``sys.stderr``. If the
3275configuration dict is constructed using Python code, this is
3276straightforward, but a problem arises when the configuration is
3277provided via a text file (e.g. JSON, YAML). In a text file, there is
3278no standard way to distinguish ``sys.stderr`` from the literal string
3279``'sys.stderr'``. To facilitate this distinction, the configuration
3280system looks for certain special prefixes in string values and
3281treat them specially. For example, if the literal string
3282``'ext://sys.stderr'`` is provided as a value in the configuration,
3283then the ``ext://`` will be stripped off and the remainder of the
3284value processed using normal import mechanisms.
3285
3286The handling of such prefixes is done in a way analogous to protocol
3287handling: there is a generic mechanism to look for prefixes which
3288match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3289whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3290in a prefix-dependent manner and the result of the processing replaces
3291the string value. If the prefix is not recognised, then the string
3292value will be left as-is.
3293
3294
3295.. _logging-config-dict-internalobj:
3296
3297Access to internal objects
3298""""""""""""""""""""""""""
3299
3300As well as external objects, there is sometimes also a need to refer
3301to objects in the configuration. This will be done implicitly by the
3302configuration system for things that it knows about. For example, the
3303string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3304automatically be converted to the value ``logging.DEBUG``, and the
3305``handlers``, ``filters`` and ``formatter`` entries will take an
3306object id and resolve to the appropriate destination object.
3307
3308However, a more generic mechanism is needed for user-defined
3309objects which are not known to the :mod:`logging` module. For
3310example, consider :class:`logging.handlers.MemoryHandler`, which takes
3311a ``target`` argument which is another handler to delegate to. Since
3312the system already knows about this class, then in the configuration,
3313the given ``target`` just needs to be the object id of the relevant
3314target handler, and the system will resolve to the handler from the
3315id. If, however, a user defines a ``my.package.MyHandler`` which has
3316an ``alternate`` handler, the configuration system would not know that
3317the ``alternate`` referred to a handler. To cater for this, a generic
3318resolution system allows the user to specify::
3319
3320 handlers:
3321 file:
3322 # configuration of file handler goes here
3323
3324 custom:
3325 (): my.package.MyHandler
3326 alternate: cfg://handlers.file
3327
3328The literal string ``'cfg://handlers.file'`` will be resolved in an
3329analogous way to strings with the ``ext://`` prefix, but looking
3330in the configuration itself rather than the import namespace. The
3331mechanism allows access by dot or by index, in a similar way to
3332that provided by ``str.format``. Thus, given the following snippet::
3333
3334 handlers:
3335 email:
3336 class: logging.handlers.SMTPHandler
3337 mailhost: localhost
3338 fromaddr: my_app@domain.tld
3339 toaddrs:
3340 - support_team@domain.tld
3341 - dev_team@domain.tld
3342 subject: Houston, we have a problem.
3343
3344in the configuration, the string ``'cfg://handlers'`` would resolve to
3345the dict with key ``handlers``, the string ``'cfg://handlers.email``
3346would resolve to the dict with key ``email`` in the ``handlers`` dict,
3347and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3348resolve to ``'dev_team.domain.tld'`` and the string
3349``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3350``'support_team@domain.tld'``. The ``subject`` value could be accessed
3351using either ``'cfg://handlers.email.subject'`` or, equivalently,
3352``'cfg://handlers.email[subject]'``. The latter form only needs to be
3353used if the key contains spaces or non-alphanumeric characters. If an
3354index value consists only of decimal digits, access will be attempted
3355using the corresponding integer value, falling back to the string
3356value if needed.
3357
3358Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3359resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3360If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3361the system will attempt to retrieve the value from
3362``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3363to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3364fails.
3365
Georg Brandl116aa622007-08-15 14:28:22 +00003366.. _logging-config-fileformat:
3367
3368Configuration file format
3369^^^^^^^^^^^^^^^^^^^^^^^^^
3370
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003371The configuration file format understood by :func:`fileConfig` is based on
3372:mod:`configparser` functionality. The file must contain sections called
3373``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3374entities of each type which are defined in the file. For each such entity, there
3375is a separate section which identifies how that entity is configured. Thus, for
3376a logger named ``log01`` in the ``[loggers]`` section, the relevant
3377configuration details are held in a section ``[logger_log01]``. Similarly, a
3378handler called ``hand01`` in the ``[handlers]`` section will have its
3379configuration held in a section called ``[handler_hand01]``, while a formatter
3380called ``form01`` in the ``[formatters]`` section will have its configuration
3381specified in a section called ``[formatter_form01]``. The root logger
3382configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003383
3384Examples of these sections in the file are given below. ::
3385
3386 [loggers]
3387 keys=root,log02,log03,log04,log05,log06,log07
3388
3389 [handlers]
3390 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3391
3392 [formatters]
3393 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3394
3395The root logger must specify a level and a list of handlers. An example of a
3396root logger section is given below. ::
3397
3398 [logger_root]
3399 level=NOTSET
3400 handlers=hand01
3401
3402The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3403``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3404logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3405package's namespace.
3406
3407The ``handlers`` entry is a comma-separated list of handler names, which must
3408appear in the ``[handlers]`` section. These names must appear in the
3409``[handlers]`` section and have corresponding sections in the configuration
3410file.
3411
3412For loggers other than the root logger, some additional information is required.
3413This is illustrated by the following example. ::
3414
3415 [logger_parser]
3416 level=DEBUG
3417 handlers=hand01
3418 propagate=1
3419 qualname=compiler.parser
3420
3421The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3422except that if a non-root logger's level is specified as ``NOTSET``, the system
3423consults loggers higher up the hierarchy to determine the effective level of the
3424logger. The ``propagate`` entry is set to 1 to indicate that messages must
3425propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3426indicate that messages are **not** propagated to handlers up the hierarchy. The
3427``qualname`` entry is the hierarchical channel name of the logger, that is to
3428say the name used by the application to get the logger.
3429
3430Sections which specify handler configuration are exemplified by the following.
3431::
3432
3433 [handler_hand01]
3434 class=StreamHandler
3435 level=NOTSET
3436 formatter=form01
3437 args=(sys.stdout,)
3438
3439The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3440in the ``logging`` package's namespace). The ``level`` is interpreted as for
3441loggers, and ``NOTSET`` is taken to mean "log everything".
3442
3443The ``formatter`` entry indicates the key name of the formatter for this
3444handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3445If a name is specified, it must appear in the ``[formatters]`` section and have
3446a corresponding section in the configuration file.
3447
3448The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3449package's namespace, is the list of arguments to the constructor for the handler
3450class. Refer to the constructors for the relevant handlers, or to the examples
3451below, to see how typical entries are constructed. ::
3452
3453 [handler_hand02]
3454 class=FileHandler
3455 level=DEBUG
3456 formatter=form02
3457 args=('python.log', 'w')
3458
3459 [handler_hand03]
3460 class=handlers.SocketHandler
3461 level=INFO
3462 formatter=form03
3463 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3464
3465 [handler_hand04]
3466 class=handlers.DatagramHandler
3467 level=WARN
3468 formatter=form04
3469 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3470
3471 [handler_hand05]
3472 class=handlers.SysLogHandler
3473 level=ERROR
3474 formatter=form05
3475 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3476
3477 [handler_hand06]
3478 class=handlers.NTEventLogHandler
3479 level=CRITICAL
3480 formatter=form06
3481 args=('Python Application', '', 'Application')
3482
3483 [handler_hand07]
3484 class=handlers.SMTPHandler
3485 level=WARN
3486 formatter=form07
3487 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3488
3489 [handler_hand08]
3490 class=handlers.MemoryHandler
3491 level=NOTSET
3492 formatter=form08
3493 target=
3494 args=(10, ERROR)
3495
3496 [handler_hand09]
3497 class=handlers.HTTPHandler
3498 level=NOTSET
3499 formatter=form09
3500 args=('localhost:9022', '/log', 'GET')
3501
3502Sections which specify formatter configuration are typified by the following. ::
3503
3504 [formatter_form01]
3505 format=F1 %(asctime)s %(levelname)s %(message)s
3506 datefmt=
3507 class=logging.Formatter
3508
3509The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003510the :func:`strftime`\ -compatible date/time format string. If empty, the
3511package substitutes ISO8601 format date/times, which is almost equivalent to
3512specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3513also specifies milliseconds, which are appended to the result of using the above
3514format string, with a comma separator. An example time in ISO8601 format is
3515``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00003516
3517The ``class`` entry is optional. It indicates the name of the formatter's class
3518(as a dotted module and class name.) This option is useful for instantiating a
3519:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3520exception tracebacks in an expanded or condensed format.
3521
Christian Heimes8b0facf2007-12-04 19:30:01 +00003522
3523Configuration server example
3524^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3525
3526Here is an example of a module using the logging configuration server::
3527
3528 import logging
3529 import logging.config
3530 import time
3531 import os
3532
3533 # read initial config file
3534 logging.config.fileConfig("logging.conf")
3535
3536 # create and start listener on port 9999
3537 t = logging.config.listen(9999)
3538 t.start()
3539
3540 logger = logging.getLogger("simpleExample")
3541
3542 try:
3543 # loop through logging calls to see the difference
3544 # new configurations make, until Ctrl+C is pressed
3545 while True:
3546 logger.debug("debug message")
3547 logger.info("info message")
3548 logger.warn("warn message")
3549 logger.error("error message")
3550 logger.critical("critical message")
3551 time.sleep(5)
3552 except KeyboardInterrupt:
3553 # cleanup
3554 logging.config.stopListening()
3555 t.join()
3556
3557And here is a script that takes a filename and sends that file to the server,
3558properly preceded with the binary-encoded length, as the new logging
3559configuration::
3560
3561 #!/usr/bin/env python
3562 import socket, sys, struct
3563
3564 data_to_send = open(sys.argv[1], "r").read()
3565
3566 HOST = 'localhost'
3567 PORT = 9999
3568 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00003569 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003570 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00003571 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003572 s.send(struct.pack(">L", len(data_to_send)))
3573 s.send(data_to_send)
3574 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00003575 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003576
3577
3578More examples
3579-------------
3580
3581Multiple handlers and formatters
3582^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3583
3584Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3585or maximum quota for the number of handlers you may add. Sometimes it will be
3586beneficial for an application to log all messages of all severities to a text
3587file while simultaneously logging errors or above to the console. To set this
3588up, simply configure the appropriate handlers. The logging calls in the
3589application code will remain unchanged. Here is a slight modification to the
3590previous simple module-based configuration example::
3591
3592 import logging
3593
3594 logger = logging.getLogger("simple_example")
3595 logger.setLevel(logging.DEBUG)
3596 # create file handler which logs even debug messages
3597 fh = logging.FileHandler("spam.log")
3598 fh.setLevel(logging.DEBUG)
3599 # create console handler with a higher log level
3600 ch = logging.StreamHandler()
3601 ch.setLevel(logging.ERROR)
3602 # create formatter and add it to the handlers
3603 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3604 ch.setFormatter(formatter)
3605 fh.setFormatter(formatter)
3606 # add the handlers to logger
3607 logger.addHandler(ch)
3608 logger.addHandler(fh)
3609
3610 # "application" code
3611 logger.debug("debug message")
3612 logger.info("info message")
3613 logger.warn("warn message")
3614 logger.error("error message")
3615 logger.critical("critical message")
3616
3617Notice that the "application" code does not care about multiple handlers. All
3618that changed was the addition and configuration of a new handler named *fh*.
3619
3620The ability to create new handlers with higher- or lower-severity filters can be
3621very helpful when writing and testing an application. Instead of using many
3622``print`` statements for debugging, use ``logger.debug``: Unlike the print
3623statements, which you will have to delete or comment out later, the logger.debug
3624statements can remain intact in the source code and remain dormant until you
3625need them again. At that time, the only change that needs to happen is to
3626modify the severity level of the logger and/or handler to debug.
3627
3628
3629Using logging in multiple modules
3630^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3631
3632It was mentioned above that multiple calls to
3633``logging.getLogger('someLogger')`` return a reference to the same logger
3634object. This is true not only within the same module, but also across modules
3635as long as it is in the same Python interpreter process. It is true for
3636references to the same object; additionally, application code can define and
3637configure a parent logger in one module and create (but not configure) a child
3638logger in a separate module, and all logger calls to the child will pass up to
3639the parent. Here is a main module::
3640
3641 import logging
3642 import auxiliary_module
3643
3644 # create logger with "spam_application"
3645 logger = logging.getLogger("spam_application")
3646 logger.setLevel(logging.DEBUG)
3647 # create file handler which logs even debug messages
3648 fh = logging.FileHandler("spam.log")
3649 fh.setLevel(logging.DEBUG)
3650 # create console handler with a higher log level
3651 ch = logging.StreamHandler()
3652 ch.setLevel(logging.ERROR)
3653 # create formatter and add it to the handlers
3654 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3655 fh.setFormatter(formatter)
3656 ch.setFormatter(formatter)
3657 # add the handlers to the logger
3658 logger.addHandler(fh)
3659 logger.addHandler(ch)
3660
3661 logger.info("creating an instance of auxiliary_module.Auxiliary")
3662 a = auxiliary_module.Auxiliary()
3663 logger.info("created an instance of auxiliary_module.Auxiliary")
3664 logger.info("calling auxiliary_module.Auxiliary.do_something")
3665 a.do_something()
3666 logger.info("finished auxiliary_module.Auxiliary.do_something")
3667 logger.info("calling auxiliary_module.some_function()")
3668 auxiliary_module.some_function()
3669 logger.info("done with auxiliary_module.some_function()")
3670
3671Here is the auxiliary module::
3672
3673 import logging
3674
3675 # create logger
3676 module_logger = logging.getLogger("spam_application.auxiliary")
3677
3678 class Auxiliary:
3679 def __init__(self):
3680 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3681 self.logger.info("creating an instance of Auxiliary")
3682 def do_something(self):
3683 self.logger.info("doing something")
3684 a = 1 + 1
3685 self.logger.info("done doing something")
3686
3687 def some_function():
3688 module_logger.info("received a call to \"some_function\"")
3689
3690The output looks like this::
3691
Christian Heimes043d6f62008-01-07 17:19:16 +00003692 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003693 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00003694 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003695 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00003696 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003697 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00003698 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003699 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00003700 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003701 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00003702 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003703 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00003704 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003705 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00003706 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003707 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00003708 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003709 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00003710 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003711 done with auxiliary_module.some_function()
3712