blob: 342762406584115b66f53d37719f6086fbb93de5 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandl8ec7f652007-08-15 14:28:01 +000012.. index:: pair: Errors; logging
13
14.. versionadded:: 2.3
15
16This module defines functions and classes which implement a flexible error
17logging system for applications.
18
19Logging is performed by calling methods on instances of the :class:`Logger`
20class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandla7395032007-10-21 12:15:05 +000021conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl8ec7f652007-08-15 14:28:01 +000022separators. For example, a logger named "scan" is the parent of loggers
23"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
24and indicate the area of an application in which a logged message originates.
25
26Logged messages also have levels of importance associated with them. The default
27levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
28:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
29importance of a logged message by calling an appropriate method of
30:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
31:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
32constrained to use these levels: you can specify your own and use a more general
33:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
34
Georg Brandlc37f2882007-12-04 17:46:27 +000035
36Logging tutorial
37----------------
38
39The key benefit of having the logging API provided by a standard library module
40is that all Python modules can participate in logging, so your application log
41can include messages from third-party modules.
42
43It is, of course, possible to log messages with different verbosity levels or to
44different destinations. Support for writing log messages to files, HTTP
45GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Georg Brandl907a7202008-02-22 12:31:45 +000046mechanisms are all supported by the standard module. You can also create your
Georg Brandlc37f2882007-12-04 17:46:27 +000047own log destination class if you have special requirements not met by any of the
48built-in classes.
49
50Simple examples
51^^^^^^^^^^^^^^^
52
53.. sectionauthor:: Doug Hellmann
54.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
55
56Most applications are probably going to want to log to a file, so let's start
57with that case. Using the :func:`basicConfig` function, we can set up the
Vinay Sajip9a26aab2010-06-03 22:34:42 +000058default handler so that debug messages are written to a file (in the example,
59we assume that you have the appropriate permissions to create a file called
Vinay Sajip998cc242010-06-04 13:41:02 +000060*example.log* in the current directory)::
Georg Brandlc37f2882007-12-04 17:46:27 +000061
62 import logging
Vinay Sajip9a26aab2010-06-03 22:34:42 +000063 LOG_FILENAME = 'example.log'
Vinay Sajipf778bec2009-09-22 17:23:41 +000064 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Georg Brandlc37f2882007-12-04 17:46:27 +000065
66 logging.debug('This message should go to the log file')
67
68And now if we open the file and look at what we have, we should find the log
69message::
70
71 DEBUG:root:This message should go to the log file
72
73If you run the script repeatedly, the additional log messages are appended to
Eric Smithe7dbebb2009-06-04 17:58:15 +000074the file. To create a new file each time, you can pass a *filemode* argument to
Georg Brandlc37f2882007-12-04 17:46:27 +000075:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
76yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
77
78 import glob
79 import logging
80 import logging.handlers
81
Vinay Sajip998cc242010-06-04 13:41:02 +000082 LOG_FILENAME = 'logging_rotatingfile_example.out'
Georg Brandlc37f2882007-12-04 17:46:27 +000083
84 # Set up a specific logger with our desired output level
85 my_logger = logging.getLogger('MyLogger')
86 my_logger.setLevel(logging.DEBUG)
87
88 # Add the log message handler to the logger
89 handler = logging.handlers.RotatingFileHandler(
90 LOG_FILENAME, maxBytes=20, backupCount=5)
91
92 my_logger.addHandler(handler)
93
94 # Log some messages
95 for i in range(20):
96 my_logger.debug('i = %d' % i)
97
98 # See what files are created
99 logfiles = glob.glob('%s*' % LOG_FILENAME)
100
101 for filename in logfiles:
102 print filename
103
104The result should be 6 separate files, each with part of the log history for the
105application::
106
Vinay Sajip998cc242010-06-04 13:41:02 +0000107 logging_rotatingfile_example.out
108 logging_rotatingfile_example.out.1
109 logging_rotatingfile_example.out.2
110 logging_rotatingfile_example.out.3
111 logging_rotatingfile_example.out.4
112 logging_rotatingfile_example.out.5
Georg Brandlc37f2882007-12-04 17:46:27 +0000113
Vinay Sajip998cc242010-06-04 13:41:02 +0000114The most current file is always :file:`logging_rotatingfile_example.out`,
Georg Brandlc37f2882007-12-04 17:46:27 +0000115and each time it reaches the size limit it is renamed with the suffix
116``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smithe7dbebb2009-06-04 17:58:15 +0000117(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Georg Brandlc37f2882007-12-04 17:46:27 +0000118
119Obviously this example sets the log length much much too small as an extreme
120example. You would want to set *maxBytes* to an appropriate value.
121
122Another useful feature of the logging API is the ability to produce different
123messages at different log levels. This allows you to instrument your code with
124debug messages, for example, but turning the log level down so that those debug
125messages are not written for your production system. The default levels are
Vinay Sajipa7d44002009-10-28 23:28:16 +0000126``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Georg Brandlc37f2882007-12-04 17:46:27 +0000127
128The logger, handler, and log message call each specify a level. The log message
129is only emitted if the handler and logger are configured to emit messages of
130that level or lower. For example, if a message is ``CRITICAL``, and the logger
131is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
132the logger is set to produce only ``ERROR``\s, the message is not emitted::
133
134 import logging
135 import sys
136
137 LEVELS = {'debug': logging.DEBUG,
138 'info': logging.INFO,
139 'warning': logging.WARNING,
140 'error': logging.ERROR,
141 'critical': logging.CRITICAL}
142
143 if len(sys.argv) > 1:
144 level_name = sys.argv[1]
145 level = LEVELS.get(level_name, logging.NOTSET)
146 logging.basicConfig(level=level)
147
148 logging.debug('This is a debug message')
149 logging.info('This is an info message')
150 logging.warning('This is a warning message')
151 logging.error('This is an error message')
152 logging.critical('This is a critical error message')
153
154Run the script with an argument like 'debug' or 'warning' to see which messages
155show up at different levels::
156
157 $ python logging_level_example.py debug
158 DEBUG:root:This is a debug message
159 INFO:root:This is an info message
160 WARNING:root:This is a warning message
161 ERROR:root:This is an error message
162 CRITICAL:root:This is a critical error message
163
164 $ python logging_level_example.py info
165 INFO:root:This is an info message
166 WARNING:root:This is a warning message
167 ERROR:root:This is an error message
168 CRITICAL:root:This is a critical error message
169
170You will notice that these log messages all have ``root`` embedded in them. The
171logging module supports a hierarchy of loggers with different names. An easy
172way to tell where a specific log message comes from is to use a separate logger
173object for each of your modules. Each new logger "inherits" the configuration
174of its parent, and log messages sent to a logger include the name of that
175logger. Optionally, each logger can be configured differently, so that messages
176from different modules are handled in different ways. Let's look at a simple
177example of how to log from different modules so it is easy to trace the source
178of the message::
179
180 import logging
181
182 logging.basicConfig(level=logging.WARNING)
183
184 logger1 = logging.getLogger('package1.module1')
185 logger2 = logging.getLogger('package2.module2')
186
187 logger1.warning('This message comes from one module')
188 logger2.warning('And this message comes from another module')
189
190And the output::
191
192 $ python logging_modules_example.py
193 WARNING:package1.module1:This message comes from one module
194 WARNING:package2.module2:And this message comes from another module
195
196There are many more options for configuring logging, including different log
197message formatting options, having messages delivered to multiple destinations,
198and changing the configuration of a long-running application on the fly using a
199socket interface. All of these options are covered in depth in the library
200module documentation.
201
202Loggers
203^^^^^^^
204
205The logging library takes a modular approach and offers the several categories
206of components: loggers, handlers, filters, and formatters. Loggers expose the
207interface that application code directly uses. Handlers send the log records to
208the appropriate destination. Filters provide a finer grained facility for
209determining which log records to send on to a handler. Formatters specify the
210layout of the resultant log record.
211
212:class:`Logger` objects have a threefold job. First, they expose several
213methods to application code so that applications can log messages at runtime.
214Second, logger objects determine which log messages to act upon based upon
215severity (the default filtering facility) or filter objects. Third, logger
216objects pass along relevant log messages to all interested log handlers.
217
218The most widely used methods on logger objects fall into two categories:
219configuration and message sending.
220
221* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
222 will handle, where debug is the lowest built-in severity level and critical is
223 the highest built-in severity. For example, if the severity level is info,
224 the logger will handle only info, warning, error, and critical messages and
225 will ignore debug messages.
226
227* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
228 objects from the logger object. This tutorial does not address filters.
229
230With the logger object configured, the following methods create log messages:
231
232* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
233 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
234 a message and a level that corresponds to their respective method names. The
235 message is actually a format string, which may contain the standard string
236 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
237 rest of their arguments is a list of objects that correspond with the
238 substitution fields in the message. With regard to :const:`**kwargs`, the
239 logging methods care only about a keyword of :const:`exc_info` and use it to
240 determine whether to log exception information.
241
242* :meth:`Logger.exception` creates a log message similar to
243 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
244 stack trace along with it. Call this method only from an exception handler.
245
246* :meth:`Logger.log` takes a log level as an explicit argument. This is a
247 little more verbose for logging messages than using the log level convenience
248 methods listed above, but this is how to log at custom log levels.
249
Brett Cannon499969a2008-02-25 05:33:07 +0000250:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajip80eed3e2010-07-06 15:08:55 +0000251name if it is provided, or ``root`` if not. The names are period-separated
Georg Brandlc37f2882007-12-04 17:46:27 +0000252hierarchical structures. Multiple calls to :func:`getLogger` with the same name
253will return a reference to the same logger object. Loggers that are further
254down in the hierarchical list are children of loggers higher up in the list.
255For example, given a logger with a name of ``foo``, loggers with names of
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000256``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
257Child loggers propagate messages up to the handlers associated with their
258ancestor loggers. Because of this, it is unnecessary to define and configure
259handlers for all the loggers an application uses. It is sufficient to
260configure handlers for a top-level logger and create child loggers as needed.
Georg Brandlc37f2882007-12-04 17:46:27 +0000261
262
263Handlers
264^^^^^^^^
265
266:class:`Handler` objects are responsible for dispatching the appropriate log
267messages (based on the log messages' severity) to the handler's specified
268destination. Logger objects can add zero or more handler objects to themselves
269with an :func:`addHandler` method. As an example scenario, an application may
270want to send all log messages to a log file, all log messages of error or higher
271to stdout, and all messages of critical to an email address. This scenario
Georg Brandl907a7202008-02-22 12:31:45 +0000272requires three individual handlers where each handler is responsible for sending
Georg Brandlc37f2882007-12-04 17:46:27 +0000273messages of a specific severity to a specific location.
274
275The standard library includes quite a few handler types; this tutorial uses only
276:class:`StreamHandler` and :class:`FileHandler` in its examples.
277
278There are very few methods in a handler for application developers to concern
279themselves with. The only handler methods that seem relevant for application
280developers who are using the built-in handler objects (that is, not creating
281custom handlers) are the following configuration methods:
282
283* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
284 lowest severity that will be dispatched to the appropriate destination. Why
285 are there two :func:`setLevel` methods? The level set in the logger
286 determines which severity of messages it will pass to its handlers. The level
287 set in each handler determines which messages that handler will send on.
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000288
289* :func:`setFormatter` selects a Formatter object for this handler to use.
Georg Brandlc37f2882007-12-04 17:46:27 +0000290
291* :func:`addFilter` and :func:`removeFilter` respectively configure and
292 deconfigure filter objects on handlers.
293
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000294Application code should not directly instantiate and use instances of
295:class:`Handler`. Instead, the :class:`Handler` class is a base class that
Vinay Sajip497256b2010-04-07 09:40:52 +0000296defines the interface that all handlers should have and establishes some
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000297default behavior that child classes can use (or override).
Georg Brandlc37f2882007-12-04 17:46:27 +0000298
299
300Formatters
301^^^^^^^^^^
302
303Formatter objects configure the final order, structure, and contents of the log
Brett Cannon499969a2008-02-25 05:33:07 +0000304message. Unlike the base :class:`logging.Handler` class, application code may
Georg Brandlc37f2882007-12-04 17:46:27 +0000305instantiate formatter classes, although you could likely subclass the formatter
306if your application needs special behavior. The constructor takes two optional
307arguments: a message format string and a date format string. If there is no
308message format string, the default is to use the raw message. If there is no
309date format string, the default date format is::
310
311 %Y-%m-%d %H:%M:%S
312
313with the milliseconds tacked on at the end.
314
315The message format string uses ``%(<dictionary key>)s`` styled string
Vinay Sajip4b782332009-01-19 06:49:19 +0000316substitution; the possible keys are documented in :ref:`formatter`.
Georg Brandlc37f2882007-12-04 17:46:27 +0000317
318The following message format string will log the time in a human-readable
319format, the severity of the message, and the contents of the message, in that
320order::
321
322 "%(asctime)s - %(levelname)s - %(message)s"
323
Vinay Sajip8d8e6152010-08-30 18:10:03 +0000324Formatters use a user-configurable function to convert the creation time of a
325record to a tuple. By default, :func:`time.localtime` is used; to change this
326for a particular formatter instance, set the ``converter`` attribute of the
327instance to a function with the same signature as :func:`time.localtime` or
328:func:`time.gmtime`. To change it for all formatters, for example if you want
329all logging times to be shown in GMT, set the ``converter`` attribute in the
330Formatter class (to ``time.gmtime`` for GMT display).
331
Georg Brandlc37f2882007-12-04 17:46:27 +0000332
333Configuring Logging
334^^^^^^^^^^^^^^^^^^^
335
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000336Programmers can configure logging in three ways:
337
3381. Creating loggers, handlers, and formatters explicitly using Python
339 code that calls the configuration methods listed above.
3402. Creating a logging config file and reading it using the :func:`fileConfig`
341 function.
3423. Creating a dictionary of configuration information and passing it
343 to the :func:`dictConfig` function.
344
345The following example configures a very simple logger, a console
Vinay Sajipa38cd522010-05-18 08:16:27 +0000346handler, and a simple formatter using Python code::
Georg Brandlc37f2882007-12-04 17:46:27 +0000347
348 import logging
349
350 # create logger
351 logger = logging.getLogger("simple_example")
352 logger.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000353
Georg Brandlc37f2882007-12-04 17:46:27 +0000354 # create console handler and set level to debug
355 ch = logging.StreamHandler()
356 ch.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000357
Georg Brandlc37f2882007-12-04 17:46:27 +0000358 # create formatter
359 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000360
Georg Brandlc37f2882007-12-04 17:46:27 +0000361 # add formatter to ch
362 ch.setFormatter(formatter)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000363
Georg Brandlc37f2882007-12-04 17:46:27 +0000364 # add ch to logger
365 logger.addHandler(ch)
366
367 # "application" code
368 logger.debug("debug message")
369 logger.info("info message")
370 logger.warn("warn message")
371 logger.error("error message")
372 logger.critical("critical message")
373
374Running this module from the command line produces the following output::
375
376 $ python simple_logging_module.py
377 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
378 2005-03-19 15:10:26,620 - simple_example - INFO - info message
379 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
380 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
381 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
382
383The following Python module creates a logger, handler, and formatter nearly
384identical to those in the example listed above, with the only difference being
385the names of the objects::
386
387 import logging
388 import logging.config
389
390 logging.config.fileConfig("logging.conf")
391
392 # create logger
393 logger = logging.getLogger("simpleExample")
394
395 # "application" code
396 logger.debug("debug message")
397 logger.info("info message")
398 logger.warn("warn message")
399 logger.error("error message")
400 logger.critical("critical message")
401
402Here is the logging.conf file::
403
404 [loggers]
405 keys=root,simpleExample
406
407 [handlers]
408 keys=consoleHandler
409
410 [formatters]
411 keys=simpleFormatter
412
413 [logger_root]
414 level=DEBUG
415 handlers=consoleHandler
416
417 [logger_simpleExample]
418 level=DEBUG
419 handlers=consoleHandler
420 qualname=simpleExample
421 propagate=0
422
423 [handler_consoleHandler]
424 class=StreamHandler
425 level=DEBUG
426 formatter=simpleFormatter
427 args=(sys.stdout,)
428
429 [formatter_simpleFormatter]
430 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
431 datefmt=
432
433The output is nearly identical to that of the non-config-file-based example::
434
435 $ python simple_logging_config.py
436 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
437 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
438 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
439 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
440 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
441
442You can see that the config file approach has a few advantages over the Python
443code approach, mainly separation of configuration and code and the ability of
444noncoders to easily modify the logging properties.
445
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000446Note that the class names referenced in config files need to be either relative
447to the logging module, or absolute values which can be resolved using normal
Georg Brandlf6d367452010-03-12 10:02:03 +0000448import mechanisms. Thus, you could use either :class:`handlers.WatchedFileHandler`
449(relative to the logging module) or :class:`mypackage.mymodule.MyHandler` (for a
450class defined in package :mod:`mypackage` and module :mod:`mymodule`, where
451:mod:`mypackage` is available on the Python import path).
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000452
Vinay Sajipc76defc2010-05-21 17:41:34 +0000453.. versionchanged:: 2.7
454
455In Python 2.7, a new means of configuring logging has been introduced, using
456dictionaries to hold configuration information. This provides a superset of the
457functionality of the config-file-based approach outlined above, and is the
458recommended configuration method for new applications and deployments. Because
459a Python dictionary is used to hold configuration information, and since you
460can populate that dictionary using different means, you have more options for
461configuration. For example, you can use a configuration file in JSON format,
462or, if you have access to YAML processing functionality, a file in YAML
463format, to populate the configuration dictionary. Or, of course, you can
464construct the dictionary in Python code, receive it in pickled form over a
465socket, or use whatever approach makes sense for your application.
466
467Here's an example of the same configuration as above, in YAML format for
468the new dictionary-based approach::
469
470 version: 1
471 formatters:
472 simple:
473 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
474 handlers:
475 console:
476 class: logging.StreamHandler
477 level: DEBUG
478 formatter: simple
479 stream: ext://sys.stdout
480 loggers:
481 simpleExample:
482 level: DEBUG
483 handlers: [console]
484 propagate: no
485 root:
486 level: DEBUG
487 handlers: [console]
488
489For more information about logging using a dictionary, see
490:ref:`logging-config-api`.
491
Vinay Sajip99505c82009-01-10 13:38:04 +0000492.. _library-config:
493
Vinay Sajip34bfda52008-09-01 15:08:07 +0000494Configuring Logging for a Library
495^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
496
497When developing a library which uses logging, some consideration needs to be
498given to its configuration. If the using application does not use logging, and
499library code makes logging calls, then a one-off message "No handlers could be
500found for logger X.Y.Z" is printed to the console. This message is intended
501to catch mistakes in logging configuration, but will confuse an application
502developer who is not aware of logging by the library.
503
504In addition to documenting how a library uses logging, a good way to configure
505library logging so that it does not cause a spurious message is to add a
506handler which does nothing. This avoids the message being printed, since a
507handler will be found: it just doesn't produce any output. If the library user
508configures logging for application use, presumably that configuration will add
509some handlers, and if levels are suitably configured then logging calls made
510in library code will send output to those handlers, as normal.
511
512A do-nothing handler can be simply defined as follows::
513
514 import logging
515
516 class NullHandler(logging.Handler):
517 def emit(self, record):
518 pass
519
520An instance of this handler should be added to the top-level logger of the
521logging namespace used by the library. If all logging by a library *foo* is
522done using loggers with names matching "foo.x.y", then the code::
523
524 import logging
525
526 h = NullHandler()
527 logging.getLogger("foo").addHandler(h)
528
529should have the desired effect. If an organisation produces a number of
530libraries, then the logger name specified can be "orgname.foo" rather than
531just "foo".
532
Vinay Sajip213faca2008-12-03 23:22:58 +0000533.. versionadded:: 2.7
534
535The :class:`NullHandler` class was not present in previous versions, but is now
536included, so that it need not be defined in library code.
537
538
Georg Brandlc37f2882007-12-04 17:46:27 +0000539
540Logging Levels
541--------------
542
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543The numeric values of logging levels are given in the following table. These are
544primarily of interest if you want to define your own levels, and need them to
545have specific values relative to the predefined levels. If you define a level
546with the same numeric value, it overwrites the predefined value; the predefined
547name is lost.
548
549+--------------+---------------+
550| Level | Numeric value |
551+==============+===============+
552| ``CRITICAL`` | 50 |
553+--------------+---------------+
554| ``ERROR`` | 40 |
555+--------------+---------------+
556| ``WARNING`` | 30 |
557+--------------+---------------+
558| ``INFO`` | 20 |
559+--------------+---------------+
560| ``DEBUG`` | 10 |
561+--------------+---------------+
562| ``NOTSET`` | 0 |
563+--------------+---------------+
564
565Levels can also be associated with loggers, being set either by the developer or
566through loading a saved logging configuration. When a logging method is called
567on a logger, the logger compares its own level with the level associated with
568the method call. If the logger's level is higher than the method call's, no
569logging message is actually generated. This is the basic mechanism controlling
570the verbosity of logging output.
571
572Logging messages are encoded as instances of the :class:`LogRecord` class. When
573a logger decides to actually log an event, a :class:`LogRecord` instance is
574created from the logging message.
575
576Logging messages are subjected to a dispatch mechanism through the use of
577:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
578class. Handlers are responsible for ensuring that a logged message (in the form
579of a :class:`LogRecord`) ends up in a particular location (or set of locations)
580which is useful for the target audience for that message (such as end users,
581support desk staff, system administrators, developers). Handlers are passed
582:class:`LogRecord` instances intended for particular destinations. Each logger
583can have zero, one or more handlers associated with it (via the
584:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
585directly associated with a logger, *all handlers associated with all ancestors
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000586of the logger* are called to dispatch the message (unless the *propagate* flag
587for a logger is set to a false value, at which point the passing to ancestor
588handlers stops).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589
590Just as for loggers, handlers can have levels associated with them. A handler's
591level acts as a filter in the same way as a logger's level does. If a handler
592decides to actually dispatch an event, the :meth:`emit` method is used to send
593the message to its destination. Most user-defined subclasses of :class:`Handler`
594will need to override this :meth:`emit`.
595
Vinay Sajip89e1ae22010-09-17 10:09:04 +0000596.. _custom-levels:
597
598Custom Levels
599^^^^^^^^^^^^^
600
601Defining your own levels is possible, but should not be necessary, as the
602existing levels have been chosen on the basis of practical experience.
603However, if you are convinced that you need custom levels, great care should
604be exercised when doing this, and it is possibly *a very bad idea to define
605custom levels if you are developing a library*. That's because if multiple
606library authors all define their own custom levels, there is a chance that
607the logging output from such multiple libraries used together will be
608difficult for the using developer to control and/or interpret, because a
609given numeric value might mean different things for different libraries.
610
611
Vinay Sajipb5902e62009-01-15 22:48:13 +0000612Useful Handlers
613---------------
614
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615In addition to the base :class:`Handler` class, many useful subclasses are
616provided:
617
Vinay Sajip4b782332009-01-19 06:49:19 +0000618#. :ref:`stream-handler` instances send error messages to streams (file-like
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619 objects).
620
Vinay Sajip4b782332009-01-19 06:49:19 +0000621#. :ref:`file-handler` instances send error messages to disk files.
Vinay Sajipb1a15e42009-01-15 23:04:47 +0000622
Vinay Sajipb5902e62009-01-15 22:48:13 +0000623#. :class:`BaseRotatingHandler` is the base class for handlers that
Vinay Sajip99234c52009-01-12 20:36:18 +0000624 rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajip4b782332009-01-19 06:49:19 +0000625 directly. Instead, use :ref:`rotating-file-handler` or
626 :ref:`timed-rotating-file-handler`.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000627
Vinay Sajip4b782332009-01-19 06:49:19 +0000628#. :ref:`rotating-file-handler` instances send error messages to disk
Vinay Sajipb5902e62009-01-15 22:48:13 +0000629 files, with support for maximum log file sizes and log file rotation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000630
Vinay Sajip4b782332009-01-19 06:49:19 +0000631#. :ref:`timed-rotating-file-handler` instances send error messages to
Vinay Sajipb5902e62009-01-15 22:48:13 +0000632 disk files, rotating the log file at certain timed intervals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633
Vinay Sajip4b782332009-01-19 06:49:19 +0000634#. :ref:`socket-handler` instances send error messages to TCP/IP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000635 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000636
Vinay Sajip4b782332009-01-19 06:49:19 +0000637#. :ref:`datagram-handler` instances send error messages to UDP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000638 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639
Vinay Sajip4b782332009-01-19 06:49:19 +0000640#. :ref:`smtp-handler` instances send error messages to a designated
Vinay Sajipb5902e62009-01-15 22:48:13 +0000641 email address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000642
Vinay Sajip4b782332009-01-19 06:49:19 +0000643#. :ref:`syslog-handler` instances send error messages to a Unix
Vinay Sajipb5902e62009-01-15 22:48:13 +0000644 syslog daemon, possibly on a remote machine.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000645
Vinay Sajip4b782332009-01-19 06:49:19 +0000646#. :ref:`nt-eventlog-handler` instances send error messages to a
Vinay Sajipb5902e62009-01-15 22:48:13 +0000647 Windows NT/2000/XP event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000648
Vinay Sajip4b782332009-01-19 06:49:19 +0000649#. :ref:`memory-handler` instances send error messages to a buffer
Vinay Sajipb5902e62009-01-15 22:48:13 +0000650 in memory, which is flushed whenever specific criteria are met.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000651
Vinay Sajip4b782332009-01-19 06:49:19 +0000652#. :ref:`http-handler` instances send error messages to an HTTP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000653 server using either ``GET`` or ``POST`` semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
Vinay Sajip4b782332009-01-19 06:49:19 +0000655#. :ref:`watched-file-handler` instances watch the file they are
Vinay Sajipb5902e62009-01-15 22:48:13 +0000656 logging to. If the file changes, it is closed and reopened using the file
657 name. This handler is only useful on Unix-like systems; Windows does not
658 support the underlying mechanism used.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000659
Vinay Sajip4b782332009-01-19 06:49:19 +0000660#. :ref:`null-handler` instances do nothing with error messages. They are used
Vinay Sajip213faca2008-12-03 23:22:58 +0000661 by library developers who want to use logging, but want to avoid the "No
662 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip99505c82009-01-10 13:38:04 +0000663 the library user has not configured logging. See :ref:`library-config` for
664 more information.
Vinay Sajip213faca2008-12-03 23:22:58 +0000665
666.. versionadded:: 2.7
667
668The :class:`NullHandler` class was not present in previous versions.
669
Vinay Sajip7cc97552008-12-30 07:01:25 +0000670The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
671classes are defined in the core logging package. The other handlers are
672defined in a sub- module, :mod:`logging.handlers`. (There is also another
673sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674
675Logged messages are formatted for presentation through instances of the
676:class:`Formatter` class. They are initialized with a format string suitable for
677use with the % operator and a dictionary.
678
679For formatting multiple messages in a batch, instances of
680:class:`BufferingFormatter` can be used. In addition to the format string (which
681is applied to each message in the batch), there is provision for header and
682trailer format strings.
683
684When filtering based on logger level and/or handler level is not enough,
685instances of :class:`Filter` can be added to both :class:`Logger` and
686:class:`Handler` instances (through their :meth:`addFilter` method). Before
687deciding to process a message further, both loggers and handlers consult all
688their filters for permission. If any filter returns a false value, the message
689is not processed further.
690
691The basic :class:`Filter` functionality allows filtering by specific logger
692name. If this feature is used, messages sent to the named logger and its
693children are allowed through the filter, and all others dropped.
694
Vinay Sajipb5902e62009-01-15 22:48:13 +0000695Module-Level Functions
696----------------------
697
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698In addition to the classes described above, there are a number of module- level
699functions.
700
701
702.. function:: getLogger([name])
703
704 Return a logger with the specified name or, if no name is specified, return a
705 logger which is the root logger of the hierarchy. If specified, the name is
706 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
707 Choice of these names is entirely up to the developer who is using logging.
708
709 All calls to this function with a given name return the same logger instance.
710 This means that logger instances never need to be passed between different parts
711 of an application.
712
713
714.. function:: getLoggerClass()
715
716 Return either the standard :class:`Logger` class, or the last class passed to
717 :func:`setLoggerClass`. This function may be called from within a new class
718 definition, to ensure that installing a customised :class:`Logger` class will
719 not undo customisations already applied by other code. For example::
720
721 class MyLogger(logging.getLoggerClass()):
722 # ... override behaviour here
723
724
725.. function:: debug(msg[, *args[, **kwargs]])
726
727 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
728 message format string, and the *args* are the arguments which are merged into
729 *msg* using the string formatting operator. (Note that this means that you can
730 use keywords in the format string, together with a single dictionary argument.)
731
732 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
733 which, if it does not evaluate as false, causes exception information to be
734 added to the logging message. If an exception tuple (in the format returned by
735 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
736 is called to get the exception information.
737
738 The other optional keyword argument is *extra* which can be used to pass a
739 dictionary which is used to populate the __dict__ of the LogRecord created for
740 the logging event with user-defined attributes. These custom attributes can then
741 be used as you like. For example, they could be incorporated into logged
742 messages. For example::
743
744 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
745 logging.basicConfig(format=FORMAT)
746 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
747 logging.warning("Protocol problem: %s", "connection reset", extra=d)
748
Vinay Sajipfe08e6f2010-09-11 10:25:28 +0000749 would print something like::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
751 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
752
753 The keys in the dictionary passed in *extra* should not clash with the keys used
754 by the logging system. (See the :class:`Formatter` documentation for more
755 information on which keys are used by the logging system.)
756
757 If you choose to use these attributes in logged messages, you need to exercise
758 some care. In the above example, for instance, the :class:`Formatter` has been
759 set up with a format string which expects 'clientip' and 'user' in the attribute
760 dictionary of the LogRecord. If these are missing, the message will not be
761 logged because a string formatting exception will occur. So in this case, you
762 always need to pass the *extra* dictionary with these keys.
763
764 While this might be annoying, this feature is intended for use in specialized
765 circumstances, such as multi-threaded servers where the same code executes in
766 many contexts, and interesting conditions which arise are dependent on this
767 context (such as remote client IP address and authenticated user name, in the
768 above example). In such circumstances, it is likely that specialized
769 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
770
771 .. versionchanged:: 2.5
772 *extra* was added.
773
774
775.. function:: info(msg[, *args[, **kwargs]])
776
777 Logs a message with level :const:`INFO` on the root logger. The arguments are
778 interpreted as for :func:`debug`.
779
780
781.. function:: warning(msg[, *args[, **kwargs]])
782
783 Logs a message with level :const:`WARNING` on the root logger. The arguments are
784 interpreted as for :func:`debug`.
785
786
787.. function:: error(msg[, *args[, **kwargs]])
788
789 Logs a message with level :const:`ERROR` on the root logger. The arguments are
790 interpreted as for :func:`debug`.
791
792
793.. function:: critical(msg[, *args[, **kwargs]])
794
795 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
796 are interpreted as for :func:`debug`.
797
798
799.. function:: exception(msg[, *args])
800
801 Logs a message with level :const:`ERROR` on the root logger. The arguments are
802 interpreted as for :func:`debug`. Exception info is added to the logging
803 message. This function should only be called from an exception handler.
804
805
806.. function:: log(level, msg[, *args[, **kwargs]])
807
808 Logs a message with level *level* on the root logger. The other arguments are
809 interpreted as for :func:`debug`.
810
Vinay Sajip89e1ae22010-09-17 10:09:04 +0000811 PLEASE NOTE: The above module-level functions which delegate to the root
812 logger should *not* be used in threads, in versions of Python earlier than
813 2.7.1 and 3.2, unless at least one handler has been added to the root
814 logger *before* the threads are started. These convenience functions call
815 :func:`basicConfig` to ensure that at least one handler is available; in
816 earlier versions of Python, this can (under rare circumstances) lead to
817 handlers being added multiple times to the root logger, which can in turn
818 lead to multiple messages for the same event.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000819
820.. function:: disable(lvl)
821
822 Provides an overriding level *lvl* for all loggers which takes precedence over
823 the logger's own level. When the need arises to temporarily throttle logging
Vinay Sajip2060e422010-03-17 15:05:57 +0000824 output down across the whole application, this function can be useful. Its
825 effect is to disable all logging calls of severity *lvl* and below, so that
826 if you call it with a value of INFO, then all INFO and DEBUG events would be
827 discarded, whereas those of severity WARNING and above would be processed
828 according to the logger's effective level.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000829
830
831.. function:: addLevelName(lvl, levelName)
832
833 Associates level *lvl* with text *levelName* in an internal dictionary, which is
834 used to map numeric levels to a textual representation, for example when a
835 :class:`Formatter` formats a message. This function can also be used to define
836 your own levels. The only constraints are that all levels used must be
837 registered using this function, levels should be positive integers and they
838 should increase in increasing order of severity.
839
Vinay Sajip89e1ae22010-09-17 10:09:04 +0000840 NOTE: If you are thinking of defining your own levels, please see the section
841 on :ref:`custom-levels`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000842
843.. function:: getLevelName(lvl)
844
845 Returns the textual representation of logging level *lvl*. If the level is one
846 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
847 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
848 have associated levels with names using :func:`addLevelName` then the name you
849 have associated with *lvl* is returned. If a numeric value corresponding to one
850 of the defined levels is passed in, the corresponding string representation is
851 returned. Otherwise, the string "Level %s" % lvl is returned.
852
853
854.. function:: makeLogRecord(attrdict)
855
856 Creates and returns a new :class:`LogRecord` instance whose attributes are
857 defined by *attrdict*. This function is useful for taking a pickled
858 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
859 it as a :class:`LogRecord` instance at the receiving end.
860
861
862.. function:: basicConfig([**kwargs])
863
864 Does basic configuration for the logging system by creating a
865 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000866 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000867 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
868 if no handlers are defined for the root logger.
869
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000870 This function does nothing if the root logger already has handlers
871 configured for it.
Georg Brandldfb5bbd2008-05-09 06:18:27 +0000872
Georg Brandl8ec7f652007-08-15 14:28:01 +0000873 .. versionchanged:: 2.4
874 Formerly, :func:`basicConfig` did not take any keyword arguments.
875
Vinay Sajip89e1ae22010-09-17 10:09:04 +0000876 PLEASE NOTE: This function should be called from the main thread
877 before other threads are started. In versions of Python prior to
878 2.7.1 and 3.2, if this function is called from multiple threads,
879 it is possible (in rare circumstances) that a handler will be added
880 to the root logger more than once, leading to unexpected results
881 such as messages being duplicated in the log.
882
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883 The following keyword arguments are supported.
884
885 +--------------+---------------------------------------------+
886 | Format | Description |
887 +==============+=============================================+
888 | ``filename`` | Specifies that a FileHandler be created, |
889 | | using the specified filename, rather than a |
890 | | StreamHandler. |
891 +--------------+---------------------------------------------+
892 | ``filemode`` | Specifies the mode to open the file, if |
893 | | filename is specified (if filemode is |
894 | | unspecified, it defaults to 'a'). |
895 +--------------+---------------------------------------------+
896 | ``format`` | Use the specified format string for the |
897 | | handler. |
898 +--------------+---------------------------------------------+
899 | ``datefmt`` | Use the specified date/time format. |
900 +--------------+---------------------------------------------+
901 | ``level`` | Set the root logger level to the specified |
902 | | level. |
903 +--------------+---------------------------------------------+
904 | ``stream`` | Use the specified stream to initialize the |
905 | | StreamHandler. Note that this argument is |
906 | | incompatible with 'filename' - if both are |
907 | | present, 'stream' is ignored. |
908 +--------------+---------------------------------------------+
909
910
911.. function:: shutdown()
912
913 Informs the logging system to perform an orderly shutdown by flushing and
Vinay Sajip91f0ee42008-03-16 21:35:58 +0000914 closing all handlers. This should be called at application exit and no
915 further use of the logging system should be made after this call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000916
917
918.. function:: setLoggerClass(klass)
919
920 Tells the logging system to use the class *klass* when instantiating a logger.
921 The class should define :meth:`__init__` such that only a name argument is
922 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
923 function is typically called before any loggers are instantiated by applications
924 which need to use custom logger behavior.
925
926
927.. seealso::
928
929 :pep:`282` - A Logging System
930 The proposal which described this feature for inclusion in the Python standard
931 library.
932
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000933 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +0000934 This is the original source for the :mod:`logging` package. The version of the
935 package available from this site is suitable for use with Python 1.5.2, 2.1.x
936 and 2.2.x, which do not include the :mod:`logging` package in the standard
937 library.
938
Vinay Sajip4b782332009-01-19 06:49:19 +0000939.. _logger:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000940
941Logger Objects
942--------------
943
944Loggers have the following attributes and methods. Note that Loggers are never
945instantiated directly, but always through the module-level function
946``logging.getLogger(name)``.
947
948
949.. attribute:: Logger.propagate
950
951 If this evaluates to false, logging messages are not passed by this logger or by
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000952 its child loggers to the handlers of higher level (ancestor) loggers. The
953 constructor sets this attribute to 1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954
955
956.. method:: Logger.setLevel(lvl)
957
958 Sets the threshold for this logger to *lvl*. Logging messages which are less
959 severe than *lvl* will be ignored. When a logger is created, the level is set to
960 :const:`NOTSET` (which causes all messages to be processed when the logger is
961 the root logger, or delegation to the parent when the logger is a non-root
962 logger). Note that the root logger is created with level :const:`WARNING`.
963
964 The term "delegation to the parent" means that if a logger has a level of
965 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
966 a level other than NOTSET is found, or the root is reached.
967
968 If an ancestor is found with a level other than NOTSET, then that ancestor's
969 level is treated as the effective level of the logger where the ancestor search
970 began, and is used to determine how a logging event is handled.
971
972 If the root is reached, and it has a level of NOTSET, then all messages will be
973 processed. Otherwise, the root's level will be used as the effective level.
974
975
976.. method:: Logger.isEnabledFor(lvl)
977
978 Indicates if a message of severity *lvl* would be processed by this logger.
979 This method checks first the module-level level set by
980 ``logging.disable(lvl)`` and then the logger's effective level as determined
981 by :meth:`getEffectiveLevel`.
982
983
984.. method:: Logger.getEffectiveLevel()
985
986 Indicates the effective level for this logger. If a value other than
987 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
988 the hierarchy is traversed towards the root until a value other than
989 :const:`NOTSET` is found, and that value is returned.
990
991
Vinay Sajip804899b2010-03-22 15:29:01 +0000992.. method:: Logger.getChild(suffix)
993
994 Returns a logger which is a descendant to this logger, as determined by the suffix.
995 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
996 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
997 convenience method, useful when the parent logger is named using e.g. ``__name__``
998 rather than a literal string.
999
1000 .. versionadded:: 2.7
1001
Georg Brandl8ec7f652007-08-15 14:28:01 +00001002.. method:: Logger.debug(msg[, *args[, **kwargs]])
1003
1004 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1005 message format string, and the *args* are the arguments which are merged into
1006 *msg* using the string formatting operator. (Note that this means that you can
1007 use keywords in the format string, together with a single dictionary argument.)
1008
1009 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
1010 which, if it does not evaluate as false, causes exception information to be
1011 added to the logging message. If an exception tuple (in the format returned by
1012 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1013 is called to get the exception information.
1014
1015 The other optional keyword argument is *extra* which can be used to pass a
1016 dictionary which is used to populate the __dict__ of the LogRecord created for
1017 the logging event with user-defined attributes. These custom attributes can then
1018 be used as you like. For example, they could be incorporated into logged
1019 messages. For example::
1020
1021 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1022 logging.basicConfig(format=FORMAT)
Neal Norwitz53004282007-10-23 05:44:27 +00001023 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl8ec7f652007-08-15 14:28:01 +00001024 logger = logging.getLogger("tcpserver")
1025 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1026
1027 would print something like ::
1028
1029 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1030
1031 The keys in the dictionary passed in *extra* should not clash with the keys used
1032 by the logging system. (See the :class:`Formatter` documentation for more
1033 information on which keys are used by the logging system.)
1034
1035 If you choose to use these attributes in logged messages, you need to exercise
1036 some care. In the above example, for instance, the :class:`Formatter` has been
1037 set up with a format string which expects 'clientip' and 'user' in the attribute
1038 dictionary of the LogRecord. If these are missing, the message will not be
1039 logged because a string formatting exception will occur. So in this case, you
1040 always need to pass the *extra* dictionary with these keys.
1041
1042 While this might be annoying, this feature is intended for use in specialized
1043 circumstances, such as multi-threaded servers where the same code executes in
1044 many contexts, and interesting conditions which arise are dependent on this
1045 context (such as remote client IP address and authenticated user name, in the
1046 above example). In such circumstances, it is likely that specialized
1047 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1048
1049 .. versionchanged:: 2.5
1050 *extra* was added.
1051
1052
1053.. method:: Logger.info(msg[, *args[, **kwargs]])
1054
1055 Logs a message with level :const:`INFO` on this logger. The arguments are
1056 interpreted as for :meth:`debug`.
1057
1058
1059.. method:: Logger.warning(msg[, *args[, **kwargs]])
1060
1061 Logs a message with level :const:`WARNING` on this logger. The arguments are
1062 interpreted as for :meth:`debug`.
1063
1064
1065.. method:: Logger.error(msg[, *args[, **kwargs]])
1066
1067 Logs a message with level :const:`ERROR` on this logger. The arguments are
1068 interpreted as for :meth:`debug`.
1069
1070
1071.. method:: Logger.critical(msg[, *args[, **kwargs]])
1072
1073 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1074 interpreted as for :meth:`debug`.
1075
1076
1077.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
1078
1079 Logs a message with integer level *lvl* on this logger. The other arguments are
1080 interpreted as for :meth:`debug`.
1081
1082
1083.. method:: Logger.exception(msg[, *args])
1084
1085 Logs a message with level :const:`ERROR` on this logger. The arguments are
1086 interpreted as for :meth:`debug`. Exception info is added to the logging
1087 message. This method should only be called from an exception handler.
1088
1089
1090.. method:: Logger.addFilter(filt)
1091
1092 Adds the specified filter *filt* to this logger.
1093
1094
1095.. method:: Logger.removeFilter(filt)
1096
1097 Removes the specified filter *filt* from this logger.
1098
1099
1100.. method:: Logger.filter(record)
1101
1102 Applies this logger's filters to the record and returns a true value if the
1103 record is to be processed.
1104
1105
1106.. method:: Logger.addHandler(hdlr)
1107
1108 Adds the specified handler *hdlr* to this logger.
1109
1110
1111.. method:: Logger.removeHandler(hdlr)
1112
1113 Removes the specified handler *hdlr* from this logger.
1114
1115
1116.. method:: Logger.findCaller()
1117
1118 Finds the caller's source filename and line number. Returns the filename, line
1119 number and function name as a 3-element tuple.
1120
Matthias Klosef0e29182007-08-16 12:03:44 +00001121 .. versionchanged:: 2.4
Georg Brandl8ec7f652007-08-15 14:28:01 +00001122 The function name was added. In earlier versions, the filename and line number
1123 were returned as a 2-element tuple..
1124
1125
1126.. method:: Logger.handle(record)
1127
1128 Handles a record by passing it to all handlers associated with this logger and
1129 its ancestors (until a false value of *propagate* is found). This method is used
1130 for unpickled records received from a socket, as well as those created locally.
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001131 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001132
1133
1134.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
1135
1136 This is a factory method which can be overridden in subclasses to create
1137 specialized :class:`LogRecord` instances.
1138
1139 .. versionchanged:: 2.5
1140 *func* and *extra* were added.
1141
1142
1143.. _minimal-example:
1144
1145Basic example
1146-------------
1147
1148.. versionchanged:: 2.4
1149 formerly :func:`basicConfig` did not take any keyword arguments.
1150
1151The :mod:`logging` package provides a lot of flexibility, and its configuration
1152can appear daunting. This section demonstrates that simple use of the logging
1153package is possible.
1154
1155The simplest example shows logging to the console::
1156
1157 import logging
1158
1159 logging.debug('A debug message')
1160 logging.info('Some information')
1161 logging.warning('A shot across the bows')
1162
1163If you run the above script, you'll see this::
1164
1165 WARNING:root:A shot across the bows
1166
1167Because no particular logger was specified, the system used the root logger. The
1168debug and info messages didn't appear because by default, the root logger is
1169configured to only handle messages with a severity of WARNING or above. The
1170message format is also a configuration default, as is the output destination of
1171the messages - ``sys.stderr``. The severity level, the message format and
1172destination can be easily changed, as shown in the example below::
1173
1174 import logging
1175
1176 logging.basicConfig(level=logging.DEBUG,
1177 format='%(asctime)s %(levelname)s %(message)s',
Vinay Sajip998cc242010-06-04 13:41:02 +00001178 filename='myapp.log',
Georg Brandl8ec7f652007-08-15 14:28:01 +00001179 filemode='w')
1180 logging.debug('A debug message')
1181 logging.info('Some information')
1182 logging.warning('A shot across the bows')
1183
1184The :meth:`basicConfig` method is used to change the configuration defaults,
Vinay Sajip998cc242010-06-04 13:41:02 +00001185which results in output (written to ``myapp.log``) which should look
Georg Brandl8ec7f652007-08-15 14:28:01 +00001186something like the following::
1187
1188 2004-07-02 13:00:08,743 DEBUG A debug message
1189 2004-07-02 13:00:08,743 INFO Some information
1190 2004-07-02 13:00:08,743 WARNING A shot across the bows
1191
1192This time, all messages with a severity of DEBUG or above were handled, and the
1193format of the messages was also changed, and output went to the specified file
1194rather than the console.
1195
1196Formatting uses standard Python string formatting - see section
1197:ref:`string-formatting`. The format string takes the following common
1198specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1199documentation.
1200
1201+-------------------+-----------------------------------------------+
1202| Format | Description |
1203+===================+===============================================+
1204| ``%(name)s`` | Name of the logger (logging channel). |
1205+-------------------+-----------------------------------------------+
1206| ``%(levelname)s`` | Text logging level for the message |
1207| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1208| | ``'ERROR'``, ``'CRITICAL'``). |
1209+-------------------+-----------------------------------------------+
1210| ``%(asctime)s`` | Human-readable time when the |
1211| | :class:`LogRecord` was created. By default |
1212| | this is of the form "2003-07-08 16:49:45,896" |
1213| | (the numbers after the comma are millisecond |
1214| | portion of the time). |
1215+-------------------+-----------------------------------------------+
1216| ``%(message)s`` | The logged message. |
1217+-------------------+-----------------------------------------------+
1218
1219To change the date/time format, you can pass an additional keyword parameter,
1220*datefmt*, as in the following::
1221
1222 import logging
1223
1224 logging.basicConfig(level=logging.DEBUG,
1225 format='%(asctime)s %(levelname)-8s %(message)s',
1226 datefmt='%a, %d %b %Y %H:%M:%S',
1227 filename='/temp/myapp.log',
1228 filemode='w')
1229 logging.debug('A debug message')
1230 logging.info('Some information')
1231 logging.warning('A shot across the bows')
1232
1233which would result in output like ::
1234
1235 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1236 Fri, 02 Jul 2004 13:06:18 INFO Some information
1237 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1238
1239The date format string follows the requirements of :func:`strftime` - see the
1240documentation for the :mod:`time` module.
1241
1242If, instead of sending logging output to the console or a file, you'd rather use
1243a file-like object which you have created separately, you can pass it to
1244:func:`basicConfig` using the *stream* keyword argument. Note that if both
1245*stream* and *filename* keyword arguments are passed, the *stream* argument is
1246ignored.
1247
1248Of course, you can put variable information in your output. To do this, simply
1249have the message be a format string and pass in additional arguments containing
1250the variable information, as in the following example::
1251
1252 import logging
1253
1254 logging.basicConfig(level=logging.DEBUG,
1255 format='%(asctime)s %(levelname)-8s %(message)s',
1256 datefmt='%a, %d %b %Y %H:%M:%S',
1257 filename='/temp/myapp.log',
1258 filemode='w')
1259 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1260
1261which would result in ::
1262
1263 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1264
1265
1266.. _multiple-destinations:
1267
1268Logging to multiple destinations
1269--------------------------------
1270
1271Let's say you want to log to console and file with different message formats and
1272in differing circumstances. Say you want to log messages with levels of DEBUG
1273and higher to file, and those messages at level INFO and higher to the console.
1274Let's also assume that the file should contain timestamps, but the console
1275messages should not. Here's how you can achieve this::
1276
1277 import logging
1278
1279 # set up logging to file - see previous section for more details
1280 logging.basicConfig(level=logging.DEBUG,
1281 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1282 datefmt='%m-%d %H:%M',
1283 filename='/temp/myapp.log',
1284 filemode='w')
1285 # define a Handler which writes INFO messages or higher to the sys.stderr
1286 console = logging.StreamHandler()
1287 console.setLevel(logging.INFO)
1288 # set a format which is simpler for console use
1289 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1290 # tell the handler to use this format
1291 console.setFormatter(formatter)
1292 # add the handler to the root logger
1293 logging.getLogger('').addHandler(console)
1294
1295 # Now, we can log to the root logger, or any other logger. First the root...
1296 logging.info('Jackdaws love my big sphinx of quartz.')
1297
1298 # Now, define a couple of other loggers which might represent areas in your
1299 # application:
1300
1301 logger1 = logging.getLogger('myapp.area1')
1302 logger2 = logging.getLogger('myapp.area2')
1303
1304 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1305 logger1.info('How quickly daft jumping zebras vex.')
1306 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1307 logger2.error('The five boxing wizards jump quickly.')
1308
1309When you run this, on the console you will see ::
1310
1311 root : INFO Jackdaws love my big sphinx of quartz.
1312 myapp.area1 : INFO How quickly daft jumping zebras vex.
1313 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1314 myapp.area2 : ERROR The five boxing wizards jump quickly.
1315
1316and in the file you will see something like ::
1317
1318 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1319 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1320 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1321 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1322 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1323
1324As you can see, the DEBUG message only shows up in the file. The other messages
1325are sent to both destinations.
1326
1327This example uses console and file handlers, but you can use any number and
1328combination of handlers you choose.
1329
Vinay Sajip333c6e72009-08-20 22:04:32 +00001330.. _logging-exceptions:
1331
1332Exceptions raised during logging
1333--------------------------------
1334
1335The logging package is designed to swallow exceptions which occur while logging
1336in production. This is so that errors which occur while handling logging events
1337- such as logging misconfiguration, network or other similar errors - do not
1338cause the application using logging to terminate prematurely.
1339
1340:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1341swallowed. Other exceptions which occur during the :meth:`emit` method of a
1342:class:`Handler` subclass are passed to its :meth:`handleError` method.
1343
1344The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlf6d367452010-03-12 10:02:03 +00001345to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1346traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip333c6e72009-08-20 22:04:32 +00001347
Georg Brandlf6d367452010-03-12 10:02:03 +00001348**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip333c6e72009-08-20 22:04:32 +00001349during development, you typically want to be notified of any exceptions that
Georg Brandlf6d367452010-03-12 10:02:03 +00001350occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip333c6e72009-08-20 22:04:32 +00001351usage.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001352
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001353.. _context-info:
1354
1355Adding contextual information to your logging output
1356----------------------------------------------------
1357
1358Sometimes you want logging output to contain contextual information in
1359addition to the parameters passed to the logging call. For example, in a
1360networked application, it may be desirable to log client-specific information
1361in the log (e.g. remote client's username, or IP address). Although you could
1362use the *extra* parameter to achieve this, it's not always convenient to pass
1363the information in this way. While it might be tempting to create
1364:class:`Logger` instances on a per-connection basis, this is not a good idea
1365because these instances are not garbage collected. While this is not a problem
1366in practice, when the number of :class:`Logger` instances is dependent on the
1367level of granularity you want to use in logging an application, it could
1368be hard to manage if the number of :class:`Logger` instances becomes
1369effectively unbounded.
1370
Vinay Sajip957a47c2010-09-06 22:18:20 +00001371
1372Using LoggerAdapters to impart contextual information
1373^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1374
Vinay Sajipc7403352008-01-18 15:54:14 +00001375An easy way in which you can pass contextual information to be output along
1376with logging event information is to use the :class:`LoggerAdapter` class.
1377This class is designed to look like a :class:`Logger`, so that you can call
1378:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1379:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1380same signatures as their counterparts in :class:`Logger`, so you can use the
1381two types of instances interchangeably.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001382
Vinay Sajipc7403352008-01-18 15:54:14 +00001383When you create an instance of :class:`LoggerAdapter`, you pass it a
1384:class:`Logger` instance and a dict-like object which contains your contextual
1385information. When you call one of the logging methods on an instance of
1386:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1387:class:`Logger` passed to its constructor, and arranges to pass the contextual
1388information in the delegated call. Here's a snippet from the code of
1389:class:`LoggerAdapter`::
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001390
Vinay Sajipc7403352008-01-18 15:54:14 +00001391 def debug(self, msg, *args, **kwargs):
1392 """
1393 Delegate a debug call to the underlying logger, after adding
1394 contextual information from this adapter instance.
1395 """
1396 msg, kwargs = self.process(msg, kwargs)
1397 self.logger.debug(msg, *args, **kwargs)
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001398
Vinay Sajipc7403352008-01-18 15:54:14 +00001399The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1400information is added to the logging output. It's passed the message and
1401keyword arguments of the logging call, and it passes back (potentially)
1402modified versions of these to use in the call to the underlying logger. The
1403default implementation of this method leaves the message alone, but inserts
1404an "extra" key in the keyword argument whose value is the dict-like object
1405passed to the constructor. Of course, if you had passed an "extra" keyword
1406argument in the call to the adapter, it will be silently overwritten.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001407
Vinay Sajipc7403352008-01-18 15:54:14 +00001408The advantage of using "extra" is that the values in the dict-like object are
1409merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1410customized strings with your :class:`Formatter` instances which know about
1411the keys of the dict-like object. If you need a different method, e.g. if you
1412want to prepend or append the contextual information to the message string,
1413you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1414to do what you need. Here's an example script which uses this class, which
1415also illustrates what dict-like behaviour is needed from an arbitrary
1416"dict-like" object for use in the constructor::
1417
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001418 import logging
Vinay Sajip733024a2008-01-21 17:39:22 +00001419
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001420 class ConnInfo:
1421 """
1422 An example class which shows how an arbitrary class can be used as
1423 the 'extra' context information repository passed to a LoggerAdapter.
1424 """
Vinay Sajip733024a2008-01-21 17:39:22 +00001425
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001426 def __getitem__(self, name):
1427 """
1428 To allow this instance to look like a dict.
1429 """
1430 from random import choice
1431 if name == "ip":
1432 result = choice(["127.0.0.1", "192.168.0.1"])
1433 elif name == "user":
1434 result = choice(["jim", "fred", "sheila"])
1435 else:
1436 result = self.__dict__.get(name, "?")
1437 return result
Vinay Sajip733024a2008-01-21 17:39:22 +00001438
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001439 def __iter__(self):
1440 """
1441 To allow iteration over keys, which will be merged into
1442 the LogRecord dict before formatting and output.
1443 """
1444 keys = ["ip", "user"]
1445 keys.extend(self.__dict__.keys())
1446 return keys.__iter__()
Vinay Sajip733024a2008-01-21 17:39:22 +00001447
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001448 if __name__ == "__main__":
1449 from random import choice
1450 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1451 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1452 { "ip" : "123.231.231.123", "user" : "sheila" })
1453 logging.basicConfig(level=logging.DEBUG,
1454 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1455 a1.debug("A debug message")
1456 a1.info("An info message with %s", "some parameters")
1457 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1458 for x in range(10):
1459 lvl = choice(levels)
1460 lvlname = logging.getLevelName(lvl)
1461 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Vinay Sajipc7403352008-01-18 15:54:14 +00001462
1463When this script is run, the output should look something like this::
1464
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001465 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1466 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1467 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
1468 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
1469 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
1470 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
1471 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
1472 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
1473 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
1474 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
1475 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
1476 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
Vinay Sajipc7403352008-01-18 15:54:14 +00001477
1478.. versionadded:: 2.6
1479
1480The :class:`LoggerAdapter` class was not present in previous versions.
1481
Vinay Sajipfb7b5052010-09-17 12:45:26 +00001482.. _filters-contextual:
1483
Vinay Sajip957a47c2010-09-06 22:18:20 +00001484Using Filters to impart contextual information
1485^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1486
1487You can also add contextual information to log output using a user-defined
1488:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1489passed to them, including adding additional attributes which can then be output
1490using a suitable format string, or if needed a custom :class:`Formatter`.
1491
1492For example in a web application, the request being processed (or at least,
1493the interesting parts of it) can be stored in a threadlocal
1494(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1495add, say, information from the request - say, the remote IP address and remote
1496user's username - to the ``LogRecord``, using the attribute names 'ip' and
1497'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1498string can be used to get similar output to that shown above. Here's an example
1499script::
1500
1501 import logging
1502 from random import choice
1503
1504 class ContextFilter(logging.Filter):
1505 """
1506 This is a filter which injects contextual information into the log.
1507
1508 Rather than use actual contextual information, we just use random
1509 data in this demo.
1510 """
1511
1512 USERS = ['jim', 'fred', 'sheila']
1513 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1514
1515 def filter(self, record):
1516
1517 record.ip = choice(ContextFilter.IPS)
1518 record.user = choice(ContextFilter.USERS)
1519 return True
1520
1521 if __name__ == "__main__":
1522 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1523 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1524 { "ip" : "123.231.231.123", "user" : "sheila" })
1525 logging.basicConfig(level=logging.DEBUG,
1526 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1527 a1 = logging.getLogger("a.b.c")
1528 a2 = logging.getLogger("d.e.f")
1529
1530 f = ContextFilter()
1531 a1.addFilter(f)
1532 a2.addFilter(f)
1533 a1.debug("A debug message")
1534 a1.info("An info message with %s", "some parameters")
1535 for x in range(10):
1536 lvl = choice(levels)
1537 lvlname = logging.getLevelName(lvl)
1538 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1539
1540which, when run, produces something like::
1541
1542 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1543 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1544 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
1545 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
1546 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
1547 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
1548 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
1549 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
1550 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
1551 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
1552 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
1553 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
1554
1555
Vinay Sajip3a0dc302009-08-15 23:23:12 +00001556.. _multiple-processes:
1557
1558Logging to a single file from multiple processes
1559------------------------------------------------
1560
1561Although logging is thread-safe, and logging to a single file from multiple
1562threads in a single process *is* supported, logging to a single file from
1563*multiple processes* is *not* supported, because there is no standard way to
1564serialize access to a single file across multiple processes in Python. If you
1565need to log to a single file from multiple processes, the best way of doing
1566this is to have all the processes log to a :class:`SocketHandler`, and have a
1567separate process which implements a socket server which reads from the socket
1568and logs to file. (If you prefer, you can dedicate one thread in one of the
1569existing processes to perform this function.) The following section documents
1570this approach in more detail and includes a working socket receiver which can
1571be used as a starting point for you to adapt in your own applications.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001572
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001573If you are using a recent version of Python which includes the
1574:mod:`multiprocessing` module, you can write your own handler which uses the
1575:class:`Lock` class from this module to serialize access to the file from
1576your processes. The existing :class:`FileHandler` and subclasses do not make
1577use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip5e7f6452009-08-17 13:14:37 +00001578Note that at present, the :mod:`multiprocessing` module does not provide
1579working lock functionality on all platforms (see
1580http://bugs.python.org/issue3770).
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001581
Georg Brandl8ec7f652007-08-15 14:28:01 +00001582.. _network-logging:
1583
1584Sending and receiving logging events across a network
1585-----------------------------------------------------
1586
1587Let's say you want to send logging events across a network, and handle them at
1588the receiving end. A simple way of doing this is attaching a
1589:class:`SocketHandler` instance to the root logger at the sending end::
1590
Benjamin Petersona7b55a32009-02-20 03:31:23 +00001591 import logging, logging.handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +00001592
1593 rootLogger = logging.getLogger('')
1594 rootLogger.setLevel(logging.DEBUG)
1595 socketHandler = logging.handlers.SocketHandler('localhost',
1596 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1597 # don't bother with a formatter, since a socket handler sends the event as
1598 # an unformatted pickle
1599 rootLogger.addHandler(socketHandler)
1600
1601 # Now, we can log to the root logger, or any other logger. First the root...
1602 logging.info('Jackdaws love my big sphinx of quartz.')
1603
1604 # Now, define a couple of other loggers which might represent areas in your
1605 # application:
1606
1607 logger1 = logging.getLogger('myapp.area1')
1608 logger2 = logging.getLogger('myapp.area2')
1609
1610 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1611 logger1.info('How quickly daft jumping zebras vex.')
1612 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1613 logger2.error('The five boxing wizards jump quickly.')
1614
Georg Brandle152a772008-05-24 18:31:28 +00001615At the receiving end, you can set up a receiver using the :mod:`SocketServer`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001616module. Here is a basic working example::
1617
1618 import cPickle
1619 import logging
1620 import logging.handlers
Georg Brandle152a772008-05-24 18:31:28 +00001621 import SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001622 import struct
1623
1624
Georg Brandle152a772008-05-24 18:31:28 +00001625 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001626 """Handler for a streaming logging request.
1627
1628 This basically logs the record using whatever logging policy is
1629 configured locally.
1630 """
1631
1632 def handle(self):
1633 """
1634 Handle multiple requests - each expected to be a 4-byte length,
1635 followed by the LogRecord in pickle format. Logs the record
1636 according to whatever policy is configured locally.
1637 """
1638 while 1:
1639 chunk = self.connection.recv(4)
1640 if len(chunk) < 4:
1641 break
1642 slen = struct.unpack(">L", chunk)[0]
1643 chunk = self.connection.recv(slen)
1644 while len(chunk) < slen:
1645 chunk = chunk + self.connection.recv(slen - len(chunk))
1646 obj = self.unPickle(chunk)
1647 record = logging.makeLogRecord(obj)
1648 self.handleLogRecord(record)
1649
1650 def unPickle(self, data):
1651 return cPickle.loads(data)
1652
1653 def handleLogRecord(self, record):
1654 # if a name is specified, we use the named logger rather than the one
1655 # implied by the record.
1656 if self.server.logname is not None:
1657 name = self.server.logname
1658 else:
1659 name = record.name
1660 logger = logging.getLogger(name)
1661 # N.B. EVERY record gets logged. This is because Logger.handle
1662 # is normally called AFTER logger-level filtering. If you want
1663 # to do filtering, do it at the client end to save wasting
1664 # cycles and network bandwidth!
1665 logger.handle(record)
1666
Georg Brandle152a772008-05-24 18:31:28 +00001667 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001668 """simple TCP socket-based logging receiver suitable for testing.
1669 """
1670
1671 allow_reuse_address = 1
1672
1673 def __init__(self, host='localhost',
1674 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1675 handler=LogRecordStreamHandler):
Georg Brandle152a772008-05-24 18:31:28 +00001676 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001677 self.abort = 0
1678 self.timeout = 1
1679 self.logname = None
1680
1681 def serve_until_stopped(self):
1682 import select
1683 abort = 0
1684 while not abort:
1685 rd, wr, ex = select.select([self.socket.fileno()],
1686 [], [],
1687 self.timeout)
1688 if rd:
1689 self.handle_request()
1690 abort = self.abort
1691
1692 def main():
1693 logging.basicConfig(
1694 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1695 tcpserver = LogRecordSocketReceiver()
1696 print "About to start TCP server..."
1697 tcpserver.serve_until_stopped()
1698
1699 if __name__ == "__main__":
1700 main()
1701
1702First run the server, and then the client. On the client side, nothing is
1703printed on the console; on the server side, you should see something like::
1704
1705 About to start TCP server...
1706 59 root INFO Jackdaws love my big sphinx of quartz.
1707 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1708 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1709 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1710 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1711
Vinay Sajip80eed3e2010-07-06 15:08:55 +00001712Note that there are some security issues with pickle in some scenarios. If
1713these affect you, you can use an alternative serialization scheme by overriding
1714the :meth:`makePickle` method and implementing your alternative there, as
1715well as adapting the above script to use your alternative serialization.
1716
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00001717.. _arbitrary-object-messages:
1718
Vinay Sajipf778bec2009-09-22 17:23:41 +00001719Using arbitrary objects as messages
1720-----------------------------------
1721
1722In the preceding sections and examples, it has been assumed that the message
1723passed when logging the event is a string. However, this is not the only
1724possibility. You can pass an arbitrary object as a message, and its
1725:meth:`__str__` method will be called when the logging system needs to convert
1726it to a string representation. In fact, if you want to, you can avoid
1727computing a string representation altogether - for example, the
1728:class:`SocketHandler` emits an event by pickling it and sending it over the
1729wire.
1730
1731Optimization
1732------------
1733
1734Formatting of message arguments is deferred until it cannot be avoided.
1735However, computing the arguments passed to the logging method can also be
1736expensive, and you may want to avoid doing it if the logger will just throw
1737away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1738method which takes a level argument and returns true if the event would be
1739created by the Logger for that level of call. You can write code like this::
1740
1741 if logger.isEnabledFor(logging.DEBUG):
1742 logger.debug("Message with %s, %s", expensive_func1(),
1743 expensive_func2())
1744
1745so that if the logger's threshold is set above ``DEBUG``, the calls to
1746:func:`expensive_func1` and :func:`expensive_func2` are never made.
1747
1748There are other optimizations which can be made for specific applications which
1749need more precise control over what logging information is collected. Here's a
1750list of things you can do to avoid processing during logging which you don't
1751need:
1752
1753+-----------------------------------------------+----------------------------------------+
1754| What you don't want to collect | How to avoid collecting it |
1755+===============================================+========================================+
1756| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1757+-----------------------------------------------+----------------------------------------+
1758| Threading information. | Set ``logging.logThreads`` to ``0``. |
1759+-----------------------------------------------+----------------------------------------+
1760| Process information. | Set ``logging.logProcesses`` to ``0``. |
1761+-----------------------------------------------+----------------------------------------+
1762
1763Also note that the core logging module only includes the basic handlers. If
1764you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1765take up any memory.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001766
Vinay Sajip4b782332009-01-19 06:49:19 +00001767.. _handler:
1768
Georg Brandl8ec7f652007-08-15 14:28:01 +00001769Handler Objects
1770---------------
1771
1772Handlers have the following attributes and methods. Note that :class:`Handler`
1773is never instantiated directly; this class acts as a base for more useful
1774subclasses. However, the :meth:`__init__` method in subclasses needs to call
1775:meth:`Handler.__init__`.
1776
1777
1778.. method:: Handler.__init__(level=NOTSET)
1779
1780 Initializes the :class:`Handler` instance by setting its level, setting the list
1781 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1782 serializing access to an I/O mechanism.
1783
1784
1785.. method:: Handler.createLock()
1786
1787 Initializes a thread lock which can be used to serialize access to underlying
1788 I/O functionality which may not be threadsafe.
1789
1790
1791.. method:: Handler.acquire()
1792
1793 Acquires the thread lock created with :meth:`createLock`.
1794
1795
1796.. method:: Handler.release()
1797
1798 Releases the thread lock acquired with :meth:`acquire`.
1799
1800
1801.. method:: Handler.setLevel(lvl)
1802
1803 Sets the threshold for this handler to *lvl*. Logging messages which are less
1804 severe than *lvl* will be ignored. When a handler is created, the level is set
1805 to :const:`NOTSET` (which causes all messages to be processed).
1806
1807
1808.. method:: Handler.setFormatter(form)
1809
1810 Sets the :class:`Formatter` for this handler to *form*.
1811
1812
1813.. method:: Handler.addFilter(filt)
1814
1815 Adds the specified filter *filt* to this handler.
1816
1817
1818.. method:: Handler.removeFilter(filt)
1819
1820 Removes the specified filter *filt* from this handler.
1821
1822
1823.. method:: Handler.filter(record)
1824
1825 Applies this handler's filters to the record and returns a true value if the
1826 record is to be processed.
1827
1828
1829.. method:: Handler.flush()
1830
1831 Ensure all logging output has been flushed. This version does nothing and is
1832 intended to be implemented by subclasses.
1833
1834
1835.. method:: Handler.close()
1836
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001837 Tidy up any resources used by the handler. This version does no output but
1838 removes the handler from an internal list of handlers which is closed when
1839 :func:`shutdown` is called. Subclasses should ensure that this gets called
1840 from overridden :meth:`close` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001841
1842
1843.. method:: Handler.handle(record)
1844
1845 Conditionally emits the specified logging record, depending on filters which may
1846 have been added to the handler. Wraps the actual emission of the record with
1847 acquisition/release of the I/O thread lock.
1848
1849
1850.. method:: Handler.handleError(record)
1851
1852 This method should be called from handlers when an exception is encountered
1853 during an :meth:`emit` call. By default it does nothing, which means that
1854 exceptions get silently ignored. This is what is mostly wanted for a logging
1855 system - most users will not care about errors in the logging system, they are
1856 more interested in application errors. You could, however, replace this with a
1857 custom handler if you wish. The specified record is the one which was being
1858 processed when the exception occurred.
1859
1860
1861.. method:: Handler.format(record)
1862
1863 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1864 default formatter for the module.
1865
1866
1867.. method:: Handler.emit(record)
1868
1869 Do whatever it takes to actually log the specified logging record. This version
1870 is intended to be implemented by subclasses and so raises a
1871 :exc:`NotImplementedError`.
1872
1873
Vinay Sajip4b782332009-01-19 06:49:19 +00001874.. _stream-handler:
1875
Georg Brandl8ec7f652007-08-15 14:28:01 +00001876StreamHandler
1877^^^^^^^^^^^^^
1878
1879The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1880sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1881file-like object (or, more precisely, any object which supports :meth:`write`
1882and :meth:`flush` methods).
1883
1884
Vinay Sajip0c6a0e32009-12-17 14:52:00 +00001885.. currentmodule:: logging
1886
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001887.. class:: StreamHandler([stream])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001888
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001889 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001890 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1891 will be used.
1892
1893
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001894 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001895
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001896 If a formatter is specified, it is used to format the record. The record
1897 is then written to the stream with a trailing newline. If exception
1898 information is present, it is formatted using
1899 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001900
1901
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001902 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001903
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001904 Flushes the stream by calling its :meth:`flush` method. Note that the
1905 :meth:`close` method is inherited from :class:`Handler` and so does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001906 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001907
1908
Vinay Sajip4b782332009-01-19 06:49:19 +00001909.. _file-handler:
1910
Georg Brandl8ec7f652007-08-15 14:28:01 +00001911FileHandler
1912^^^^^^^^^^^
1913
1914The :class:`FileHandler` class, located in the core :mod:`logging` package,
1915sends logging output to a disk file. It inherits the output functionality from
1916:class:`StreamHandler`.
1917
1918
Vinay Sajipf38ba782008-01-24 12:38:30 +00001919.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001920
1921 Returns a new instance of the :class:`FileHandler` class. The specified file is
1922 opened and used as the stream for logging. If *mode* is not specified,
1923 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001924 with that encoding. If *delay* is true, then file opening is deferred until the
1925 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001926
Vinay Sajip59584c42009-08-14 11:33:54 +00001927 .. versionchanged:: 2.6
1928 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001929
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001930 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001931
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001932 Closes the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001933
1934
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001935 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001936
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001937 Outputs the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001938
Vinay Sajip4b782332009-01-19 06:49:19 +00001939.. _null-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001940
Vinay Sajip51104862009-01-02 18:53:04 +00001941NullHandler
1942^^^^^^^^^^^
1943
1944.. versionadded:: 2.7
1945
1946The :class:`NullHandler` class, located in the core :mod:`logging` package,
1947does not do any formatting or output. It is essentially a "no-op" handler
1948for use by library developers.
1949
1950
1951.. class:: NullHandler()
1952
1953 Returns a new instance of the :class:`NullHandler` class.
1954
1955
1956 .. method:: emit(record)
1957
1958 This method does nothing.
1959
Vinay Sajip99505c82009-01-10 13:38:04 +00001960See :ref:`library-config` for more information on how to use
1961:class:`NullHandler`.
1962
Vinay Sajip4b782332009-01-19 06:49:19 +00001963.. _watched-file-handler:
1964
Georg Brandl8ec7f652007-08-15 14:28:01 +00001965WatchedFileHandler
1966^^^^^^^^^^^^^^^^^^
1967
1968.. versionadded:: 2.6
1969
Vinay Sajipb1a15e42009-01-15 23:04:47 +00001970.. currentmodule:: logging.handlers
Vinay Sajip51104862009-01-02 18:53:04 +00001971
Georg Brandl8ec7f652007-08-15 14:28:01 +00001972The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1973module, is a :class:`FileHandler` which watches the file it is logging to. If
1974the file changes, it is closed and reopened using the file name.
1975
1976A file change can happen because of usage of programs such as *newsyslog* and
1977*logrotate* which perform log file rotation. This handler, intended for use
1978under Unix/Linux, watches the file to see if it has changed since the last emit.
1979(A file is deemed to have changed if its device or inode have changed.) If the
1980file has changed, the old file stream is closed, and the file opened to get a
1981new stream.
1982
1983This handler is not appropriate for use under Windows, because under Windows
1984open log files cannot be moved or renamed - logging opens the files with
1985exclusive locks - and so there is no need for such a handler. Furthermore,
1986*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1987this value.
1988
1989
Vinay Sajipf38ba782008-01-24 12:38:30 +00001990.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001991
1992 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1993 file is opened and used as the stream for logging. If *mode* is not specified,
1994 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001995 with that encoding. If *delay* is true, then file opening is deferred until the
1996 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001997
Vinay Sajip59584c42009-08-14 11:33:54 +00001998 .. versionchanged:: 2.6
1999 *delay* was added.
2000
Georg Brandl8ec7f652007-08-15 14:28:01 +00002001
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002002 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002003
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002004 Outputs the record to the file, but first checks to see if the file has
2005 changed. If it has, the existing stream is flushed and closed and the
2006 file opened again, before outputting the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002007
Vinay Sajip4b782332009-01-19 06:49:19 +00002008.. _rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002009
2010RotatingFileHandler
2011^^^^^^^^^^^^^^^^^^^
2012
2013The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2014module, supports rotation of disk log files.
2015
2016
Vinay Sajipf38ba782008-01-24 12:38:30 +00002017.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002018
2019 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2020 file is opened and used as the stream for logging. If *mode* is not specified,
Vinay Sajipf38ba782008-01-24 12:38:30 +00002021 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2022 with that encoding. If *delay* is true, then file opening is deferred until the
2023 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002024
2025 You can use the *maxBytes* and *backupCount* values to allow the file to
2026 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2027 the file is closed and a new file is silently opened for output. Rollover occurs
2028 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2029 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2030 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2031 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2032 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2033 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2034 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2035 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2036 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2037
Vinay Sajip59584c42009-08-14 11:33:54 +00002038 .. versionchanged:: 2.6
2039 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002040
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002041 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002042
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002043 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002044
2045
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002046 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002047
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002048 Outputs the record to the file, catering for rollover as described
2049 previously.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002050
Vinay Sajip4b782332009-01-19 06:49:19 +00002051.. _timed-rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002052
2053TimedRotatingFileHandler
2054^^^^^^^^^^^^^^^^^^^^^^^^
2055
2056The :class:`TimedRotatingFileHandler` class, located in the
2057:mod:`logging.handlers` module, supports rotation of disk log files at certain
2058timed intervals.
2059
2060
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00002061.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002062
2063 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2064 specified file is opened and used as the stream for logging. On rotating it also
2065 sets the filename suffix. Rotating happens based on the product of *when* and
2066 *interval*.
2067
2068 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandld77554f2008-06-06 07:34:50 +00002069 values is below. Note that they are not case sensitive.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002070
Georg Brandl72780a42008-03-02 13:41:39 +00002071 +----------------+-----------------------+
2072 | Value | Type of interval |
2073 +================+=======================+
2074 | ``'S'`` | Seconds |
2075 +----------------+-----------------------+
2076 | ``'M'`` | Minutes |
2077 +----------------+-----------------------+
2078 | ``'H'`` | Hours |
2079 +----------------+-----------------------+
2080 | ``'D'`` | Days |
2081 +----------------+-----------------------+
2082 | ``'W'`` | Week day (0=Monday) |
2083 +----------------+-----------------------+
2084 | ``'midnight'`` | Roll over at midnight |
2085 +----------------+-----------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00002086
Georg Brandle6dab2a2008-03-02 14:15:04 +00002087 The system will save old log files by appending extensions to the filename.
2088 The extensions are date-and-time based, using the strftime format
Vinay Sajip89a01cd2008-04-02 21:17:25 +00002089 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Vinay Sajip2a649f92008-07-18 09:00:35 +00002090 rollover interval.
Vinay Sajipecfa08f2010-03-12 09:16:10 +00002091
2092 When computing the next rollover time for the first time (when the handler
2093 is created), the last modification time of an existing log file, or else
2094 the current time, is used to compute when the next rotation will occur.
2095
Georg Brandld77554f2008-06-06 07:34:50 +00002096 If the *utc* argument is true, times in UTC will be used; otherwise
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00002097 local time is used.
2098
2099 If *backupCount* is nonzero, at most *backupCount* files
Vinay Sajip89a01cd2008-04-02 21:17:25 +00002100 will be kept, and if more would be created when rollover occurs, the oldest
2101 one is deleted. The deletion logic uses the interval to determine which
2102 files to delete, so changing the interval may leave old files lying around.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002103
Vinay Sajip59584c42009-08-14 11:33:54 +00002104 If *delay* is true, then file opening is deferred until the first call to
2105 :meth:`emit`.
2106
2107 .. versionchanged:: 2.6
2108 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002109
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002110 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002111
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002112 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002113
2114
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002115 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002116
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002117 Outputs the record to the file, catering for rollover as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002118
2119
Vinay Sajip4b782332009-01-19 06:49:19 +00002120.. _socket-handler:
2121
Georg Brandl8ec7f652007-08-15 14:28:01 +00002122SocketHandler
2123^^^^^^^^^^^^^
2124
2125The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2126sends logging output to a network socket. The base class uses a TCP socket.
2127
2128
2129.. class:: SocketHandler(host, port)
2130
2131 Returns a new instance of the :class:`SocketHandler` class intended to
2132 communicate with a remote machine whose address is given by *host* and *port*.
2133
2134
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002135 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002136
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002137 Closes the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002138
2139
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002140 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002141
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002142 Pickles the record's attribute dictionary and writes it to the socket in
2143 binary format. If there is an error with the socket, silently drops the
2144 packet. If the connection was previously lost, re-establishes the
2145 connection. To unpickle the record at the receiving end into a
2146 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002147
2148
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002149 .. method:: handleError()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002150
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002151 Handles an error which has occurred during :meth:`emit`. The most likely
2152 cause is a lost connection. Closes the socket so that we can retry on the
2153 next event.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002154
2155
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002156 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002157
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002158 This is a factory method which allows subclasses to define the precise
2159 type of socket they want. The default implementation creates a TCP socket
2160 (:const:`socket.SOCK_STREAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002161
2162
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002163 .. method:: makePickle(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002164
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002165 Pickles the record's attribute dictionary in binary format with a length
2166 prefix, and returns it ready for transmission across the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002167
Vinay Sajip86aa9052010-06-29 15:13:14 +00002168 Note that pickles aren't completely secure. If you are concerned about
2169 security, you may want to override this method to implement a more secure
2170 mechanism. For example, you can sign pickles using HMAC and then verify
2171 them on the receiving end, or alternatively you can disable unpickling of
2172 global objects on the receiving end.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002173
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002174 .. method:: send(packet)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002175
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002176 Send a pickled string *packet* to the socket. This function allows for
2177 partial sends which can happen when the network is busy.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002178
2179
Vinay Sajip4b782332009-01-19 06:49:19 +00002180.. _datagram-handler:
2181
Georg Brandl8ec7f652007-08-15 14:28:01 +00002182DatagramHandler
2183^^^^^^^^^^^^^^^
2184
2185The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2186module, inherits from :class:`SocketHandler` to support sending logging messages
2187over UDP sockets.
2188
2189
2190.. class:: DatagramHandler(host, port)
2191
2192 Returns a new instance of the :class:`DatagramHandler` class intended to
2193 communicate with a remote machine whose address is given by *host* and *port*.
2194
2195
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002196 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002197
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002198 Pickles the record's attribute dictionary and writes it to the socket in
2199 binary format. If there is an error with the socket, silently drops the
2200 packet. To unpickle the record at the receiving end into a
2201 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002202
2203
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002204 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002205
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002206 The factory method of :class:`SocketHandler` is here overridden to create
2207 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002208
2209
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002210 .. method:: send(s)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002211
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002212 Send a pickled string to a socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002213
2214
Vinay Sajip4b782332009-01-19 06:49:19 +00002215.. _syslog-handler:
2216
Georg Brandl8ec7f652007-08-15 14:28:01 +00002217SysLogHandler
2218^^^^^^^^^^^^^
2219
2220The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2221supports sending logging messages to a remote or local Unix syslog.
2222
2223
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002224.. class:: SysLogHandler([address[, facility[, socktype]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002225
2226 Returns a new instance of the :class:`SysLogHandler` class intended to
2227 communicate with a remote Unix machine whose address is given by *address* in
2228 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002229 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl8ec7f652007-08-15 14:28:01 +00002230 alternative to providing a ``(host, port)`` tuple is providing an address as a
2231 string, for example "/dev/log". In this case, a Unix domain socket is used to
2232 send the message to the syslog. If *facility* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002233 :const:`LOG_USER` is used. The type of socket opened depends on the
2234 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2235 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2236 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2237
2238 .. versionchanged:: 2.7
2239 *socktype* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002240
2241
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002242 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002243
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002244 Closes the socket to the remote host.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002245
2246
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002247 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002248
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002249 The record is formatted, and then sent to the syslog server. If exception
2250 information is present, it is *not* sent to the server.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002251
2252
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002253 .. method:: encodePriority(facility, priority)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002254
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002255 Encodes the facility and priority into an integer. You can pass in strings
2256 or integers - if strings are passed, internal mapping dictionaries are
2257 used to convert them to integers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002258
Vinay Sajipa3c39c02010-03-24 15:10:40 +00002259 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2260 mirror the values defined in the ``sys/syslog.h`` header file.
Vinay Sajipb0623d62010-03-24 14:31:21 +00002261
Georg Brandld3bab6a2010-04-02 09:03:18 +00002262 **Priorities**
2263
Vinay Sajipb0623d62010-03-24 14:31:21 +00002264 +--------------------------+---------------+
2265 | Name (string) | Symbolic value|
2266 +==========================+===============+
2267 | ``alert`` | LOG_ALERT |
2268 +--------------------------+---------------+
2269 | ``crit`` or ``critical`` | LOG_CRIT |
2270 +--------------------------+---------------+
2271 | ``debug`` | LOG_DEBUG |
2272 +--------------------------+---------------+
2273 | ``emerg`` or ``panic`` | LOG_EMERG |
2274 +--------------------------+---------------+
2275 | ``err`` or ``error`` | LOG_ERR |
2276 +--------------------------+---------------+
2277 | ``info`` | LOG_INFO |
2278 +--------------------------+---------------+
2279 | ``notice`` | LOG_NOTICE |
2280 +--------------------------+---------------+
2281 | ``warn`` or ``warning`` | LOG_WARNING |
2282 +--------------------------+---------------+
2283
Georg Brandld3bab6a2010-04-02 09:03:18 +00002284 **Facilities**
2285
Vinay Sajipb0623d62010-03-24 14:31:21 +00002286 +---------------+---------------+
2287 | Name (string) | Symbolic value|
2288 +===============+===============+
2289 | ``auth`` | LOG_AUTH |
2290 +---------------+---------------+
2291 | ``authpriv`` | LOG_AUTHPRIV |
2292 +---------------+---------------+
2293 | ``cron`` | LOG_CRON |
2294 +---------------+---------------+
2295 | ``daemon`` | LOG_DAEMON |
2296 +---------------+---------------+
2297 | ``ftp`` | LOG_FTP |
2298 +---------------+---------------+
2299 | ``kern`` | LOG_KERN |
2300 +---------------+---------------+
2301 | ``lpr`` | LOG_LPR |
2302 +---------------+---------------+
2303 | ``mail`` | LOG_MAIL |
2304 +---------------+---------------+
2305 | ``news`` | LOG_NEWS |
2306 +---------------+---------------+
2307 | ``syslog`` | LOG_SYSLOG |
2308 +---------------+---------------+
2309 | ``user`` | LOG_USER |
2310 +---------------+---------------+
2311 | ``uucp`` | LOG_UUCP |
2312 +---------------+---------------+
2313 | ``local0`` | LOG_LOCAL0 |
2314 +---------------+---------------+
2315 | ``local1`` | LOG_LOCAL1 |
2316 +---------------+---------------+
2317 | ``local2`` | LOG_LOCAL2 |
2318 +---------------+---------------+
2319 | ``local3`` | LOG_LOCAL3 |
2320 +---------------+---------------+
2321 | ``local4`` | LOG_LOCAL4 |
2322 +---------------+---------------+
2323 | ``local5`` | LOG_LOCAL5 |
2324 +---------------+---------------+
2325 | ``local6`` | LOG_LOCAL6 |
2326 +---------------+---------------+
2327 | ``local7`` | LOG_LOCAL7 |
2328 +---------------+---------------+
2329
Vinay Sajip66d19e22010-03-24 17:36:35 +00002330 .. method:: mapPriority(levelname)
2331
2332 Maps a logging level name to a syslog priority name.
2333 You may need to override this if you are using custom levels, or
2334 if the default algorithm is not suitable for your needs. The
2335 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2336 ``CRITICAL`` to the equivalent syslog names, and all other level
2337 names to "warning".
Georg Brandl8ec7f652007-08-15 14:28:01 +00002338
Vinay Sajip4b782332009-01-19 06:49:19 +00002339.. _nt-eventlog-handler:
2340
Georg Brandl8ec7f652007-08-15 14:28:01 +00002341NTEventLogHandler
2342^^^^^^^^^^^^^^^^^
2343
2344The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2345module, supports sending logging messages to a local Windows NT, Windows 2000 or
2346Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2347extensions for Python installed.
2348
2349
2350.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
2351
2352 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2353 used to define the application name as it appears in the event log. An
2354 appropriate registry entry is created using this name. The *dllname* should give
2355 the fully qualified pathname of a .dll or .exe which contains message
2356 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2357 - this is installed with the Win32 extensions and contains some basic
2358 placeholder message definitions. Note that use of these placeholders will make
2359 your event logs big, as the entire message source is held in the log. If you
2360 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2361 contains the message definitions you want to use in the event log). The
2362 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2363 defaults to ``'Application'``.
2364
2365
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002366 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002367
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002368 At this point, you can remove the application name from the registry as a
2369 source of event log entries. However, if you do this, you will not be able
2370 to see the events as you intended in the Event Log Viewer - it needs to be
2371 able to access the registry to get the .dll name. The current version does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00002372 not do this.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002373
2374
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002375 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002376
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002377 Determines the message ID, event category and event type, and then logs
2378 the message in the NT event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002379
2380
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002381 .. method:: getEventCategory(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002382
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002383 Returns the event category for the record. Override this if you want to
2384 specify your own categories. This version returns 0.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002385
2386
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002387 .. method:: getEventType(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002388
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002389 Returns the event type for the record. Override this if you want to
2390 specify your own types. This version does a mapping using the handler's
2391 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2392 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2393 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2394 your own levels, you will either need to override this method or place a
2395 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002396
2397
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002398 .. method:: getMessageID(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002399
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002400 Returns the message ID for the record. If you are using your own messages,
2401 you could do this by having the *msg* passed to the logger being an ID
2402 rather than a format string. Then, in here, you could use a dictionary
2403 lookup to get the message ID. This version returns 1, which is the base
2404 message ID in :file:`win32service.pyd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002405
Vinay Sajip4b782332009-01-19 06:49:19 +00002406.. _smtp-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002407
2408SMTPHandler
2409^^^^^^^^^^^
2410
2411The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2412supports sending logging messages to an email address via SMTP.
2413
2414
2415.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
2416
2417 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2418 initialized with the from and to addresses and subject line of the email. The
2419 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2420 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2421 the standard SMTP port is used. If your SMTP server requires authentication, you
2422 can specify a (username, password) tuple for the *credentials* argument.
2423
2424 .. versionchanged:: 2.6
2425 *credentials* was added.
2426
2427
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002428 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002429
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002430 Formats the record and sends it to the specified addressees.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002431
2432
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002433 .. method:: getSubject(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002434
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002435 If you want to specify a subject line which is record-dependent, override
2436 this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002437
Vinay Sajip4b782332009-01-19 06:49:19 +00002438.. _memory-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002439
2440MemoryHandler
2441^^^^^^^^^^^^^
2442
2443The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2444supports buffering of logging records in memory, periodically flushing them to a
2445:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2446event of a certain severity or greater is seen.
2447
2448:class:`MemoryHandler` is a subclass of the more general
2449:class:`BufferingHandler`, which is an abstract class. This buffers logging
2450records in memory. Whenever each record is added to the buffer, a check is made
2451by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2452should, then :meth:`flush` is expected to do the needful.
2453
2454
2455.. class:: BufferingHandler(capacity)
2456
2457 Initializes the handler with a buffer of the specified capacity.
2458
2459
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002460 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002461
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002462 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2463 calls :meth:`flush` to process the buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002464
2465
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002466 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002467
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002468 You can override this to implement custom flushing behavior. This version
2469 just zaps the buffer to empty.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002470
2471
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002472 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002473
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002474 Returns true if the buffer is up to capacity. This method can be
2475 overridden to implement custom flushing strategies.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002476
2477
2478.. class:: MemoryHandler(capacity[, flushLevel [, target]])
2479
2480 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2481 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2482 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2483 set using :meth:`setTarget` before this handler does anything useful.
2484
2485
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002486 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002487
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002488 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2489 buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002490
2491
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002492 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002493
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002494 For a :class:`MemoryHandler`, flushing means just sending the buffered
2495 records to the target, if there is one. Override if you want different
2496 behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002497
2498
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002499 .. method:: setTarget(target)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002500
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002501 Sets the target handler for this handler.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002502
2503
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002504 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002505
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002506 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002507
2508
Vinay Sajip4b782332009-01-19 06:49:19 +00002509.. _http-handler:
2510
Georg Brandl8ec7f652007-08-15 14:28:01 +00002511HTTPHandler
2512^^^^^^^^^^^
2513
2514The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2515supports sending logging messages to a Web server, using either ``GET`` or
2516``POST`` semantics.
2517
2518
2519.. class:: HTTPHandler(host, url[, method])
2520
2521 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2522 initialized with a host address, url and HTTP method. The *host* can be of the
2523 form ``host:port``, should you need to use a specific port number. If no
2524 *method* is specified, ``GET`` is used.
2525
2526
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002527 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002528
Senthil Kumaranbd13f452010-08-09 20:14:11 +00002529 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002530
2531
Vinay Sajip4b782332009-01-19 06:49:19 +00002532.. _formatter:
Georg Brandlc37f2882007-12-04 17:46:27 +00002533
Georg Brandl8ec7f652007-08-15 14:28:01 +00002534Formatter Objects
2535-----------------
2536
Georg Brandl430effb2009-01-01 13:05:13 +00002537.. currentmodule:: logging
2538
Georg Brandl8ec7f652007-08-15 14:28:01 +00002539:class:`Formatter`\ s have the following attributes and methods. They are
2540responsible for converting a :class:`LogRecord` to (usually) a string which can
2541be interpreted by either a human or an external system. The base
2542:class:`Formatter` allows a formatting string to be specified. If none is
2543supplied, the default value of ``'%(message)s'`` is used.
2544
2545A Formatter can be initialized with a format string which makes use of knowledge
2546of the :class:`LogRecord` attributes - such as the default value mentioned above
2547making use of the fact that the user's message and arguments are pre-formatted
2548into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti062d2b52009-12-19 22:41:49 +00002549standard Python %-style mapping keys. See section :ref:`string-formatting`
Georg Brandl8ec7f652007-08-15 14:28:01 +00002550for more information on string formatting.
2551
2552Currently, the useful mapping keys in a :class:`LogRecord` are:
2553
2554+-------------------------+-----------------------------------------------+
2555| Format | Description |
2556+=========================+===============================================+
2557| ``%(name)s`` | Name of the logger (logging channel). |
2558+-------------------------+-----------------------------------------------+
2559| ``%(levelno)s`` | Numeric logging level for the message |
2560| | (:const:`DEBUG`, :const:`INFO`, |
2561| | :const:`WARNING`, :const:`ERROR`, |
2562| | :const:`CRITICAL`). |
2563+-------------------------+-----------------------------------------------+
2564| ``%(levelname)s`` | Text logging level for the message |
2565| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2566| | ``'ERROR'``, ``'CRITICAL'``). |
2567+-------------------------+-----------------------------------------------+
2568| ``%(pathname)s`` | Full pathname of the source file where the |
2569| | logging call was issued (if available). |
2570+-------------------------+-----------------------------------------------+
2571| ``%(filename)s`` | Filename portion of pathname. |
2572+-------------------------+-----------------------------------------------+
2573| ``%(module)s`` | Module (name portion of filename). |
2574+-------------------------+-----------------------------------------------+
2575| ``%(funcName)s`` | Name of function containing the logging call. |
2576+-------------------------+-----------------------------------------------+
2577| ``%(lineno)d`` | Source line number where the logging call was |
2578| | issued (if available). |
2579+-------------------------+-----------------------------------------------+
2580| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2581| | (as returned by :func:`time.time`). |
2582+-------------------------+-----------------------------------------------+
2583| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2584| | created, relative to the time the logging |
2585| | module was loaded. |
2586+-------------------------+-----------------------------------------------+
2587| ``%(asctime)s`` | Human-readable time when the |
2588| | :class:`LogRecord` was created. By default |
2589| | this is of the form "2003-07-08 16:49:45,896" |
2590| | (the numbers after the comma are millisecond |
2591| | portion of the time). |
2592+-------------------------+-----------------------------------------------+
2593| ``%(msecs)d`` | Millisecond portion of the time when the |
2594| | :class:`LogRecord` was created. |
2595+-------------------------+-----------------------------------------------+
2596| ``%(thread)d`` | Thread ID (if available). |
2597+-------------------------+-----------------------------------------------+
2598| ``%(threadName)s`` | Thread name (if available). |
2599+-------------------------+-----------------------------------------------+
2600| ``%(process)d`` | Process ID (if available). |
2601+-------------------------+-----------------------------------------------+
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002602| ``%(processName)s`` | Process name (if available). |
2603+-------------------------+-----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00002604| ``%(message)s`` | The logged message, computed as ``msg % |
2605| | args``. |
2606+-------------------------+-----------------------------------------------+
2607
2608.. versionchanged:: 2.5
2609 *funcName* was added.
2610
2611
2612.. class:: Formatter([fmt[, datefmt]])
2613
2614 Returns a new instance of the :class:`Formatter` class. The instance is
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002615 initialized with a format string for the message as a whole, as well as a
2616 format string for the date/time portion of a message. If no *fmt* is
2617 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
2618 ISO8601 date format is used.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002619
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002620 .. method:: format(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002621
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002622 The record's attribute dictionary is used as the operand to a string
2623 formatting operation. Returns the resulting string. Before formatting the
2624 dictionary, a couple of preparatory steps are carried out. The *message*
2625 attribute of the record is computed using *msg* % *args*. If the
2626 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2627 to format the event time. If there is exception information, it is
2628 formatted using :meth:`formatException` and appended to the message. Note
2629 that the formatted exception information is cached in attribute
2630 *exc_text*. This is useful because the exception information can be
2631 pickled and sent across the wire, but you should be careful if you have
2632 more than one :class:`Formatter` subclass which customizes the formatting
2633 of exception information. In this case, you will have to clear the cached
2634 value after a formatter has done its formatting, so that the next
2635 formatter to handle the event doesn't use the cached value but
2636 recalculates it afresh.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002637
2638
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002639 .. method:: formatTime(record[, datefmt])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002640
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002641 This method should be called from :meth:`format` by a formatter which
2642 wants to make use of a formatted time. This method can be overridden in
2643 formatters to provide for any specific requirement, but the basic behavior
2644 is as follows: if *datefmt* (a string) is specified, it is used with
2645 :func:`time.strftime` to format the creation time of the
2646 record. Otherwise, the ISO8601 format is used. The resulting string is
2647 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002648
2649
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002650 .. method:: formatException(exc_info)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002651
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002652 Formats the specified exception information (a standard exception tuple as
2653 returned by :func:`sys.exc_info`) as a string. This default implementation
2654 just uses :func:`traceback.print_exception`. The resulting string is
2655 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002656
Vinay Sajip4b782332009-01-19 06:49:19 +00002657.. _filter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002658
2659Filter Objects
2660--------------
2661
Vinay Sajipfb7b5052010-09-17 12:45:26 +00002662:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
Georg Brandl8ec7f652007-08-15 14:28:01 +00002663more sophisticated filtering than is provided by levels. The base filter class
2664only allows events which are below a certain point in the logger hierarchy. For
2665example, a filter initialized with "A.B" will allow events logged by loggers
2666"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2667initialized with the empty string, all events are passed.
2668
2669
2670.. class:: Filter([name])
2671
2672 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2673 names a logger which, together with its children, will have its events allowed
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002674 through the filter. If *name* is the empty string, allows every event.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002675
2676
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002677 .. method:: filter(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002678
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002679 Is the specified record to be logged? Returns zero for no, nonzero for
2680 yes. If deemed appropriate, the record may be modified in-place by this
2681 method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002682
Vinay Sajip3478ac02010-08-19 19:17:41 +00002683Note that filters attached to handlers are consulted whenever an event is
2684emitted by the handler, whereas filters attached to loggers are consulted
2685whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
2686etc.) This means that events which have been generated by descendant loggers
2687will not be filtered by a logger's filter setting, unless the filter has also
2688been applied to those descendant loggers.
2689
Vinay Sajipfb7b5052010-09-17 12:45:26 +00002690Other uses for filters
2691^^^^^^^^^^^^^^^^^^^^^^
2692
2693Although filters are used primarily to filter records based on more
2694sophisticated criteria than levels, they get to see every record which is
2695processed by the handler or logger they're attached to: this can be useful if
2696you want to do things like counting how many records were processed by a
2697particular logger or handler, or adding, changing or removing attributes in
2698the LogRecord being processed. Obviously changing the LogRecord needs to be
2699done with some care, but it does allow the injection of contextual information
2700into logs (see :ref:`filters-contextual`).
2701
Vinay Sajip4b782332009-01-19 06:49:19 +00002702.. _log-record:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002703
2704LogRecord Objects
2705-----------------
2706
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002707:class:`LogRecord` instances are created automatically by the :class:`Logger`
2708every time something is logged, and can be created manually via
2709:func:`makeLogRecord` (for example, from a pickled event received over the
2710wire).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002711
2712
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002713.. class::
2714 LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func=None])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002715
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002716 Contains all the information pertinent to the event being logged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002717
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002718 The primary information is passed in :attr:`msg` and :attr:`args`, which
2719 are combined using ``msg % args`` to create the :attr:`message` field of the
2720 record.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002721
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002722 .. attribute:: args
2723
2724 Tuple of arguments to be used in formatting :attr:`msg`.
2725
2726 .. attribute:: exc_info
2727
2728 Exception tuple (à la `sys.exc_info`) or `None` if no exception
2729 information is availble.
2730
2731 .. attribute:: func
2732
2733 Name of the function of origin (i.e. in which the logging call was made).
2734
2735 .. attribute:: lineno
2736
2737 Line number in the source file of origin.
2738
2739 .. attribute:: lvl
2740
2741 Numeric logging level.
2742
2743 .. attribute:: message
2744
2745 Bound to the result of :meth:`getMessage` when
2746 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
2747
2748 .. attribute:: msg
2749
2750 User-supplied :ref:`format string<string-formatting>` or arbitrary object
2751 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
2752
2753 .. attribute:: name
2754
2755 Name of the logger that emitted the record.
2756
2757 .. attribute:: pathname
2758
2759 Absolute pathname of the source file of origin.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002760
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002761 .. method:: getMessage()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002762
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002763 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajipfe08e6f2010-09-11 10:25:28 +00002764 user-supplied arguments with the message. If the user-supplied message
2765 argument to the logging call is not a string, :func:`str` is called on it to
2766 convert it to a string. This allows use of user-defined classes as
2767 messages, whose ``__str__`` method can return the actual format string to
2768 be used.
2769
2770 .. versionchanged:: 2.5
2771 *func* was added.
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002772
Vinay Sajip4b782332009-01-19 06:49:19 +00002773.. _logger-adapter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002774
Vinay Sajipc7403352008-01-18 15:54:14 +00002775LoggerAdapter Objects
2776---------------------
2777
2778.. versionadded:: 2.6
2779
2780:class:`LoggerAdapter` instances are used to conveniently pass contextual
Vinay Sajip733024a2008-01-21 17:39:22 +00002781information into logging calls. For a usage example , see the section on
2782`adding contextual information to your logging output`__.
2783
2784__ context-info_
Vinay Sajipc7403352008-01-18 15:54:14 +00002785
2786.. class:: LoggerAdapter(logger, extra)
2787
2788 Returns an instance of :class:`LoggerAdapter` initialized with an
2789 underlying :class:`Logger` instance and a dict-like object.
2790
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002791 .. method:: process(msg, kwargs)
Vinay Sajipc7403352008-01-18 15:54:14 +00002792
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002793 Modifies the message and/or keyword arguments passed to a logging call in
2794 order to insert contextual information. This implementation takes the object
2795 passed as *extra* to the constructor and adds it to *kwargs* using key
2796 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2797 (possibly modified) versions of the arguments passed in.
Vinay Sajipc7403352008-01-18 15:54:14 +00002798
2799In addition to the above, :class:`LoggerAdapter` supports all the logging
2800methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2801:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2802methods have the same signatures as their counterparts in :class:`Logger`, so
2803you can use the two types of instances interchangeably.
2804
Vinay Sajip804899b2010-03-22 15:29:01 +00002805.. versionchanged:: 2.7
2806
2807The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method
2808delegates to the underlying logger.
2809
Georg Brandl8ec7f652007-08-15 14:28:01 +00002810
2811Thread Safety
2812-------------
2813
2814The logging module is intended to be thread-safe without any special work
2815needing to be done by its clients. It achieves this though using threading
2816locks; there is one lock to serialize access to the module's shared data, and
2817each handler also creates a lock to serialize access to its underlying I/O.
2818
Vinay Sajip353a85f2009-04-03 21:58:16 +00002819If you are implementing asynchronous signal handlers using the :mod:`signal`
2820module, you may not be able to use logging from within such handlers. This is
2821because lock implementations in the :mod:`threading` module are not always
2822re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002823
Vinay Sajip61afd262010-02-19 23:53:17 +00002824
2825Integration with the warnings module
2826------------------------------------
2827
2828The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2829with the :mod:`warnings` module.
2830
2831.. function:: captureWarnings(capture)
2832
2833 This function is used to turn the capture of warnings by logging on and
2834 off.
2835
Georg Brandlf6d367452010-03-12 10:02:03 +00002836 If *capture* is ``True``, warnings issued by the :mod:`warnings` module
Vinay Sajip61afd262010-02-19 23:53:17 +00002837 will be redirected to the logging system. Specifically, a warning will be
2838 formatted using :func:`warnings.formatwarning` and the resulting string
Georg Brandlf6d367452010-03-12 10:02:03 +00002839 logged to a logger named "py.warnings" with a severity of ``WARNING``.
Vinay Sajip61afd262010-02-19 23:53:17 +00002840
Georg Brandlf6d367452010-03-12 10:02:03 +00002841 If *capture* is ``False``, the redirection of warnings to the logging system
Vinay Sajip61afd262010-02-19 23:53:17 +00002842 will stop, and warnings will be redirected to their original destinations
Georg Brandlf6d367452010-03-12 10:02:03 +00002843 (i.e. those in effect before ``captureWarnings(True)`` was called).
Vinay Sajip61afd262010-02-19 23:53:17 +00002844
2845
Georg Brandl8ec7f652007-08-15 14:28:01 +00002846Configuration
2847-------------
2848
2849
2850.. _logging-config-api:
2851
2852Configuration functions
2853^^^^^^^^^^^^^^^^^^^^^^^
2854
Georg Brandl8ec7f652007-08-15 14:28:01 +00002855The following functions configure the logging module. They are located in the
2856:mod:`logging.config` module. Their use is optional --- you can configure the
2857logging module using these functions or by making calls to the main API (defined
2858in :mod:`logging` itself) and defining handlers which are declared either in
2859:mod:`logging` or :mod:`logging.handlers`.
2860
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002861.. function:: dictConfig(config)
2862
2863 Takes the logging configuration from a dictionary. The contents of
2864 this dictionary are described in :ref:`logging-config-dictschema`
2865 below.
2866
2867 If an error is encountered during configuration, this function will
2868 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2869 or :exc:`ImportError` with a suitably descriptive message. The
2870 following is a (possibly incomplete) list of conditions which will
2871 raise an error:
2872
2873 * A ``level`` which is not a string or which is a string not
2874 corresponding to an actual logging level.
2875 * A ``propagate`` value which is not a boolean.
2876 * An id which does not have a corresponding destination.
2877 * A non-existent handler id found during an incremental call.
2878 * An invalid logger name.
2879 * Inability to resolve to an internal or external object.
2880
2881 Parsing is performed by the :class:`DictConfigurator` class, whose
2882 constructor is passed the dictionary used for configuration, and
2883 has a :meth:`configure` method. The :mod:`logging.config` module
2884 has a callable attribute :attr:`dictConfigClass`
2885 which is initially set to :class:`DictConfigurator`.
2886 You can replace the value of :attr:`dictConfigClass` with a
2887 suitable implementation of your own.
2888
2889 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2890 the specified dictionary, and then calls the :meth:`configure` method on
2891 the returned object to put the configuration into effect::
2892
2893 def dictConfig(config):
2894 dictConfigClass(config).configure()
2895
2896 For example, a subclass of :class:`DictConfigurator` could call
2897 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2898 set up custom prefixes which would be usable in the subsequent
2899 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2900 this new subclass, and then :func:`dictConfig` could be called exactly as
2901 in the default, uncustomized state.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002902
2903.. function:: fileConfig(fname[, defaults])
2904
Vinay Sajip51104862009-01-02 18:53:04 +00002905 Reads the logging configuration from a :mod:`ConfigParser`\-format file named
2906 *fname*. This function can be called several times from an application,
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002907 allowing an end user to select from various pre-canned
Vinay Sajip51104862009-01-02 18:53:04 +00002908 configurations (if the developer provides a mechanism to present the choices
2909 and load the chosen configuration). Defaults to be passed to the ConfigParser
2910 can be specified in the *defaults* argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002911
Georg Brandl8ec7f652007-08-15 14:28:01 +00002912.. function:: listen([port])
2913
2914 Starts up a socket server on the specified port, and listens for new
2915 configurations. If no port is specified, the module's default
2916 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2917 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2918 :class:`Thread` instance on which you can call :meth:`start` to start the
2919 server, and which you can :meth:`join` when appropriate. To stop the server,
Georg Brandlc37f2882007-12-04 17:46:27 +00002920 call :func:`stopListening`.
2921
2922 To send a configuration to the socket, read in the configuration file and
2923 send it to the socket as a string of bytes preceded by a four-byte length
2924 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002925
2926
2927.. function:: stopListening()
2928
Georg Brandlc37f2882007-12-04 17:46:27 +00002929 Stops the listening server which was created with a call to :func:`listen`.
2930 This is typically called before calling :meth:`join` on the return value from
Georg Brandl8ec7f652007-08-15 14:28:01 +00002931 :func:`listen`.
2932
2933
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002934.. _logging-config-dictschema:
2935
2936Configuration dictionary schema
2937^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2938
2939Describing a logging configuration requires listing the various
2940objects to create and the connections between them; for example, you
2941may create a handler named "console" and then say that the logger
2942named "startup" will send its messages to the "console" handler.
2943These objects aren't limited to those provided by the :mod:`logging`
2944module because you might write your own formatter or handler class.
2945The parameters to these classes may also need to include external
2946objects such as ``sys.stderr``. The syntax for describing these
2947objects and connections is defined in :ref:`logging-config-dict-connections`
2948below.
2949
2950Dictionary Schema Details
2951"""""""""""""""""""""""""
2952
2953The dictionary passed to :func:`dictConfig` must contain the following
2954keys:
2955
2956* `version` - to be set to an integer value representing the schema
2957 version. The only valid value at present is 1, but having this key
2958 allows the schema to evolve while still preserving backwards
2959 compatibility.
2960
2961All other keys are optional, but if present they will be interpreted
2962as described below. In all cases below where a 'configuring dict' is
2963mentioned, it will be checked for the special ``'()'`` key to see if a
Andrew M. Kuchling1b553472010-05-16 23:31:16 +00002964custom instantiation is required. If so, the mechanism described in
2965:ref:`logging-config-dict-userdef` below is used to create an instance;
2966otherwise, the context is used to determine what to instantiate.
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002967
2968* `formatters` - the corresponding value will be a dict in which each
2969 key is a formatter id and each value is a dict describing how to
2970 configure the corresponding Formatter instance.
2971
2972 The configuring dict is searched for keys ``format`` and ``datefmt``
2973 (with defaults of ``None``) and these are used to construct a
2974 :class:`logging.Formatter` instance.
2975
2976* `filters` - the corresponding value will be a dict in which each key
2977 is a filter id and each value is a dict describing how to configure
2978 the corresponding Filter instance.
2979
2980 The configuring dict is searched for the key ``name`` (defaulting to the
2981 empty string) and this is used to construct a :class:`logging.Filter`
2982 instance.
2983
2984* `handlers` - the corresponding value will be a dict in which each
2985 key is a handler id and each value is a dict describing how to
2986 configure the corresponding Handler instance.
2987
2988 The configuring dict is searched for the following keys:
2989
2990 * ``class`` (mandatory). This is the fully qualified name of the
2991 handler class.
2992
2993 * ``level`` (optional). The level of the handler.
2994
2995 * ``formatter`` (optional). The id of the formatter for this
2996 handler.
2997
2998 * ``filters`` (optional). A list of ids of the filters for this
2999 handler.
3000
3001 All *other* keys are passed through as keyword arguments to the
3002 handler's constructor. For example, given the snippet::
3003
3004 handlers:
3005 console:
3006 class : logging.StreamHandler
3007 formatter: brief
3008 level : INFO
3009 filters: [allow_foo]
3010 stream : ext://sys.stdout
3011 file:
3012 class : logging.handlers.RotatingFileHandler
3013 formatter: precise
3014 filename: logconfig.log
3015 maxBytes: 1024
3016 backupCount: 3
3017
3018 the handler with id ``console`` is instantiated as a
3019 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3020 stream. The handler with id ``file`` is instantiated as a
3021 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3022 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3023
3024* `loggers` - the corresponding value will be a dict in which each key
3025 is a logger name and each value is a dict describing how to
3026 configure the corresponding Logger instance.
3027
3028 The configuring dict is searched for the following keys:
3029
3030 * ``level`` (optional). The level of the logger.
3031
3032 * ``propagate`` (optional). The propagation setting of the logger.
3033
3034 * ``filters`` (optional). A list of ids of the filters for this
3035 logger.
3036
3037 * ``handlers`` (optional). A list of ids of the handlers for this
3038 logger.
3039
3040 The specified loggers will be configured according to the level,
3041 propagation, filters and handlers specified.
3042
3043* `root` - this will be the configuration for the root logger.
3044 Processing of the configuration will be as for any logger, except
3045 that the ``propagate`` setting will not be applicable.
3046
3047* `incremental` - whether the configuration is to be interpreted as
3048 incremental to the existing configuration. This value defaults to
3049 ``False``, which means that the specified configuration replaces the
3050 existing configuration with the same semantics as used by the
3051 existing :func:`fileConfig` API.
3052
3053 If the specified value is ``True``, the configuration is processed
3054 as described in the section on :ref:`logging-config-dict-incremental`.
3055
3056* `disable_existing_loggers` - whether any existing loggers are to be
3057 disabled. This setting mirrors the parameter of the same name in
3058 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
3059 This value is ignored if `incremental` is ``True``.
3060
3061.. _logging-config-dict-incremental:
3062
3063Incremental Configuration
3064"""""""""""""""""""""""""
3065
3066It is difficult to provide complete flexibility for incremental
3067configuration. For example, because objects such as filters
3068and formatters are anonymous, once a configuration is set up, it is
3069not possible to refer to such anonymous objects when augmenting a
3070configuration.
3071
3072Furthermore, there is not a compelling case for arbitrarily altering
3073the object graph of loggers, handlers, filters, formatters at
3074run-time, once a configuration is set up; the verbosity of loggers and
3075handlers can be controlled just by setting levels (and, in the case of
3076loggers, propagation flags). Changing the object graph arbitrarily in
3077a safe way is problematic in a multi-threaded environment; while not
3078impossible, the benefits are not worth the complexity it adds to the
3079implementation.
3080
3081Thus, when the ``incremental`` key of a configuration dict is present
3082and is ``True``, the system will completely ignore any ``formatters`` and
3083``filters`` entries, and process only the ``level``
3084settings in the ``handlers`` entries, and the ``level`` and
3085``propagate`` settings in the ``loggers`` and ``root`` entries.
3086
3087Using a value in the configuration dict lets configurations to be sent
3088over the wire as pickled dicts to a socket listener. Thus, the logging
3089verbosity of a long-running application can be altered over time with
3090no need to stop and restart the application.
3091
3092.. _logging-config-dict-connections:
3093
3094Object connections
3095""""""""""""""""""
3096
3097The schema describes a set of logging objects - loggers,
3098handlers, formatters, filters - which are connected to each other in
3099an object graph. Thus, the schema needs to represent connections
3100between the objects. For example, say that, once configured, a
3101particular logger has attached to it a particular handler. For the
3102purposes of this discussion, we can say that the logger represents the
3103source, and the handler the destination, of a connection between the
3104two. Of course in the configured objects this is represented by the
3105logger holding a reference to the handler. In the configuration dict,
3106this is done by giving each destination object an id which identifies
3107it unambiguously, and then using the id in the source object's
3108configuration to indicate that a connection exists between the source
3109and the destination object with that id.
3110
3111So, for example, consider the following YAML snippet::
3112
3113 formatters:
3114 brief:
3115 # configuration for formatter with id 'brief' goes here
3116 precise:
3117 # configuration for formatter with id 'precise' goes here
3118 handlers:
3119 h1: #This is an id
3120 # configuration of handler with id 'h1' goes here
3121 formatter: brief
3122 h2: #This is another id
3123 # configuration of handler with id 'h2' goes here
3124 formatter: precise
3125 loggers:
3126 foo.bar.baz:
3127 # other configuration for logger 'foo.bar.baz'
3128 handlers: [h1, h2]
3129
3130(Note: YAML used here because it's a little more readable than the
3131equivalent Python source form for the dictionary.)
3132
3133The ids for loggers are the logger names which would be used
3134programmatically to obtain a reference to those loggers, e.g.
3135``foo.bar.baz``. The ids for Formatters and Filters can be any string
3136value (such as ``brief``, ``precise`` above) and they are transient,
3137in that they are only meaningful for processing the configuration
3138dictionary and used to determine connections between objects, and are
3139not persisted anywhere when the configuration call is complete.
3140
3141The above snippet indicates that logger named ``foo.bar.baz`` should
3142have two handlers attached to it, which are described by the handler
3143ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3144``brief``, and the formatter for ``h2`` is that described by id
3145``precise``.
3146
3147
3148.. _logging-config-dict-userdef:
3149
3150User-defined objects
3151""""""""""""""""""""
3152
3153The schema supports user-defined objects for handlers, filters and
3154formatters. (Loggers do not need to have different types for
3155different instances, so there is no support in this configuration
3156schema for user-defined logger classes.)
3157
3158Objects to be configured are described by dictionaries
3159which detail their configuration. In some places, the logging system
3160will be able to infer from the context how an object is to be
3161instantiated, but when a user-defined object is to be instantiated,
3162the system will not know how to do this. In order to provide complete
3163flexibility for user-defined object instantiation, the user needs
3164to provide a 'factory' - a callable which is called with a
3165configuration dictionary and which returns the instantiated object.
3166This is signalled by an absolute import path to the factory being
3167made available under the special key ``'()'``. Here's a concrete
3168example::
3169
3170 formatters:
3171 brief:
3172 format: '%(message)s'
3173 default:
3174 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3175 datefmt: '%Y-%m-%d %H:%M:%S'
3176 custom:
3177 (): my.package.customFormatterFactory
3178 bar: baz
3179 spam: 99.9
3180 answer: 42
3181
3182The above YAML snippet defines three formatters. The first, with id
3183``brief``, is a standard :class:`logging.Formatter` instance with the
3184specified format string. The second, with id ``default``, has a
3185longer format and also defines the time format explicitly, and will
3186result in a :class:`logging.Formatter` initialized with those two format
3187strings. Shown in Python source form, the ``brief`` and ``default``
3188formatters have configuration sub-dictionaries::
3189
3190 {
3191 'format' : '%(message)s'
3192 }
3193
3194and::
3195
3196 {
3197 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3198 'datefmt' : '%Y-%m-%d %H:%M:%S'
3199 }
3200
3201respectively, and as these dictionaries do not contain the special key
3202``'()'``, the instantiation is inferred from the context: as a result,
3203standard :class:`logging.Formatter` instances are created. The
3204configuration sub-dictionary for the third formatter, with id
3205``custom``, is::
3206
3207 {
3208 '()' : 'my.package.customFormatterFactory',
3209 'bar' : 'baz',
3210 'spam' : 99.9,
3211 'answer' : 42
3212 }
3213
3214and this contains the special key ``'()'``, which means that
3215user-defined instantiation is wanted. In this case, the specified
3216factory callable will be used. If it is an actual callable it will be
3217used directly - otherwise, if you specify a string (as in the example)
3218the actual callable will be located using normal import mechanisms.
3219The callable will be called with the **remaining** items in the
3220configuration sub-dictionary as keyword arguments. In the above
3221example, the formatter with id ``custom`` will be assumed to be
3222returned by the call::
3223
3224 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3225
3226The key ``'()'`` has been used as the special key because it is not a
3227valid keyword parameter name, and so will not clash with the names of
3228the keyword arguments used in the call. The ``'()'`` also serves as a
3229mnemonic that the corresponding value is a callable.
3230
3231
3232.. _logging-config-dict-externalobj:
3233
3234Access to external objects
3235""""""""""""""""""""""""""
3236
3237There are times where a configuration needs to refer to objects
3238external to the configuration, for example ``sys.stderr``. If the
3239configuration dict is constructed using Python code, this is
3240straightforward, but a problem arises when the configuration is
3241provided via a text file (e.g. JSON, YAML). In a text file, there is
3242no standard way to distinguish ``sys.stderr`` from the literal string
3243``'sys.stderr'``. To facilitate this distinction, the configuration
3244system looks for certain special prefixes in string values and
3245treat them specially. For example, if the literal string
3246``'ext://sys.stderr'`` is provided as a value in the configuration,
3247then the ``ext://`` will be stripped off and the remainder of the
3248value processed using normal import mechanisms.
3249
3250The handling of such prefixes is done in a way analogous to protocol
3251handling: there is a generic mechanism to look for prefixes which
3252match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3253whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3254in a prefix-dependent manner and the result of the processing replaces
3255the string value. If the prefix is not recognised, then the string
3256value will be left as-is.
3257
3258
3259.. _logging-config-dict-internalobj:
3260
3261Access to internal objects
3262""""""""""""""""""""""""""
3263
3264As well as external objects, there is sometimes also a need to refer
3265to objects in the configuration. This will be done implicitly by the
3266configuration system for things that it knows about. For example, the
3267string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3268automatically be converted to the value ``logging.DEBUG``, and the
3269``handlers``, ``filters`` and ``formatter`` entries will take an
3270object id and resolve to the appropriate destination object.
3271
3272However, a more generic mechanism is needed for user-defined
3273objects which are not known to the :mod:`logging` module. For
3274example, consider :class:`logging.handlers.MemoryHandler`, which takes
3275a ``target`` argument which is another handler to delegate to. Since
3276the system already knows about this class, then in the configuration,
3277the given ``target`` just needs to be the object id of the relevant
3278target handler, and the system will resolve to the handler from the
3279id. If, however, a user defines a ``my.package.MyHandler`` which has
3280an ``alternate`` handler, the configuration system would not know that
3281the ``alternate`` referred to a handler. To cater for this, a generic
3282resolution system allows the user to specify::
3283
3284 handlers:
3285 file:
3286 # configuration of file handler goes here
3287
3288 custom:
3289 (): my.package.MyHandler
3290 alternate: cfg://handlers.file
3291
3292The literal string ``'cfg://handlers.file'`` will be resolved in an
3293analogous way to strings with the ``ext://`` prefix, but looking
3294in the configuration itself rather than the import namespace. The
3295mechanism allows access by dot or by index, in a similar way to
3296that provided by ``str.format``. Thus, given the following snippet::
3297
3298 handlers:
3299 email:
3300 class: logging.handlers.SMTPHandler
3301 mailhost: localhost
3302 fromaddr: my_app@domain.tld
3303 toaddrs:
3304 - support_team@domain.tld
3305 - dev_team@domain.tld
3306 subject: Houston, we have a problem.
3307
3308in the configuration, the string ``'cfg://handlers'`` would resolve to
3309the dict with key ``handlers``, the string ``'cfg://handlers.email``
3310would resolve to the dict with key ``email`` in the ``handlers`` dict,
3311and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3312resolve to ``'dev_team.domain.tld'`` and the string
3313``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3314``'support_team@domain.tld'``. The ``subject`` value could be accessed
3315using either ``'cfg://handlers.email.subject'`` or, equivalently,
3316``'cfg://handlers.email[subject]'``. The latter form only needs to be
3317used if the key contains spaces or non-alphanumeric characters. If an
3318index value consists only of decimal digits, access will be attempted
3319using the corresponding integer value, falling back to the string
3320value if needed.
3321
3322Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3323resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3324If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3325the system will attempt to retrieve the value from
3326``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3327to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3328fails.
3329
Georg Brandl8ec7f652007-08-15 14:28:01 +00003330.. _logging-config-fileformat:
3331
3332Configuration file format
3333^^^^^^^^^^^^^^^^^^^^^^^^^
3334
Georg Brandl392c6fc2008-05-25 07:25:25 +00003335The configuration file format understood by :func:`fileConfig` is based on
Vinay Sajip51104862009-01-02 18:53:04 +00003336:mod:`ConfigParser` functionality. The file must contain sections called
3337``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3338entities of each type which are defined in the file. For each such entity,
3339there is a separate section which identifies how that entity is configured.
3340Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant
3341configuration details are held in a section ``[logger_log01]``. Similarly, a
3342handler called ``hand01`` in the ``[handlers]`` section will have its
3343configuration held in a section called ``[handler_hand01]``, while a formatter
3344called ``form01`` in the ``[formatters]`` section will have its configuration
3345specified in a section called ``[formatter_form01]``. The root logger
3346configuration must be specified in a section called ``[logger_root]``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003347
3348Examples of these sections in the file are given below. ::
3349
3350 [loggers]
3351 keys=root,log02,log03,log04,log05,log06,log07
3352
3353 [handlers]
3354 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3355
3356 [formatters]
3357 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3358
3359The root logger must specify a level and a list of handlers. An example of a
3360root logger section is given below. ::
3361
3362 [logger_root]
3363 level=NOTSET
3364 handlers=hand01
3365
3366The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3367``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3368logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3369package's namespace.
3370
3371The ``handlers`` entry is a comma-separated list of handler names, which must
3372appear in the ``[handlers]`` section. These names must appear in the
3373``[handlers]`` section and have corresponding sections in the configuration
3374file.
3375
3376For loggers other than the root logger, some additional information is required.
3377This is illustrated by the following example. ::
3378
3379 [logger_parser]
3380 level=DEBUG
3381 handlers=hand01
3382 propagate=1
3383 qualname=compiler.parser
3384
3385The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3386except that if a non-root logger's level is specified as ``NOTSET``, the system
3387consults loggers higher up the hierarchy to determine the effective level of the
3388logger. The ``propagate`` entry is set to 1 to indicate that messages must
3389propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3390indicate that messages are **not** propagated to handlers up the hierarchy. The
3391``qualname`` entry is the hierarchical channel name of the logger, that is to
3392say the name used by the application to get the logger.
3393
3394Sections which specify handler configuration are exemplified by the following.
3395::
3396
3397 [handler_hand01]
3398 class=StreamHandler
3399 level=NOTSET
3400 formatter=form01
3401 args=(sys.stdout,)
3402
3403The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3404in the ``logging`` package's namespace). The ``level`` is interpreted as for
3405loggers, and ``NOTSET`` is taken to mean "log everything".
3406
Vinay Sajip2a649f92008-07-18 09:00:35 +00003407.. versionchanged:: 2.6
3408 Added support for resolving the handler's class as a dotted module and class
3409 name.
3410
Georg Brandl8ec7f652007-08-15 14:28:01 +00003411The ``formatter`` entry indicates the key name of the formatter for this
3412handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3413If a name is specified, it must appear in the ``[formatters]`` section and have
3414a corresponding section in the configuration file.
3415
3416The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3417package's namespace, is the list of arguments to the constructor for the handler
3418class. Refer to the constructors for the relevant handlers, or to the examples
3419below, to see how typical entries are constructed. ::
3420
3421 [handler_hand02]
3422 class=FileHandler
3423 level=DEBUG
3424 formatter=form02
3425 args=('python.log', 'w')
3426
3427 [handler_hand03]
3428 class=handlers.SocketHandler
3429 level=INFO
3430 formatter=form03
3431 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3432
3433 [handler_hand04]
3434 class=handlers.DatagramHandler
3435 level=WARN
3436 formatter=form04
3437 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3438
3439 [handler_hand05]
3440 class=handlers.SysLogHandler
3441 level=ERROR
3442 formatter=form05
3443 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3444
3445 [handler_hand06]
3446 class=handlers.NTEventLogHandler
3447 level=CRITICAL
3448 formatter=form06
3449 args=('Python Application', '', 'Application')
3450
3451 [handler_hand07]
3452 class=handlers.SMTPHandler
3453 level=WARN
3454 formatter=form07
3455 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3456
3457 [handler_hand08]
3458 class=handlers.MemoryHandler
3459 level=NOTSET
3460 formatter=form08
3461 target=
3462 args=(10, ERROR)
3463
3464 [handler_hand09]
3465 class=handlers.HTTPHandler
3466 level=NOTSET
3467 formatter=form09
3468 args=('localhost:9022', '/log', 'GET')
3469
3470Sections which specify formatter configuration are typified by the following. ::
3471
3472 [formatter_form01]
3473 format=F1 %(asctime)s %(levelname)s %(message)s
3474 datefmt=
3475 class=logging.Formatter
3476
3477The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Georg Brandlb19be572007-12-29 10:57:00 +00003478the :func:`strftime`\ -compatible date/time format string. If empty, the
3479package substitutes ISO8601 format date/times, which is almost equivalent to
3480specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3481also specifies milliseconds, which are appended to the result of using the above
3482format string, with a comma separator. An example time in ISO8601 format is
3483``2003-01-23 00:29:50,411``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003484
3485The ``class`` entry is optional. It indicates the name of the formatter's class
3486(as a dotted module and class name.) This option is useful for instantiating a
3487:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3488exception tracebacks in an expanded or condensed format.
3489
Georg Brandlc37f2882007-12-04 17:46:27 +00003490
3491Configuration server example
3492^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3493
3494Here is an example of a module using the logging configuration server::
3495
3496 import logging
3497 import logging.config
3498 import time
3499 import os
3500
3501 # read initial config file
3502 logging.config.fileConfig("logging.conf")
3503
3504 # create and start listener on port 9999
3505 t = logging.config.listen(9999)
3506 t.start()
3507
3508 logger = logging.getLogger("simpleExample")
3509
3510 try:
3511 # loop through logging calls to see the difference
3512 # new configurations make, until Ctrl+C is pressed
3513 while True:
3514 logger.debug("debug message")
3515 logger.info("info message")
3516 logger.warn("warn message")
3517 logger.error("error message")
3518 logger.critical("critical message")
3519 time.sleep(5)
3520 except KeyboardInterrupt:
3521 # cleanup
3522 logging.config.stopListening()
3523 t.join()
3524
3525And here is a script that takes a filename and sends that file to the server,
3526properly preceded with the binary-encoded length, as the new logging
3527configuration::
3528
3529 #!/usr/bin/env python
Benjamin Petersona7b55a32009-02-20 03:31:23 +00003530 import socket, sys, struct
Georg Brandlc37f2882007-12-04 17:46:27 +00003531
3532 data_to_send = open(sys.argv[1], "r").read()
3533
3534 HOST = 'localhost'
3535 PORT = 9999
3536 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3537 print "connecting..."
3538 s.connect((HOST, PORT))
3539 print "sending config..."
3540 s.send(struct.pack(">L", len(data_to_send)))
3541 s.send(data_to_send)
3542 s.close()
3543 print "complete"
3544
3545
3546More examples
3547-------------
3548
3549Multiple handlers and formatters
3550^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3551
3552Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3553or maximum quota for the number of handlers you may add. Sometimes it will be
3554beneficial for an application to log all messages of all severities to a text
3555file while simultaneously logging errors or above to the console. To set this
3556up, simply configure the appropriate handlers. The logging calls in the
3557application code will remain unchanged. Here is a slight modification to the
3558previous simple module-based configuration example::
3559
3560 import logging
3561
3562 logger = logging.getLogger("simple_example")
3563 logger.setLevel(logging.DEBUG)
3564 # create file handler which logs even debug messages
3565 fh = logging.FileHandler("spam.log")
3566 fh.setLevel(logging.DEBUG)
3567 # create console handler with a higher log level
3568 ch = logging.StreamHandler()
3569 ch.setLevel(logging.ERROR)
3570 # create formatter and add it to the handlers
3571 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3572 ch.setFormatter(formatter)
3573 fh.setFormatter(formatter)
3574 # add the handlers to logger
3575 logger.addHandler(ch)
3576 logger.addHandler(fh)
3577
3578 # "application" code
3579 logger.debug("debug message")
3580 logger.info("info message")
3581 logger.warn("warn message")
3582 logger.error("error message")
3583 logger.critical("critical message")
3584
3585Notice that the "application" code does not care about multiple handlers. All
3586that changed was the addition and configuration of a new handler named *fh*.
3587
3588The ability to create new handlers with higher- or lower-severity filters can be
3589very helpful when writing and testing an application. Instead of using many
3590``print`` statements for debugging, use ``logger.debug``: Unlike the print
3591statements, which you will have to delete or comment out later, the logger.debug
3592statements can remain intact in the source code and remain dormant until you
3593need them again. At that time, the only change that needs to happen is to
3594modify the severity level of the logger and/or handler to debug.
3595
3596
3597Using logging in multiple modules
3598^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3599
3600It was mentioned above that multiple calls to
3601``logging.getLogger('someLogger')`` return a reference to the same logger
3602object. This is true not only within the same module, but also across modules
3603as long as it is in the same Python interpreter process. It is true for
3604references to the same object; additionally, application code can define and
3605configure a parent logger in one module and create (but not configure) a child
3606logger in a separate module, and all logger calls to the child will pass up to
3607the parent. Here is a main module::
3608
3609 import logging
3610 import auxiliary_module
3611
3612 # create logger with "spam_application"
3613 logger = logging.getLogger("spam_application")
3614 logger.setLevel(logging.DEBUG)
3615 # create file handler which logs even debug messages
3616 fh = logging.FileHandler("spam.log")
3617 fh.setLevel(logging.DEBUG)
3618 # create console handler with a higher log level
3619 ch = logging.StreamHandler()
3620 ch.setLevel(logging.ERROR)
3621 # create formatter and add it to the handlers
3622 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3623 fh.setFormatter(formatter)
3624 ch.setFormatter(formatter)
3625 # add the handlers to the logger
3626 logger.addHandler(fh)
3627 logger.addHandler(ch)
3628
3629 logger.info("creating an instance of auxiliary_module.Auxiliary")
3630 a = auxiliary_module.Auxiliary()
3631 logger.info("created an instance of auxiliary_module.Auxiliary")
3632 logger.info("calling auxiliary_module.Auxiliary.do_something")
3633 a.do_something()
3634 logger.info("finished auxiliary_module.Auxiliary.do_something")
3635 logger.info("calling auxiliary_module.some_function()")
3636 auxiliary_module.some_function()
3637 logger.info("done with auxiliary_module.some_function()")
3638
3639Here is the auxiliary module::
3640
3641 import logging
3642
3643 # create logger
3644 module_logger = logging.getLogger("spam_application.auxiliary")
3645
3646 class Auxiliary:
3647 def __init__(self):
3648 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3649 self.logger.info("creating an instance of Auxiliary")
3650 def do_something(self):
3651 self.logger.info("doing something")
3652 a = 1 + 1
3653 self.logger.info("done doing something")
3654
3655 def some_function():
3656 module_logger.info("received a call to \"some_function\"")
3657
3658The output looks like this::
3659
Vinay Sajipe28fa292008-01-07 15:30:36 +00003660 2005-03-23 23:47:11,663 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003661 creating an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003662 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003663 creating an instance of Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003664 2005-03-23 23:47:11,665 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003665 created an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003666 2005-03-23 23:47:11,668 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003667 calling auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003668 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003669 doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003670 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003671 done doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003672 2005-03-23 23:47:11,670 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003673 finished auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003674 2005-03-23 23:47:11,671 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003675 calling auxiliary_module.some_function()
Vinay Sajipe28fa292008-01-07 15:30:36 +00003676 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003677 received a call to "some_function"
Vinay Sajipe28fa292008-01-07 15:30:36 +00003678 2005-03-23 23:47:11,673 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003679 done with auxiliary_module.some_function()
3680