blob: 3a0845d2fe5dbe1dc81130a23673ccf8fe61d46e [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
324
325Configuring Logging
326^^^^^^^^^^^^^^^^^^^
327
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000328Programmers can configure logging in three ways:
329
3301. Creating loggers, handlers, and formatters explicitly using Python
331 code that calls the configuration methods listed above.
3322. Creating a logging config file and reading it using the :func:`fileConfig`
333 function.
3343. Creating a dictionary of configuration information and passing it
335 to the :func:`dictConfig` function.
336
337The following example configures a very simple logger, a console
Vinay Sajipa38cd522010-05-18 08:16:27 +0000338handler, and a simple formatter using Python code::
Georg Brandlc37f2882007-12-04 17:46:27 +0000339
340 import logging
341
342 # create logger
343 logger = logging.getLogger("simple_example")
344 logger.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000345
Georg Brandlc37f2882007-12-04 17:46:27 +0000346 # create console handler and set level to debug
347 ch = logging.StreamHandler()
348 ch.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000349
Georg Brandlc37f2882007-12-04 17:46:27 +0000350 # create formatter
351 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000352
Georg Brandlc37f2882007-12-04 17:46:27 +0000353 # add formatter to ch
354 ch.setFormatter(formatter)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000355
Georg Brandlc37f2882007-12-04 17:46:27 +0000356 # add ch to logger
357 logger.addHandler(ch)
358
359 # "application" code
360 logger.debug("debug message")
361 logger.info("info message")
362 logger.warn("warn message")
363 logger.error("error message")
364 logger.critical("critical message")
365
366Running this module from the command line produces the following output::
367
368 $ python simple_logging_module.py
369 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
370 2005-03-19 15:10:26,620 - simple_example - INFO - info message
371 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
372 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
373 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
374
375The following Python module creates a logger, handler, and formatter nearly
376identical to those in the example listed above, with the only difference being
377the names of the objects::
378
379 import logging
380 import logging.config
381
382 logging.config.fileConfig("logging.conf")
383
384 # create logger
385 logger = logging.getLogger("simpleExample")
386
387 # "application" code
388 logger.debug("debug message")
389 logger.info("info message")
390 logger.warn("warn message")
391 logger.error("error message")
392 logger.critical("critical message")
393
394Here is the logging.conf file::
395
396 [loggers]
397 keys=root,simpleExample
398
399 [handlers]
400 keys=consoleHandler
401
402 [formatters]
403 keys=simpleFormatter
404
405 [logger_root]
406 level=DEBUG
407 handlers=consoleHandler
408
409 [logger_simpleExample]
410 level=DEBUG
411 handlers=consoleHandler
412 qualname=simpleExample
413 propagate=0
414
415 [handler_consoleHandler]
416 class=StreamHandler
417 level=DEBUG
418 formatter=simpleFormatter
419 args=(sys.stdout,)
420
421 [formatter_simpleFormatter]
422 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
423 datefmt=
424
425The output is nearly identical to that of the non-config-file-based example::
426
427 $ python simple_logging_config.py
428 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
429 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
430 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
431 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
432 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
433
434You can see that the config file approach has a few advantages over the Python
435code approach, mainly separation of configuration and code and the ability of
436noncoders to easily modify the logging properties.
437
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000438Note that the class names referenced in config files need to be either relative
439to the logging module, or absolute values which can be resolved using normal
Georg Brandlf6d367452010-03-12 10:02:03 +0000440import mechanisms. Thus, you could use either :class:`handlers.WatchedFileHandler`
441(relative to the logging module) or :class:`mypackage.mymodule.MyHandler` (for a
442class defined in package :mod:`mypackage` and module :mod:`mymodule`, where
443:mod:`mypackage` is available on the Python import path).
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000444
Vinay Sajipc76defc2010-05-21 17:41:34 +0000445.. versionchanged:: 2.7
446
447In Python 2.7, a new means of configuring logging has been introduced, using
448dictionaries to hold configuration information. This provides a superset of the
449functionality of the config-file-based approach outlined above, and is the
450recommended configuration method for new applications and deployments. Because
451a Python dictionary is used to hold configuration information, and since you
452can populate that dictionary using different means, you have more options for
453configuration. For example, you can use a configuration file in JSON format,
454or, if you have access to YAML processing functionality, a file in YAML
455format, to populate the configuration dictionary. Or, of course, you can
456construct the dictionary in Python code, receive it in pickled form over a
457socket, or use whatever approach makes sense for your application.
458
459Here's an example of the same configuration as above, in YAML format for
460the new dictionary-based approach::
461
462 version: 1
463 formatters:
464 simple:
465 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
466 handlers:
467 console:
468 class: logging.StreamHandler
469 level: DEBUG
470 formatter: simple
471 stream: ext://sys.stdout
472 loggers:
473 simpleExample:
474 level: DEBUG
475 handlers: [console]
476 propagate: no
477 root:
478 level: DEBUG
479 handlers: [console]
480
481For more information about logging using a dictionary, see
482:ref:`logging-config-api`.
483
Vinay Sajip99505c82009-01-10 13:38:04 +0000484.. _library-config:
485
Vinay Sajip34bfda52008-09-01 15:08:07 +0000486Configuring Logging for a Library
487^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
488
489When developing a library which uses logging, some consideration needs to be
490given to its configuration. If the using application does not use logging, and
491library code makes logging calls, then a one-off message "No handlers could be
492found for logger X.Y.Z" is printed to the console. This message is intended
493to catch mistakes in logging configuration, but will confuse an application
494developer who is not aware of logging by the library.
495
496In addition to documenting how a library uses logging, a good way to configure
497library logging so that it does not cause a spurious message is to add a
498handler which does nothing. This avoids the message being printed, since a
499handler will be found: it just doesn't produce any output. If the library user
500configures logging for application use, presumably that configuration will add
501some handlers, and if levels are suitably configured then logging calls made
502in library code will send output to those handlers, as normal.
503
504A do-nothing handler can be simply defined as follows::
505
506 import logging
507
508 class NullHandler(logging.Handler):
509 def emit(self, record):
510 pass
511
512An instance of this handler should be added to the top-level logger of the
513logging namespace used by the library. If all logging by a library *foo* is
514done using loggers with names matching "foo.x.y", then the code::
515
516 import logging
517
518 h = NullHandler()
519 logging.getLogger("foo").addHandler(h)
520
521should have the desired effect. If an organisation produces a number of
522libraries, then the logger name specified can be "orgname.foo" rather than
523just "foo".
524
Vinay Sajip213faca2008-12-03 23:22:58 +0000525.. versionadded:: 2.7
526
527The :class:`NullHandler` class was not present in previous versions, but is now
528included, so that it need not be defined in library code.
529
530
Georg Brandlc37f2882007-12-04 17:46:27 +0000531
532Logging Levels
533--------------
534
Georg Brandl8ec7f652007-08-15 14:28:01 +0000535The numeric values of logging levels are given in the following table. These are
536primarily of interest if you want to define your own levels, and need them to
537have specific values relative to the predefined levels. If you define a level
538with the same numeric value, it overwrites the predefined value; the predefined
539name is lost.
540
541+--------------+---------------+
542| Level | Numeric value |
543+==============+===============+
544| ``CRITICAL`` | 50 |
545+--------------+---------------+
546| ``ERROR`` | 40 |
547+--------------+---------------+
548| ``WARNING`` | 30 |
549+--------------+---------------+
550| ``INFO`` | 20 |
551+--------------+---------------+
552| ``DEBUG`` | 10 |
553+--------------+---------------+
554| ``NOTSET`` | 0 |
555+--------------+---------------+
556
557Levels can also be associated with loggers, being set either by the developer or
558through loading a saved logging configuration. When a logging method is called
559on a logger, the logger compares its own level with the level associated with
560the method call. If the logger's level is higher than the method call's, no
561logging message is actually generated. This is the basic mechanism controlling
562the verbosity of logging output.
563
564Logging messages are encoded as instances of the :class:`LogRecord` class. When
565a logger decides to actually log an event, a :class:`LogRecord` instance is
566created from the logging message.
567
568Logging messages are subjected to a dispatch mechanism through the use of
569:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
570class. Handlers are responsible for ensuring that a logged message (in the form
571of a :class:`LogRecord`) ends up in a particular location (or set of locations)
572which is useful for the target audience for that message (such as end users,
573support desk staff, system administrators, developers). Handlers are passed
574:class:`LogRecord` instances intended for particular destinations. Each logger
575can have zero, one or more handlers associated with it (via the
576:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
577directly associated with a logger, *all handlers associated with all ancestors
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000578of the logger* are called to dispatch the message (unless the *propagate* flag
579for a logger is set to a false value, at which point the passing to ancestor
580handlers stops).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000581
582Just as for loggers, handlers can have levels associated with them. A handler's
583level acts as a filter in the same way as a logger's level does. If a handler
584decides to actually dispatch an event, the :meth:`emit` method is used to send
585the message to its destination. Most user-defined subclasses of :class:`Handler`
586will need to override this :meth:`emit`.
587
Vinay Sajipb5902e62009-01-15 22:48:13 +0000588Useful Handlers
589---------------
590
Georg Brandl8ec7f652007-08-15 14:28:01 +0000591In addition to the base :class:`Handler` class, many useful subclasses are
592provided:
593
Vinay Sajip4b782332009-01-19 06:49:19 +0000594#. :ref:`stream-handler` instances send error messages to streams (file-like
Georg Brandl8ec7f652007-08-15 14:28:01 +0000595 objects).
596
Vinay Sajip4b782332009-01-19 06:49:19 +0000597#. :ref:`file-handler` instances send error messages to disk files.
Vinay Sajipb1a15e42009-01-15 23:04:47 +0000598
Vinay Sajipb5902e62009-01-15 22:48:13 +0000599#. :class:`BaseRotatingHandler` is the base class for handlers that
Vinay Sajip99234c52009-01-12 20:36:18 +0000600 rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajip4b782332009-01-19 06:49:19 +0000601 directly. Instead, use :ref:`rotating-file-handler` or
602 :ref:`timed-rotating-file-handler`.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000603
Vinay Sajip4b782332009-01-19 06:49:19 +0000604#. :ref:`rotating-file-handler` instances send error messages to disk
Vinay Sajipb5902e62009-01-15 22:48:13 +0000605 files, with support for maximum log file sizes and log file rotation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000606
Vinay Sajip4b782332009-01-19 06:49:19 +0000607#. :ref:`timed-rotating-file-handler` instances send error messages to
Vinay Sajipb5902e62009-01-15 22:48:13 +0000608 disk files, rotating the log file at certain timed intervals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
Vinay Sajip4b782332009-01-19 06:49:19 +0000610#. :ref:`socket-handler` instances send error messages to TCP/IP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000611 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000612
Vinay Sajip4b782332009-01-19 06:49:19 +0000613#. :ref:`datagram-handler` instances send error messages to UDP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000614 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615
Vinay Sajip4b782332009-01-19 06:49:19 +0000616#. :ref:`smtp-handler` instances send error messages to a designated
Vinay Sajipb5902e62009-01-15 22:48:13 +0000617 email address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000618
Vinay Sajip4b782332009-01-19 06:49:19 +0000619#. :ref:`syslog-handler` instances send error messages to a Unix
Vinay Sajipb5902e62009-01-15 22:48:13 +0000620 syslog daemon, possibly on a remote machine.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621
Vinay Sajip4b782332009-01-19 06:49:19 +0000622#. :ref:`nt-eventlog-handler` instances send error messages to a
Vinay Sajipb5902e62009-01-15 22:48:13 +0000623 Windows NT/2000/XP event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624
Vinay Sajip4b782332009-01-19 06:49:19 +0000625#. :ref:`memory-handler` instances send error messages to a buffer
Vinay Sajipb5902e62009-01-15 22:48:13 +0000626 in memory, which is flushed whenever specific criteria are met.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000627
Vinay Sajip4b782332009-01-19 06:49:19 +0000628#. :ref:`http-handler` instances send error messages to an HTTP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000629 server using either ``GET`` or ``POST`` semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000630
Vinay Sajip4b782332009-01-19 06:49:19 +0000631#. :ref:`watched-file-handler` instances watch the file they are
Vinay Sajipb5902e62009-01-15 22:48:13 +0000632 logging to. If the file changes, it is closed and reopened using the file
633 name. This handler is only useful on Unix-like systems; Windows does not
634 support the underlying mechanism used.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000635
Vinay Sajip4b782332009-01-19 06:49:19 +0000636#. :ref:`null-handler` instances do nothing with error messages. They are used
Vinay Sajip213faca2008-12-03 23:22:58 +0000637 by library developers who want to use logging, but want to avoid the "No
638 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip99505c82009-01-10 13:38:04 +0000639 the library user has not configured logging. See :ref:`library-config` for
640 more information.
Vinay Sajip213faca2008-12-03 23:22:58 +0000641
642.. versionadded:: 2.7
643
644The :class:`NullHandler` class was not present in previous versions.
645
Vinay Sajip7cc97552008-12-30 07:01:25 +0000646The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
647classes are defined in the core logging package. The other handlers are
648defined in a sub- module, :mod:`logging.handlers`. (There is also another
649sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000650
651Logged messages are formatted for presentation through instances of the
652:class:`Formatter` class. They are initialized with a format string suitable for
653use with the % operator and a dictionary.
654
655For formatting multiple messages in a batch, instances of
656:class:`BufferingFormatter` can be used. In addition to the format string (which
657is applied to each message in the batch), there is provision for header and
658trailer format strings.
659
660When filtering based on logger level and/or handler level is not enough,
661instances of :class:`Filter` can be added to both :class:`Logger` and
662:class:`Handler` instances (through their :meth:`addFilter` method). Before
663deciding to process a message further, both loggers and handlers consult all
664their filters for permission. If any filter returns a false value, the message
665is not processed further.
666
667The basic :class:`Filter` functionality allows filtering by specific logger
668name. If this feature is used, messages sent to the named logger and its
669children are allowed through the filter, and all others dropped.
670
Vinay Sajipb5902e62009-01-15 22:48:13 +0000671Module-Level Functions
672----------------------
673
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674In addition to the classes described above, there are a number of module- level
675functions.
676
677
678.. function:: getLogger([name])
679
680 Return a logger with the specified name or, if no name is specified, return a
681 logger which is the root logger of the hierarchy. If specified, the name is
682 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
683 Choice of these names is entirely up to the developer who is using logging.
684
685 All calls to this function with a given name return the same logger instance.
686 This means that logger instances never need to be passed between different parts
687 of an application.
688
689
690.. function:: getLoggerClass()
691
692 Return either the standard :class:`Logger` class, or the last class passed to
693 :func:`setLoggerClass`. This function may be called from within a new class
694 definition, to ensure that installing a customised :class:`Logger` class will
695 not undo customisations already applied by other code. For example::
696
697 class MyLogger(logging.getLoggerClass()):
698 # ... override behaviour here
699
700
701.. function:: debug(msg[, *args[, **kwargs]])
702
703 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
704 message format string, and the *args* are the arguments which are merged into
705 *msg* using the string formatting operator. (Note that this means that you can
706 use keywords in the format string, together with a single dictionary argument.)
707
708 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
709 which, if it does not evaluate as false, causes exception information to be
710 added to the logging message. If an exception tuple (in the format returned by
711 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
712 is called to get the exception information.
713
714 The other optional keyword argument is *extra* which can be used to pass a
715 dictionary which is used to populate the __dict__ of the LogRecord created for
716 the logging event with user-defined attributes. These custom attributes can then
717 be used as you like. For example, they could be incorporated into logged
718 messages. For example::
719
720 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
721 logging.basicConfig(format=FORMAT)
722 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
723 logging.warning("Protocol problem: %s", "connection reset", extra=d)
724
725 would print something like ::
726
727 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
728
729 The keys in the dictionary passed in *extra* should not clash with the keys used
730 by the logging system. (See the :class:`Formatter` documentation for more
731 information on which keys are used by the logging system.)
732
733 If you choose to use these attributes in logged messages, you need to exercise
734 some care. In the above example, for instance, the :class:`Formatter` has been
735 set up with a format string which expects 'clientip' and 'user' in the attribute
736 dictionary of the LogRecord. If these are missing, the message will not be
737 logged because a string formatting exception will occur. So in this case, you
738 always need to pass the *extra* dictionary with these keys.
739
740 While this might be annoying, this feature is intended for use in specialized
741 circumstances, such as multi-threaded servers where the same code executes in
742 many contexts, and interesting conditions which arise are dependent on this
743 context (such as remote client IP address and authenticated user name, in the
744 above example). In such circumstances, it is likely that specialized
745 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
746
747 .. versionchanged:: 2.5
748 *extra* was added.
749
750
751.. function:: info(msg[, *args[, **kwargs]])
752
753 Logs a message with level :const:`INFO` on the root logger. The arguments are
754 interpreted as for :func:`debug`.
755
756
757.. function:: warning(msg[, *args[, **kwargs]])
758
759 Logs a message with level :const:`WARNING` on the root logger. The arguments are
760 interpreted as for :func:`debug`.
761
762
763.. function:: error(msg[, *args[, **kwargs]])
764
765 Logs a message with level :const:`ERROR` on the root logger. The arguments are
766 interpreted as for :func:`debug`.
767
768
769.. function:: critical(msg[, *args[, **kwargs]])
770
771 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
772 are interpreted as for :func:`debug`.
773
774
775.. function:: exception(msg[, *args])
776
777 Logs a message with level :const:`ERROR` on the root logger. The arguments are
778 interpreted as for :func:`debug`. Exception info is added to the logging
779 message. This function should only be called from an exception handler.
780
781
782.. function:: log(level, msg[, *args[, **kwargs]])
783
784 Logs a message with level *level* on the root logger. The other arguments are
785 interpreted as for :func:`debug`.
786
787
788.. function:: disable(lvl)
789
790 Provides an overriding level *lvl* for all loggers which takes precedence over
791 the logger's own level. When the need arises to temporarily throttle logging
Vinay Sajip2060e422010-03-17 15:05:57 +0000792 output down across the whole application, this function can be useful. Its
793 effect is to disable all logging calls of severity *lvl* and below, so that
794 if you call it with a value of INFO, then all INFO and DEBUG events would be
795 discarded, whereas those of severity WARNING and above would be processed
796 according to the logger's effective level.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
798
799.. function:: addLevelName(lvl, levelName)
800
801 Associates level *lvl* with text *levelName* in an internal dictionary, which is
802 used to map numeric levels to a textual representation, for example when a
803 :class:`Formatter` formats a message. This function can also be used to define
804 your own levels. The only constraints are that all levels used must be
805 registered using this function, levels should be positive integers and they
806 should increase in increasing order of severity.
807
808
809.. function:: getLevelName(lvl)
810
811 Returns the textual representation of logging level *lvl*. If the level is one
812 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
813 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
814 have associated levels with names using :func:`addLevelName` then the name you
815 have associated with *lvl* is returned. If a numeric value corresponding to one
816 of the defined levels is passed in, the corresponding string representation is
817 returned. Otherwise, the string "Level %s" % lvl is returned.
818
819
820.. function:: makeLogRecord(attrdict)
821
822 Creates and returns a new :class:`LogRecord` instance whose attributes are
823 defined by *attrdict*. This function is useful for taking a pickled
824 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
825 it as a :class:`LogRecord` instance at the receiving end.
826
827
828.. function:: basicConfig([**kwargs])
829
830 Does basic configuration for the logging system by creating a
831 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000832 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000833 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
834 if no handlers are defined for the root logger.
835
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000836 This function does nothing if the root logger already has handlers
837 configured for it.
Georg Brandldfb5bbd2008-05-09 06:18:27 +0000838
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839 .. versionchanged:: 2.4
840 Formerly, :func:`basicConfig` did not take any keyword arguments.
841
842 The following keyword arguments are supported.
843
844 +--------------+---------------------------------------------+
845 | Format | Description |
846 +==============+=============================================+
847 | ``filename`` | Specifies that a FileHandler be created, |
848 | | using the specified filename, rather than a |
849 | | StreamHandler. |
850 +--------------+---------------------------------------------+
851 | ``filemode`` | Specifies the mode to open the file, if |
852 | | filename is specified (if filemode is |
853 | | unspecified, it defaults to 'a'). |
854 +--------------+---------------------------------------------+
855 | ``format`` | Use the specified format string for the |
856 | | handler. |
857 +--------------+---------------------------------------------+
858 | ``datefmt`` | Use the specified date/time format. |
859 +--------------+---------------------------------------------+
860 | ``level`` | Set the root logger level to the specified |
861 | | level. |
862 +--------------+---------------------------------------------+
863 | ``stream`` | Use the specified stream to initialize the |
864 | | StreamHandler. Note that this argument is |
865 | | incompatible with 'filename' - if both are |
866 | | present, 'stream' is ignored. |
867 +--------------+---------------------------------------------+
868
869
870.. function:: shutdown()
871
872 Informs the logging system to perform an orderly shutdown by flushing and
Vinay Sajip91f0ee42008-03-16 21:35:58 +0000873 closing all handlers. This should be called at application exit and no
874 further use of the logging system should be made after this call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000875
876
877.. function:: setLoggerClass(klass)
878
879 Tells the logging system to use the class *klass* when instantiating a logger.
880 The class should define :meth:`__init__` such that only a name argument is
881 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
882 function is typically called before any loggers are instantiated by applications
883 which need to use custom logger behavior.
884
885
886.. seealso::
887
888 :pep:`282` - A Logging System
889 The proposal which described this feature for inclusion in the Python standard
890 library.
891
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000892 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +0000893 This is the original source for the :mod:`logging` package. The version of the
894 package available from this site is suitable for use with Python 1.5.2, 2.1.x
895 and 2.2.x, which do not include the :mod:`logging` package in the standard
896 library.
897
Vinay Sajip4b782332009-01-19 06:49:19 +0000898.. _logger:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
900Logger Objects
901--------------
902
903Loggers have the following attributes and methods. Note that Loggers are never
904instantiated directly, but always through the module-level function
905``logging.getLogger(name)``.
906
907
908.. attribute:: Logger.propagate
909
910 If this evaluates to false, logging messages are not passed by this logger or by
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000911 its child loggers to the handlers of higher level (ancestor) loggers. The
912 constructor sets this attribute to 1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913
914
915.. method:: Logger.setLevel(lvl)
916
917 Sets the threshold for this logger to *lvl*. Logging messages which are less
918 severe than *lvl* will be ignored. When a logger is created, the level is set to
919 :const:`NOTSET` (which causes all messages to be processed when the logger is
920 the root logger, or delegation to the parent when the logger is a non-root
921 logger). Note that the root logger is created with level :const:`WARNING`.
922
923 The term "delegation to the parent" means that if a logger has a level of
924 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
925 a level other than NOTSET is found, or the root is reached.
926
927 If an ancestor is found with a level other than NOTSET, then that ancestor's
928 level is treated as the effective level of the logger where the ancestor search
929 began, and is used to determine how a logging event is handled.
930
931 If the root is reached, and it has a level of NOTSET, then all messages will be
932 processed. Otherwise, the root's level will be used as the effective level.
933
934
935.. method:: Logger.isEnabledFor(lvl)
936
937 Indicates if a message of severity *lvl* would be processed by this logger.
938 This method checks first the module-level level set by
939 ``logging.disable(lvl)`` and then the logger's effective level as determined
940 by :meth:`getEffectiveLevel`.
941
942
943.. method:: Logger.getEffectiveLevel()
944
945 Indicates the effective level for this logger. If a value other than
946 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
947 the hierarchy is traversed towards the root until a value other than
948 :const:`NOTSET` is found, and that value is returned.
949
950
Vinay Sajip804899b2010-03-22 15:29:01 +0000951.. method:: Logger.getChild(suffix)
952
953 Returns a logger which is a descendant to this logger, as determined by the suffix.
954 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
955 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
956 convenience method, useful when the parent logger is named using e.g. ``__name__``
957 rather than a literal string.
958
959 .. versionadded:: 2.7
960
Georg Brandl8ec7f652007-08-15 14:28:01 +0000961.. method:: Logger.debug(msg[, *args[, **kwargs]])
962
963 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
964 message format string, and the *args* are the arguments which are merged into
965 *msg* using the string formatting operator. (Note that this means that you can
966 use keywords in the format string, together with a single dictionary argument.)
967
968 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
969 which, if it does not evaluate as false, causes exception information to be
970 added to the logging message. If an exception tuple (in the format returned by
971 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
972 is called to get the exception information.
973
974 The other optional keyword argument is *extra* which can be used to pass a
975 dictionary which is used to populate the __dict__ of the LogRecord created for
976 the logging event with user-defined attributes. These custom attributes can then
977 be used as you like. For example, they could be incorporated into logged
978 messages. For example::
979
980 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
981 logging.basicConfig(format=FORMAT)
Neal Norwitz53004282007-10-23 05:44:27 +0000982 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl8ec7f652007-08-15 14:28:01 +0000983 logger = logging.getLogger("tcpserver")
984 logger.warning("Protocol problem: %s", "connection reset", extra=d)
985
986 would print something like ::
987
988 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
989
990 The keys in the dictionary passed in *extra* should not clash with the keys used
991 by the logging system. (See the :class:`Formatter` documentation for more
992 information on which keys are used by the logging system.)
993
994 If you choose to use these attributes in logged messages, you need to exercise
995 some care. In the above example, for instance, the :class:`Formatter` has been
996 set up with a format string which expects 'clientip' and 'user' in the attribute
997 dictionary of the LogRecord. If these are missing, the message will not be
998 logged because a string formatting exception will occur. So in this case, you
999 always need to pass the *extra* dictionary with these keys.
1000
1001 While this might be annoying, this feature is intended for use in specialized
1002 circumstances, such as multi-threaded servers where the same code executes in
1003 many contexts, and interesting conditions which arise are dependent on this
1004 context (such as remote client IP address and authenticated user name, in the
1005 above example). In such circumstances, it is likely that specialized
1006 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1007
1008 .. versionchanged:: 2.5
1009 *extra* was added.
1010
1011
1012.. method:: Logger.info(msg[, *args[, **kwargs]])
1013
1014 Logs a message with level :const:`INFO` on this logger. The arguments are
1015 interpreted as for :meth:`debug`.
1016
1017
1018.. method:: Logger.warning(msg[, *args[, **kwargs]])
1019
1020 Logs a message with level :const:`WARNING` on this logger. The arguments are
1021 interpreted as for :meth:`debug`.
1022
1023
1024.. method:: Logger.error(msg[, *args[, **kwargs]])
1025
1026 Logs a message with level :const:`ERROR` on this logger. The arguments are
1027 interpreted as for :meth:`debug`.
1028
1029
1030.. method:: Logger.critical(msg[, *args[, **kwargs]])
1031
1032 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1033 interpreted as for :meth:`debug`.
1034
1035
1036.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
1037
1038 Logs a message with integer level *lvl* on this logger. The other arguments are
1039 interpreted as for :meth:`debug`.
1040
1041
1042.. method:: Logger.exception(msg[, *args])
1043
1044 Logs a message with level :const:`ERROR` on this logger. The arguments are
1045 interpreted as for :meth:`debug`. Exception info is added to the logging
1046 message. This method should only be called from an exception handler.
1047
1048
1049.. method:: Logger.addFilter(filt)
1050
1051 Adds the specified filter *filt* to this logger.
1052
1053
1054.. method:: Logger.removeFilter(filt)
1055
1056 Removes the specified filter *filt* from this logger.
1057
1058
1059.. method:: Logger.filter(record)
1060
1061 Applies this logger's filters to the record and returns a true value if the
1062 record is to be processed.
1063
1064
1065.. method:: Logger.addHandler(hdlr)
1066
1067 Adds the specified handler *hdlr* to this logger.
1068
1069
1070.. method:: Logger.removeHandler(hdlr)
1071
1072 Removes the specified handler *hdlr* from this logger.
1073
1074
1075.. method:: Logger.findCaller()
1076
1077 Finds the caller's source filename and line number. Returns the filename, line
1078 number and function name as a 3-element tuple.
1079
Matthias Klosef0e29182007-08-16 12:03:44 +00001080 .. versionchanged:: 2.4
Georg Brandl8ec7f652007-08-15 14:28:01 +00001081 The function name was added. In earlier versions, the filename and line number
1082 were returned as a 2-element tuple..
1083
1084
1085.. method:: Logger.handle(record)
1086
1087 Handles a record by passing it to all handlers associated with this logger and
1088 its ancestors (until a false value of *propagate* is found). This method is used
1089 for unpickled records received from a socket, as well as those created locally.
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001090 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091
1092
1093.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
1094
1095 This is a factory method which can be overridden in subclasses to create
1096 specialized :class:`LogRecord` instances.
1097
1098 .. versionchanged:: 2.5
1099 *func* and *extra* were added.
1100
1101
1102.. _minimal-example:
1103
1104Basic example
1105-------------
1106
1107.. versionchanged:: 2.4
1108 formerly :func:`basicConfig` did not take any keyword arguments.
1109
1110The :mod:`logging` package provides a lot of flexibility, and its configuration
1111can appear daunting. This section demonstrates that simple use of the logging
1112package is possible.
1113
1114The simplest example shows logging to the console::
1115
1116 import logging
1117
1118 logging.debug('A debug message')
1119 logging.info('Some information')
1120 logging.warning('A shot across the bows')
1121
1122If you run the above script, you'll see this::
1123
1124 WARNING:root:A shot across the bows
1125
1126Because no particular logger was specified, the system used the root logger. The
1127debug and info messages didn't appear because by default, the root logger is
1128configured to only handle messages with a severity of WARNING or above. The
1129message format is also a configuration default, as is the output destination of
1130the messages - ``sys.stderr``. The severity level, the message format and
1131destination can be easily changed, as shown in the example below::
1132
1133 import logging
1134
1135 logging.basicConfig(level=logging.DEBUG,
1136 format='%(asctime)s %(levelname)s %(message)s',
Vinay Sajip998cc242010-06-04 13:41:02 +00001137 filename='myapp.log',
Georg Brandl8ec7f652007-08-15 14:28:01 +00001138 filemode='w')
1139 logging.debug('A debug message')
1140 logging.info('Some information')
1141 logging.warning('A shot across the bows')
1142
1143The :meth:`basicConfig` method is used to change the configuration defaults,
Vinay Sajip998cc242010-06-04 13:41:02 +00001144which results in output (written to ``myapp.log``) which should look
Georg Brandl8ec7f652007-08-15 14:28:01 +00001145something like the following::
1146
1147 2004-07-02 13:00:08,743 DEBUG A debug message
1148 2004-07-02 13:00:08,743 INFO Some information
1149 2004-07-02 13:00:08,743 WARNING A shot across the bows
1150
1151This time, all messages with a severity of DEBUG or above were handled, and the
1152format of the messages was also changed, and output went to the specified file
1153rather than the console.
1154
1155Formatting uses standard Python string formatting - see section
1156:ref:`string-formatting`. The format string takes the following common
1157specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1158documentation.
1159
1160+-------------------+-----------------------------------------------+
1161| Format | Description |
1162+===================+===============================================+
1163| ``%(name)s`` | Name of the logger (logging channel). |
1164+-------------------+-----------------------------------------------+
1165| ``%(levelname)s`` | Text logging level for the message |
1166| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1167| | ``'ERROR'``, ``'CRITICAL'``). |
1168+-------------------+-----------------------------------------------+
1169| ``%(asctime)s`` | Human-readable time when the |
1170| | :class:`LogRecord` was created. By default |
1171| | this is of the form "2003-07-08 16:49:45,896" |
1172| | (the numbers after the comma are millisecond |
1173| | portion of the time). |
1174+-------------------+-----------------------------------------------+
1175| ``%(message)s`` | The logged message. |
1176+-------------------+-----------------------------------------------+
1177
1178To change the date/time format, you can pass an additional keyword parameter,
1179*datefmt*, as in the following::
1180
1181 import logging
1182
1183 logging.basicConfig(level=logging.DEBUG,
1184 format='%(asctime)s %(levelname)-8s %(message)s',
1185 datefmt='%a, %d %b %Y %H:%M:%S',
1186 filename='/temp/myapp.log',
1187 filemode='w')
1188 logging.debug('A debug message')
1189 logging.info('Some information')
1190 logging.warning('A shot across the bows')
1191
1192which would result in output like ::
1193
1194 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1195 Fri, 02 Jul 2004 13:06:18 INFO Some information
1196 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1197
1198The date format string follows the requirements of :func:`strftime` - see the
1199documentation for the :mod:`time` module.
1200
1201If, instead of sending logging output to the console or a file, you'd rather use
1202a file-like object which you have created separately, you can pass it to
1203:func:`basicConfig` using the *stream* keyword argument. Note that if both
1204*stream* and *filename* keyword arguments are passed, the *stream* argument is
1205ignored.
1206
1207Of course, you can put variable information in your output. To do this, simply
1208have the message be a format string and pass in additional arguments containing
1209the variable information, as in the following example::
1210
1211 import logging
1212
1213 logging.basicConfig(level=logging.DEBUG,
1214 format='%(asctime)s %(levelname)-8s %(message)s',
1215 datefmt='%a, %d %b %Y %H:%M:%S',
1216 filename='/temp/myapp.log',
1217 filemode='w')
1218 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1219
1220which would result in ::
1221
1222 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1223
1224
1225.. _multiple-destinations:
1226
1227Logging to multiple destinations
1228--------------------------------
1229
1230Let's say you want to log to console and file with different message formats and
1231in differing circumstances. Say you want to log messages with levels of DEBUG
1232and higher to file, and those messages at level INFO and higher to the console.
1233Let's also assume that the file should contain timestamps, but the console
1234messages should not. Here's how you can achieve this::
1235
1236 import logging
1237
1238 # set up logging to file - see previous section for more details
1239 logging.basicConfig(level=logging.DEBUG,
1240 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1241 datefmt='%m-%d %H:%M',
1242 filename='/temp/myapp.log',
1243 filemode='w')
1244 # define a Handler which writes INFO messages or higher to the sys.stderr
1245 console = logging.StreamHandler()
1246 console.setLevel(logging.INFO)
1247 # set a format which is simpler for console use
1248 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1249 # tell the handler to use this format
1250 console.setFormatter(formatter)
1251 # add the handler to the root logger
1252 logging.getLogger('').addHandler(console)
1253
1254 # Now, we can log to the root logger, or any other logger. First the root...
1255 logging.info('Jackdaws love my big sphinx of quartz.')
1256
1257 # Now, define a couple of other loggers which might represent areas in your
1258 # application:
1259
1260 logger1 = logging.getLogger('myapp.area1')
1261 logger2 = logging.getLogger('myapp.area2')
1262
1263 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1264 logger1.info('How quickly daft jumping zebras vex.')
1265 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1266 logger2.error('The five boxing wizards jump quickly.')
1267
1268When you run this, on the console you will see ::
1269
1270 root : INFO Jackdaws love my big sphinx of quartz.
1271 myapp.area1 : INFO How quickly daft jumping zebras vex.
1272 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1273 myapp.area2 : ERROR The five boxing wizards jump quickly.
1274
1275and in the file you will see something like ::
1276
1277 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1278 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1279 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1280 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1281 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1282
1283As you can see, the DEBUG message only shows up in the file. The other messages
1284are sent to both destinations.
1285
1286This example uses console and file handlers, but you can use any number and
1287combination of handlers you choose.
1288
Vinay Sajip333c6e72009-08-20 22:04:32 +00001289.. _logging-exceptions:
1290
1291Exceptions raised during logging
1292--------------------------------
1293
1294The logging package is designed to swallow exceptions which occur while logging
1295in production. This is so that errors which occur while handling logging events
1296- such as logging misconfiguration, network or other similar errors - do not
1297cause the application using logging to terminate prematurely.
1298
1299:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1300swallowed. Other exceptions which occur during the :meth:`emit` method of a
1301:class:`Handler` subclass are passed to its :meth:`handleError` method.
1302
1303The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlf6d367452010-03-12 10:02:03 +00001304to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1305traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip333c6e72009-08-20 22:04:32 +00001306
Georg Brandlf6d367452010-03-12 10:02:03 +00001307**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip333c6e72009-08-20 22:04:32 +00001308during development, you typically want to be notified of any exceptions that
Georg Brandlf6d367452010-03-12 10:02:03 +00001309occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip333c6e72009-08-20 22:04:32 +00001310usage.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001311
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001312.. _context-info:
1313
1314Adding contextual information to your logging output
1315----------------------------------------------------
1316
1317Sometimes you want logging output to contain contextual information in
1318addition to the parameters passed to the logging call. For example, in a
1319networked application, it may be desirable to log client-specific information
1320in the log (e.g. remote client's username, or IP address). Although you could
1321use the *extra* parameter to achieve this, it's not always convenient to pass
1322the information in this way. While it might be tempting to create
1323:class:`Logger` instances on a per-connection basis, this is not a good idea
1324because these instances are not garbage collected. While this is not a problem
1325in practice, when the number of :class:`Logger` instances is dependent on the
1326level of granularity you want to use in logging an application, it could
1327be hard to manage if the number of :class:`Logger` instances becomes
1328effectively unbounded.
1329
Vinay Sajipc7403352008-01-18 15:54:14 +00001330An easy way in which you can pass contextual information to be output along
1331with logging event information is to use the :class:`LoggerAdapter` class.
1332This class is designed to look like a :class:`Logger`, so that you can call
1333:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1334:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1335same signatures as their counterparts in :class:`Logger`, so you can use the
1336two types of instances interchangeably.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001337
Vinay Sajipc7403352008-01-18 15:54:14 +00001338When you create an instance of :class:`LoggerAdapter`, you pass it a
1339:class:`Logger` instance and a dict-like object which contains your contextual
1340information. When you call one of the logging methods on an instance of
1341:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1342:class:`Logger` passed to its constructor, and arranges to pass the contextual
1343information in the delegated call. Here's a snippet from the code of
1344:class:`LoggerAdapter`::
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001345
Vinay Sajipc7403352008-01-18 15:54:14 +00001346 def debug(self, msg, *args, **kwargs):
1347 """
1348 Delegate a debug call to the underlying logger, after adding
1349 contextual information from this adapter instance.
1350 """
1351 msg, kwargs = self.process(msg, kwargs)
1352 self.logger.debug(msg, *args, **kwargs)
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001353
Vinay Sajipc7403352008-01-18 15:54:14 +00001354The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1355information is added to the logging output. It's passed the message and
1356keyword arguments of the logging call, and it passes back (potentially)
1357modified versions of these to use in the call to the underlying logger. The
1358default implementation of this method leaves the message alone, but inserts
1359an "extra" key in the keyword argument whose value is the dict-like object
1360passed to the constructor. Of course, if you had passed an "extra" keyword
1361argument in the call to the adapter, it will be silently overwritten.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001362
Vinay Sajipc7403352008-01-18 15:54:14 +00001363The advantage of using "extra" is that the values in the dict-like object are
1364merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1365customized strings with your :class:`Formatter` instances which know about
1366the keys of the dict-like object. If you need a different method, e.g. if you
1367want to prepend or append the contextual information to the message string,
1368you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1369to do what you need. Here's an example script which uses this class, which
1370also illustrates what dict-like behaviour is needed from an arbitrary
1371"dict-like" object for use in the constructor::
1372
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001373 import logging
Vinay Sajip733024a2008-01-21 17:39:22 +00001374
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001375 class ConnInfo:
1376 """
1377 An example class which shows how an arbitrary class can be used as
1378 the 'extra' context information repository passed to a LoggerAdapter.
1379 """
Vinay Sajip733024a2008-01-21 17:39:22 +00001380
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001381 def __getitem__(self, name):
1382 """
1383 To allow this instance to look like a dict.
1384 """
1385 from random import choice
1386 if name == "ip":
1387 result = choice(["127.0.0.1", "192.168.0.1"])
1388 elif name == "user":
1389 result = choice(["jim", "fred", "sheila"])
1390 else:
1391 result = self.__dict__.get(name, "?")
1392 return result
Vinay Sajip733024a2008-01-21 17:39:22 +00001393
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001394 def __iter__(self):
1395 """
1396 To allow iteration over keys, which will be merged into
1397 the LogRecord dict before formatting and output.
1398 """
1399 keys = ["ip", "user"]
1400 keys.extend(self.__dict__.keys())
1401 return keys.__iter__()
Vinay Sajip733024a2008-01-21 17:39:22 +00001402
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001403 if __name__ == "__main__":
1404 from random import choice
1405 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1406 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1407 { "ip" : "123.231.231.123", "user" : "sheila" })
1408 logging.basicConfig(level=logging.DEBUG,
1409 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1410 a1.debug("A debug message")
1411 a1.info("An info message with %s", "some parameters")
1412 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1413 for x in range(10):
1414 lvl = choice(levels)
1415 lvlname = logging.getLevelName(lvl)
1416 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Vinay Sajipc7403352008-01-18 15:54:14 +00001417
1418When this script is run, the output should look something like this::
1419
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001420 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1421 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1422 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
1423 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
1424 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
1425 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
1426 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
1427 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
1428 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
1429 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
1430 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
1431 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 +00001432
1433.. versionadded:: 2.6
1434
1435The :class:`LoggerAdapter` class was not present in previous versions.
1436
Vinay Sajip3a0dc302009-08-15 23:23:12 +00001437.. _multiple-processes:
1438
1439Logging to a single file from multiple processes
1440------------------------------------------------
1441
1442Although logging is thread-safe, and logging to a single file from multiple
1443threads in a single process *is* supported, logging to a single file from
1444*multiple processes* is *not* supported, because there is no standard way to
1445serialize access to a single file across multiple processes in Python. If you
1446need to log to a single file from multiple processes, the best way of doing
1447this is to have all the processes log to a :class:`SocketHandler`, and have a
1448separate process which implements a socket server which reads from the socket
1449and logs to file. (If you prefer, you can dedicate one thread in one of the
1450existing processes to perform this function.) The following section documents
1451this approach in more detail and includes a working socket receiver which can
1452be used as a starting point for you to adapt in your own applications.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001453
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001454If you are using a recent version of Python which includes the
1455:mod:`multiprocessing` module, you can write your own handler which uses the
1456:class:`Lock` class from this module to serialize access to the file from
1457your processes. The existing :class:`FileHandler` and subclasses do not make
1458use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip5e7f6452009-08-17 13:14:37 +00001459Note that at present, the :mod:`multiprocessing` module does not provide
1460working lock functionality on all platforms (see
1461http://bugs.python.org/issue3770).
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001462
Georg Brandl8ec7f652007-08-15 14:28:01 +00001463.. _network-logging:
1464
1465Sending and receiving logging events across a network
1466-----------------------------------------------------
1467
1468Let's say you want to send logging events across a network, and handle them at
1469the receiving end. A simple way of doing this is attaching a
1470:class:`SocketHandler` instance to the root logger at the sending end::
1471
Benjamin Petersona7b55a32009-02-20 03:31:23 +00001472 import logging, logging.handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +00001473
1474 rootLogger = logging.getLogger('')
1475 rootLogger.setLevel(logging.DEBUG)
1476 socketHandler = logging.handlers.SocketHandler('localhost',
1477 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1478 # don't bother with a formatter, since a socket handler sends the event as
1479 # an unformatted pickle
1480 rootLogger.addHandler(socketHandler)
1481
1482 # Now, we can log to the root logger, or any other logger. First the root...
1483 logging.info('Jackdaws love my big sphinx of quartz.')
1484
1485 # Now, define a couple of other loggers which might represent areas in your
1486 # application:
1487
1488 logger1 = logging.getLogger('myapp.area1')
1489 logger2 = logging.getLogger('myapp.area2')
1490
1491 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1492 logger1.info('How quickly daft jumping zebras vex.')
1493 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1494 logger2.error('The five boxing wizards jump quickly.')
1495
Georg Brandle152a772008-05-24 18:31:28 +00001496At the receiving end, you can set up a receiver using the :mod:`SocketServer`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001497module. Here is a basic working example::
1498
1499 import cPickle
1500 import logging
1501 import logging.handlers
Georg Brandle152a772008-05-24 18:31:28 +00001502 import SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001503 import struct
1504
1505
Georg Brandle152a772008-05-24 18:31:28 +00001506 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001507 """Handler for a streaming logging request.
1508
1509 This basically logs the record using whatever logging policy is
1510 configured locally.
1511 """
1512
1513 def handle(self):
1514 """
1515 Handle multiple requests - each expected to be a 4-byte length,
1516 followed by the LogRecord in pickle format. Logs the record
1517 according to whatever policy is configured locally.
1518 """
1519 while 1:
1520 chunk = self.connection.recv(4)
1521 if len(chunk) < 4:
1522 break
1523 slen = struct.unpack(">L", chunk)[0]
1524 chunk = self.connection.recv(slen)
1525 while len(chunk) < slen:
1526 chunk = chunk + self.connection.recv(slen - len(chunk))
1527 obj = self.unPickle(chunk)
1528 record = logging.makeLogRecord(obj)
1529 self.handleLogRecord(record)
1530
1531 def unPickle(self, data):
1532 return cPickle.loads(data)
1533
1534 def handleLogRecord(self, record):
1535 # if a name is specified, we use the named logger rather than the one
1536 # implied by the record.
1537 if self.server.logname is not None:
1538 name = self.server.logname
1539 else:
1540 name = record.name
1541 logger = logging.getLogger(name)
1542 # N.B. EVERY record gets logged. This is because Logger.handle
1543 # is normally called AFTER logger-level filtering. If you want
1544 # to do filtering, do it at the client end to save wasting
1545 # cycles and network bandwidth!
1546 logger.handle(record)
1547
Georg Brandle152a772008-05-24 18:31:28 +00001548 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001549 """simple TCP socket-based logging receiver suitable for testing.
1550 """
1551
1552 allow_reuse_address = 1
1553
1554 def __init__(self, host='localhost',
1555 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1556 handler=LogRecordStreamHandler):
Georg Brandle152a772008-05-24 18:31:28 +00001557 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001558 self.abort = 0
1559 self.timeout = 1
1560 self.logname = None
1561
1562 def serve_until_stopped(self):
1563 import select
1564 abort = 0
1565 while not abort:
1566 rd, wr, ex = select.select([self.socket.fileno()],
1567 [], [],
1568 self.timeout)
1569 if rd:
1570 self.handle_request()
1571 abort = self.abort
1572
1573 def main():
1574 logging.basicConfig(
1575 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1576 tcpserver = LogRecordSocketReceiver()
1577 print "About to start TCP server..."
1578 tcpserver.serve_until_stopped()
1579
1580 if __name__ == "__main__":
1581 main()
1582
1583First run the server, and then the client. On the client side, nothing is
1584printed on the console; on the server side, you should see something like::
1585
1586 About to start TCP server...
1587 59 root INFO Jackdaws love my big sphinx of quartz.
1588 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1589 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1590 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1591 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1592
Vinay Sajip80eed3e2010-07-06 15:08:55 +00001593Note that there are some security issues with pickle in some scenarios. If
1594these affect you, you can use an alternative serialization scheme by overriding
1595the :meth:`makePickle` method and implementing your alternative there, as
1596well as adapting the above script to use your alternative serialization.
1597
Vinay Sajipf778bec2009-09-22 17:23:41 +00001598Using arbitrary objects as messages
1599-----------------------------------
1600
1601In the preceding sections and examples, it has been assumed that the message
1602passed when logging the event is a string. However, this is not the only
1603possibility. You can pass an arbitrary object as a message, and its
1604:meth:`__str__` method will be called when the logging system needs to convert
1605it to a string representation. In fact, if you want to, you can avoid
1606computing a string representation altogether - for example, the
1607:class:`SocketHandler` emits an event by pickling it and sending it over the
1608wire.
1609
1610Optimization
1611------------
1612
1613Formatting of message arguments is deferred until it cannot be avoided.
1614However, computing the arguments passed to the logging method can also be
1615expensive, and you may want to avoid doing it if the logger will just throw
1616away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1617method which takes a level argument and returns true if the event would be
1618created by the Logger for that level of call. You can write code like this::
1619
1620 if logger.isEnabledFor(logging.DEBUG):
1621 logger.debug("Message with %s, %s", expensive_func1(),
1622 expensive_func2())
1623
1624so that if the logger's threshold is set above ``DEBUG``, the calls to
1625:func:`expensive_func1` and :func:`expensive_func2` are never made.
1626
1627There are other optimizations which can be made for specific applications which
1628need more precise control over what logging information is collected. Here's a
1629list of things you can do to avoid processing during logging which you don't
1630need:
1631
1632+-----------------------------------------------+----------------------------------------+
1633| What you don't want to collect | How to avoid collecting it |
1634+===============================================+========================================+
1635| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1636+-----------------------------------------------+----------------------------------------+
1637| Threading information. | Set ``logging.logThreads`` to ``0``. |
1638+-----------------------------------------------+----------------------------------------+
1639| Process information. | Set ``logging.logProcesses`` to ``0``. |
1640+-----------------------------------------------+----------------------------------------+
1641
1642Also note that the core logging module only includes the basic handlers. If
1643you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1644take up any memory.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001645
Vinay Sajip4b782332009-01-19 06:49:19 +00001646.. _handler:
1647
Georg Brandl8ec7f652007-08-15 14:28:01 +00001648Handler Objects
1649---------------
1650
1651Handlers have the following attributes and methods. Note that :class:`Handler`
1652is never instantiated directly; this class acts as a base for more useful
1653subclasses. However, the :meth:`__init__` method in subclasses needs to call
1654:meth:`Handler.__init__`.
1655
1656
1657.. method:: Handler.__init__(level=NOTSET)
1658
1659 Initializes the :class:`Handler` instance by setting its level, setting the list
1660 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1661 serializing access to an I/O mechanism.
1662
1663
1664.. method:: Handler.createLock()
1665
1666 Initializes a thread lock which can be used to serialize access to underlying
1667 I/O functionality which may not be threadsafe.
1668
1669
1670.. method:: Handler.acquire()
1671
1672 Acquires the thread lock created with :meth:`createLock`.
1673
1674
1675.. method:: Handler.release()
1676
1677 Releases the thread lock acquired with :meth:`acquire`.
1678
1679
1680.. method:: Handler.setLevel(lvl)
1681
1682 Sets the threshold for this handler to *lvl*. Logging messages which are less
1683 severe than *lvl* will be ignored. When a handler is created, the level is set
1684 to :const:`NOTSET` (which causes all messages to be processed).
1685
1686
1687.. method:: Handler.setFormatter(form)
1688
1689 Sets the :class:`Formatter` for this handler to *form*.
1690
1691
1692.. method:: Handler.addFilter(filt)
1693
1694 Adds the specified filter *filt* to this handler.
1695
1696
1697.. method:: Handler.removeFilter(filt)
1698
1699 Removes the specified filter *filt* from this handler.
1700
1701
1702.. method:: Handler.filter(record)
1703
1704 Applies this handler's filters to the record and returns a true value if the
1705 record is to be processed.
1706
1707
1708.. method:: Handler.flush()
1709
1710 Ensure all logging output has been flushed. This version does nothing and is
1711 intended to be implemented by subclasses.
1712
1713
1714.. method:: Handler.close()
1715
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001716 Tidy up any resources used by the handler. This version does no output but
1717 removes the handler from an internal list of handlers which is closed when
1718 :func:`shutdown` is called. Subclasses should ensure that this gets called
1719 from overridden :meth:`close` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001720
1721
1722.. method:: Handler.handle(record)
1723
1724 Conditionally emits the specified logging record, depending on filters which may
1725 have been added to the handler. Wraps the actual emission of the record with
1726 acquisition/release of the I/O thread lock.
1727
1728
1729.. method:: Handler.handleError(record)
1730
1731 This method should be called from handlers when an exception is encountered
1732 during an :meth:`emit` call. By default it does nothing, which means that
1733 exceptions get silently ignored. This is what is mostly wanted for a logging
1734 system - most users will not care about errors in the logging system, they are
1735 more interested in application errors. You could, however, replace this with a
1736 custom handler if you wish. The specified record is the one which was being
1737 processed when the exception occurred.
1738
1739
1740.. method:: Handler.format(record)
1741
1742 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1743 default formatter for the module.
1744
1745
1746.. method:: Handler.emit(record)
1747
1748 Do whatever it takes to actually log the specified logging record. This version
1749 is intended to be implemented by subclasses and so raises a
1750 :exc:`NotImplementedError`.
1751
1752
Vinay Sajip4b782332009-01-19 06:49:19 +00001753.. _stream-handler:
1754
Georg Brandl8ec7f652007-08-15 14:28:01 +00001755StreamHandler
1756^^^^^^^^^^^^^
1757
1758The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1759sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1760file-like object (or, more precisely, any object which supports :meth:`write`
1761and :meth:`flush` methods).
1762
1763
Vinay Sajip0c6a0e32009-12-17 14:52:00 +00001764.. currentmodule:: logging
1765
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001766.. class:: StreamHandler([stream])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001767
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001768 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001769 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1770 will be used.
1771
1772
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001773 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001774
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001775 If a formatter is specified, it is used to format the record. The record
1776 is then written to the stream with a trailing newline. If exception
1777 information is present, it is formatted using
1778 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001779
1780
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001781 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001782
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001783 Flushes the stream by calling its :meth:`flush` method. Note that the
1784 :meth:`close` method is inherited from :class:`Handler` and so does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001785 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001786
1787
Vinay Sajip4b782332009-01-19 06:49:19 +00001788.. _file-handler:
1789
Georg Brandl8ec7f652007-08-15 14:28:01 +00001790FileHandler
1791^^^^^^^^^^^
1792
1793The :class:`FileHandler` class, located in the core :mod:`logging` package,
1794sends logging output to a disk file. It inherits the output functionality from
1795:class:`StreamHandler`.
1796
1797
Vinay Sajipf38ba782008-01-24 12:38:30 +00001798.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001799
1800 Returns a new instance of the :class:`FileHandler` class. The specified file is
1801 opened and used as the stream for logging. If *mode* is not specified,
1802 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001803 with that encoding. If *delay* is true, then file opening is deferred until the
1804 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001805
Vinay Sajip59584c42009-08-14 11:33:54 +00001806 .. versionchanged:: 2.6
1807 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001808
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001809 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001810
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001811 Closes the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001812
1813
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001814 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001815
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001816 Outputs the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001817
Vinay Sajip4b782332009-01-19 06:49:19 +00001818.. _null-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001819
Vinay Sajip51104862009-01-02 18:53:04 +00001820NullHandler
1821^^^^^^^^^^^
1822
1823.. versionadded:: 2.7
1824
1825The :class:`NullHandler` class, located in the core :mod:`logging` package,
1826does not do any formatting or output. It is essentially a "no-op" handler
1827for use by library developers.
1828
1829
1830.. class:: NullHandler()
1831
1832 Returns a new instance of the :class:`NullHandler` class.
1833
1834
1835 .. method:: emit(record)
1836
1837 This method does nothing.
1838
Vinay Sajip99505c82009-01-10 13:38:04 +00001839See :ref:`library-config` for more information on how to use
1840:class:`NullHandler`.
1841
Vinay Sajip4b782332009-01-19 06:49:19 +00001842.. _watched-file-handler:
1843
Georg Brandl8ec7f652007-08-15 14:28:01 +00001844WatchedFileHandler
1845^^^^^^^^^^^^^^^^^^
1846
1847.. versionadded:: 2.6
1848
Vinay Sajipb1a15e42009-01-15 23:04:47 +00001849.. currentmodule:: logging.handlers
Vinay Sajip51104862009-01-02 18:53:04 +00001850
Georg Brandl8ec7f652007-08-15 14:28:01 +00001851The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1852module, is a :class:`FileHandler` which watches the file it is logging to. If
1853the file changes, it is closed and reopened using the file name.
1854
1855A file change can happen because of usage of programs such as *newsyslog* and
1856*logrotate* which perform log file rotation. This handler, intended for use
1857under Unix/Linux, watches the file to see if it has changed since the last emit.
1858(A file is deemed to have changed if its device or inode have changed.) If the
1859file has changed, the old file stream is closed, and the file opened to get a
1860new stream.
1861
1862This handler is not appropriate for use under Windows, because under Windows
1863open log files cannot be moved or renamed - logging opens the files with
1864exclusive locks - and so there is no need for such a handler. Furthermore,
1865*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1866this value.
1867
1868
Vinay Sajipf38ba782008-01-24 12:38:30 +00001869.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001870
1871 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1872 file is opened and used as the stream for logging. If *mode* is not specified,
1873 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001874 with that encoding. If *delay* is true, then file opening is deferred until the
1875 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001876
Vinay Sajip59584c42009-08-14 11:33:54 +00001877 .. versionchanged:: 2.6
1878 *delay* was added.
1879
Georg Brandl8ec7f652007-08-15 14:28:01 +00001880
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001881 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001882
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001883 Outputs the record to the file, but first checks to see if the file has
1884 changed. If it has, the existing stream is flushed and closed and the
1885 file opened again, before outputting the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001886
Vinay Sajip4b782332009-01-19 06:49:19 +00001887.. _rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001888
1889RotatingFileHandler
1890^^^^^^^^^^^^^^^^^^^
1891
1892The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1893module, supports rotation of disk log files.
1894
1895
Vinay Sajipf38ba782008-01-24 12:38:30 +00001896.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001897
1898 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1899 file is opened and used as the stream for logging. If *mode* is not specified,
Vinay Sajipf38ba782008-01-24 12:38:30 +00001900 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
1901 with that encoding. If *delay* is true, then file opening is deferred until the
1902 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001903
1904 You can use the *maxBytes* and *backupCount* values to allow the file to
1905 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1906 the file is closed and a new file is silently opened for output. Rollover occurs
1907 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1908 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1909 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1910 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1911 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1912 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1913 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1914 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1915 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1916
Vinay Sajip59584c42009-08-14 11:33:54 +00001917 .. versionchanged:: 2.6
1918 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001919
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001920 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001921
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001922 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001923
1924
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001925 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001926
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001927 Outputs the record to the file, catering for rollover as described
1928 previously.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001929
Vinay Sajip4b782332009-01-19 06:49:19 +00001930.. _timed-rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001931
1932TimedRotatingFileHandler
1933^^^^^^^^^^^^^^^^^^^^^^^^
1934
1935The :class:`TimedRotatingFileHandler` class, located in the
1936:mod:`logging.handlers` module, supports rotation of disk log files at certain
1937timed intervals.
1938
1939
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001940.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001941
1942 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1943 specified file is opened and used as the stream for logging. On rotating it also
1944 sets the filename suffix. Rotating happens based on the product of *when* and
1945 *interval*.
1946
1947 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandld77554f2008-06-06 07:34:50 +00001948 values is below. Note that they are not case sensitive.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001949
Georg Brandl72780a42008-03-02 13:41:39 +00001950 +----------------+-----------------------+
1951 | Value | Type of interval |
1952 +================+=======================+
1953 | ``'S'`` | Seconds |
1954 +----------------+-----------------------+
1955 | ``'M'`` | Minutes |
1956 +----------------+-----------------------+
1957 | ``'H'`` | Hours |
1958 +----------------+-----------------------+
1959 | ``'D'`` | Days |
1960 +----------------+-----------------------+
1961 | ``'W'`` | Week day (0=Monday) |
1962 +----------------+-----------------------+
1963 | ``'midnight'`` | Roll over at midnight |
1964 +----------------+-----------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001965
Georg Brandle6dab2a2008-03-02 14:15:04 +00001966 The system will save old log files by appending extensions to the filename.
1967 The extensions are date-and-time based, using the strftime format
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001968 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Vinay Sajip2a649f92008-07-18 09:00:35 +00001969 rollover interval.
Vinay Sajipecfa08f2010-03-12 09:16:10 +00001970
1971 When computing the next rollover time for the first time (when the handler
1972 is created), the last modification time of an existing log file, or else
1973 the current time, is used to compute when the next rotation will occur.
1974
Georg Brandld77554f2008-06-06 07:34:50 +00001975 If the *utc* argument is true, times in UTC will be used; otherwise
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001976 local time is used.
1977
1978 If *backupCount* is nonzero, at most *backupCount* files
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001979 will be kept, and if more would be created when rollover occurs, the oldest
1980 one is deleted. The deletion logic uses the interval to determine which
1981 files to delete, so changing the interval may leave old files lying around.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001982
Vinay Sajip59584c42009-08-14 11:33:54 +00001983 If *delay* is true, then file opening is deferred until the first call to
1984 :meth:`emit`.
1985
1986 .. versionchanged:: 2.6
1987 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001988
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001989 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001990
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001991 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001992
1993
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001994 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001995
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001996 Outputs the record to the file, catering for rollover as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001997
1998
Vinay Sajip4b782332009-01-19 06:49:19 +00001999.. _socket-handler:
2000
Georg Brandl8ec7f652007-08-15 14:28:01 +00002001SocketHandler
2002^^^^^^^^^^^^^
2003
2004The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2005sends logging output to a network socket. The base class uses a TCP socket.
2006
2007
2008.. class:: SocketHandler(host, port)
2009
2010 Returns a new instance of the :class:`SocketHandler` class intended to
2011 communicate with a remote machine whose address is given by *host* and *port*.
2012
2013
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002014 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002015
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002016 Closes the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002017
2018
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002019 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002020
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002021 Pickles the record's attribute dictionary and writes it to the socket in
2022 binary format. If there is an error with the socket, silently drops the
2023 packet. If the connection was previously lost, re-establishes the
2024 connection. To unpickle the record at the receiving end into a
2025 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002026
2027
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002028 .. method:: handleError()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002029
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002030 Handles an error which has occurred during :meth:`emit`. The most likely
2031 cause is a lost connection. Closes the socket so that we can retry on the
2032 next event.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002033
2034
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002035 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002037 This is a factory method which allows subclasses to define the precise
2038 type of socket they want. The default implementation creates a TCP socket
2039 (:const:`socket.SOCK_STREAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002040
2041
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002042 .. method:: makePickle(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002043
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002044 Pickles the record's attribute dictionary in binary format with a length
2045 prefix, and returns it ready for transmission across the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002046
Vinay Sajip86aa9052010-06-29 15:13:14 +00002047 Note that pickles aren't completely secure. If you are concerned about
2048 security, you may want to override this method to implement a more secure
2049 mechanism. For example, you can sign pickles using HMAC and then verify
2050 them on the receiving end, or alternatively you can disable unpickling of
2051 global objects on the receiving end.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002052
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002053 .. method:: send(packet)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002054
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002055 Send a pickled string *packet* to the socket. This function allows for
2056 partial sends which can happen when the network is busy.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002057
2058
Vinay Sajip4b782332009-01-19 06:49:19 +00002059.. _datagram-handler:
2060
Georg Brandl8ec7f652007-08-15 14:28:01 +00002061DatagramHandler
2062^^^^^^^^^^^^^^^
2063
2064The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2065module, inherits from :class:`SocketHandler` to support sending logging messages
2066over UDP sockets.
2067
2068
2069.. class:: DatagramHandler(host, port)
2070
2071 Returns a new instance of the :class:`DatagramHandler` class intended to
2072 communicate with a remote machine whose address is given by *host* and *port*.
2073
2074
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002075 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002076
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002077 Pickles the record's attribute dictionary and writes it to the socket in
2078 binary format. If there is an error with the socket, silently drops the
2079 packet. To unpickle the record at the receiving end into a
2080 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002081
2082
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002083 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002084
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002085 The factory method of :class:`SocketHandler` is here overridden to create
2086 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002087
2088
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002089 .. method:: send(s)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002090
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002091 Send a pickled string to a socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002092
2093
Vinay Sajip4b782332009-01-19 06:49:19 +00002094.. _syslog-handler:
2095
Georg Brandl8ec7f652007-08-15 14:28:01 +00002096SysLogHandler
2097^^^^^^^^^^^^^
2098
2099The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2100supports sending logging messages to a remote or local Unix syslog.
2101
2102
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002103.. class:: SysLogHandler([address[, facility[, socktype]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002104
2105 Returns a new instance of the :class:`SysLogHandler` class intended to
2106 communicate with a remote Unix machine whose address is given by *address* in
2107 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002108 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl8ec7f652007-08-15 14:28:01 +00002109 alternative to providing a ``(host, port)`` tuple is providing an address as a
2110 string, for example "/dev/log". In this case, a Unix domain socket is used to
2111 send the message to the syslog. If *facility* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002112 :const:`LOG_USER` is used. The type of socket opened depends on the
2113 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2114 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2115 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2116
2117 .. versionchanged:: 2.7
2118 *socktype* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002119
2120
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002121 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002122
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002123 Closes the socket to the remote host.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002124
2125
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002126 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002127
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002128 The record is formatted, and then sent to the syslog server. If exception
2129 information is present, it is *not* sent to the server.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002130
2131
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002132 .. method:: encodePriority(facility, priority)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002133
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002134 Encodes the facility and priority into an integer. You can pass in strings
2135 or integers - if strings are passed, internal mapping dictionaries are
2136 used to convert them to integers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002137
Vinay Sajipa3c39c02010-03-24 15:10:40 +00002138 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2139 mirror the values defined in the ``sys/syslog.h`` header file.
Vinay Sajipb0623d62010-03-24 14:31:21 +00002140
Georg Brandld3bab6a2010-04-02 09:03:18 +00002141 **Priorities**
2142
Vinay Sajipb0623d62010-03-24 14:31:21 +00002143 +--------------------------+---------------+
2144 | Name (string) | Symbolic value|
2145 +==========================+===============+
2146 | ``alert`` | LOG_ALERT |
2147 +--------------------------+---------------+
2148 | ``crit`` or ``critical`` | LOG_CRIT |
2149 +--------------------------+---------------+
2150 | ``debug`` | LOG_DEBUG |
2151 +--------------------------+---------------+
2152 | ``emerg`` or ``panic`` | LOG_EMERG |
2153 +--------------------------+---------------+
2154 | ``err`` or ``error`` | LOG_ERR |
2155 +--------------------------+---------------+
2156 | ``info`` | LOG_INFO |
2157 +--------------------------+---------------+
2158 | ``notice`` | LOG_NOTICE |
2159 +--------------------------+---------------+
2160 | ``warn`` or ``warning`` | LOG_WARNING |
2161 +--------------------------+---------------+
2162
Georg Brandld3bab6a2010-04-02 09:03:18 +00002163 **Facilities**
2164
Vinay Sajipb0623d62010-03-24 14:31:21 +00002165 +---------------+---------------+
2166 | Name (string) | Symbolic value|
2167 +===============+===============+
2168 | ``auth`` | LOG_AUTH |
2169 +---------------+---------------+
2170 | ``authpriv`` | LOG_AUTHPRIV |
2171 +---------------+---------------+
2172 | ``cron`` | LOG_CRON |
2173 +---------------+---------------+
2174 | ``daemon`` | LOG_DAEMON |
2175 +---------------+---------------+
2176 | ``ftp`` | LOG_FTP |
2177 +---------------+---------------+
2178 | ``kern`` | LOG_KERN |
2179 +---------------+---------------+
2180 | ``lpr`` | LOG_LPR |
2181 +---------------+---------------+
2182 | ``mail`` | LOG_MAIL |
2183 +---------------+---------------+
2184 | ``news`` | LOG_NEWS |
2185 +---------------+---------------+
2186 | ``syslog`` | LOG_SYSLOG |
2187 +---------------+---------------+
2188 | ``user`` | LOG_USER |
2189 +---------------+---------------+
2190 | ``uucp`` | LOG_UUCP |
2191 +---------------+---------------+
2192 | ``local0`` | LOG_LOCAL0 |
2193 +---------------+---------------+
2194 | ``local1`` | LOG_LOCAL1 |
2195 +---------------+---------------+
2196 | ``local2`` | LOG_LOCAL2 |
2197 +---------------+---------------+
2198 | ``local3`` | LOG_LOCAL3 |
2199 +---------------+---------------+
2200 | ``local4`` | LOG_LOCAL4 |
2201 +---------------+---------------+
2202 | ``local5`` | LOG_LOCAL5 |
2203 +---------------+---------------+
2204 | ``local6`` | LOG_LOCAL6 |
2205 +---------------+---------------+
2206 | ``local7`` | LOG_LOCAL7 |
2207 +---------------+---------------+
2208
Vinay Sajip66d19e22010-03-24 17:36:35 +00002209 .. method:: mapPriority(levelname)
2210
2211 Maps a logging level name to a syslog priority name.
2212 You may need to override this if you are using custom levels, or
2213 if the default algorithm is not suitable for your needs. The
2214 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2215 ``CRITICAL`` to the equivalent syslog names, and all other level
2216 names to "warning".
Georg Brandl8ec7f652007-08-15 14:28:01 +00002217
Vinay Sajip4b782332009-01-19 06:49:19 +00002218.. _nt-eventlog-handler:
2219
Georg Brandl8ec7f652007-08-15 14:28:01 +00002220NTEventLogHandler
2221^^^^^^^^^^^^^^^^^
2222
2223The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2224module, supports sending logging messages to a local Windows NT, Windows 2000 or
2225Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2226extensions for Python installed.
2227
2228
2229.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
2230
2231 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2232 used to define the application name as it appears in the event log. An
2233 appropriate registry entry is created using this name. The *dllname* should give
2234 the fully qualified pathname of a .dll or .exe which contains message
2235 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2236 - this is installed with the Win32 extensions and contains some basic
2237 placeholder message definitions. Note that use of these placeholders will make
2238 your event logs big, as the entire message source is held in the log. If you
2239 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2240 contains the message definitions you want to use in the event log). The
2241 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2242 defaults to ``'Application'``.
2243
2244
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002245 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002246
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002247 At this point, you can remove the application name from the registry as a
2248 source of event log entries. However, if you do this, you will not be able
2249 to see the events as you intended in the Event Log Viewer - it needs to be
2250 able to access the registry to get the .dll name. The current version does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00002251 not do this.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002252
2253
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002254 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002255
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002256 Determines the message ID, event category and event type, and then logs
2257 the message in the NT event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002258
2259
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002260 .. method:: getEventCategory(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002261
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002262 Returns the event category for the record. Override this if you want to
2263 specify your own categories. This version returns 0.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002264
2265
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002266 .. method:: getEventType(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002267
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002268 Returns the event type for the record. Override this if you want to
2269 specify your own types. This version does a mapping using the handler's
2270 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2271 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2272 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2273 your own levels, you will either need to override this method or place a
2274 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002275
2276
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002277 .. method:: getMessageID(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002278
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002279 Returns the message ID for the record. If you are using your own messages,
2280 you could do this by having the *msg* passed to the logger being an ID
2281 rather than a format string. Then, in here, you could use a dictionary
2282 lookup to get the message ID. This version returns 1, which is the base
2283 message ID in :file:`win32service.pyd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002284
Vinay Sajip4b782332009-01-19 06:49:19 +00002285.. _smtp-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002286
2287SMTPHandler
2288^^^^^^^^^^^
2289
2290The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2291supports sending logging messages to an email address via SMTP.
2292
2293
2294.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
2295
2296 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2297 initialized with the from and to addresses and subject line of the email. The
2298 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2299 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2300 the standard SMTP port is used. If your SMTP server requires authentication, you
2301 can specify a (username, password) tuple for the *credentials* argument.
2302
2303 .. versionchanged:: 2.6
2304 *credentials* was added.
2305
2306
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002307 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002308
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002309 Formats the record and sends it to the specified addressees.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002310
2311
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002312 .. method:: getSubject(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002313
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002314 If you want to specify a subject line which is record-dependent, override
2315 this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002316
Vinay Sajip4b782332009-01-19 06:49:19 +00002317.. _memory-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002318
2319MemoryHandler
2320^^^^^^^^^^^^^
2321
2322The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2323supports buffering of logging records in memory, periodically flushing them to a
2324:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2325event of a certain severity or greater is seen.
2326
2327:class:`MemoryHandler` is a subclass of the more general
2328:class:`BufferingHandler`, which is an abstract class. This buffers logging
2329records in memory. Whenever each record is added to the buffer, a check is made
2330by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2331should, then :meth:`flush` is expected to do the needful.
2332
2333
2334.. class:: BufferingHandler(capacity)
2335
2336 Initializes the handler with a buffer of the specified capacity.
2337
2338
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002339 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002340
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002341 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2342 calls :meth:`flush` to process the buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002343
2344
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002345 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002346
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002347 You can override this to implement custom flushing behavior. This version
2348 just zaps the buffer to empty.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002349
2350
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002351 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002352
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002353 Returns true if the buffer is up to capacity. This method can be
2354 overridden to implement custom flushing strategies.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002355
2356
2357.. class:: MemoryHandler(capacity[, flushLevel [, target]])
2358
2359 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2360 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2361 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2362 set using :meth:`setTarget` before this handler does anything useful.
2363
2364
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002365 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002366
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002367 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2368 buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002369
2370
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002371 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002372
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002373 For a :class:`MemoryHandler`, flushing means just sending the buffered
2374 records to the target, if there is one. Override if you want different
2375 behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002376
2377
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002378 .. method:: setTarget(target)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002379
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002380 Sets the target handler for this handler.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002381
2382
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002383 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002384
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002385 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002386
2387
Vinay Sajip4b782332009-01-19 06:49:19 +00002388.. _http-handler:
2389
Georg Brandl8ec7f652007-08-15 14:28:01 +00002390HTTPHandler
2391^^^^^^^^^^^
2392
2393The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2394supports sending logging messages to a Web server, using either ``GET`` or
2395``POST`` semantics.
2396
2397
2398.. class:: HTTPHandler(host, url[, method])
2399
2400 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2401 initialized with a host address, url and HTTP method. The *host* can be of the
2402 form ``host:port``, should you need to use a specific port number. If no
2403 *method* is specified, ``GET`` is used.
2404
2405
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002406 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002407
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002408 Sends the record to the Web server as an URL-encoded dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002409
2410
Vinay Sajip4b782332009-01-19 06:49:19 +00002411.. _formatter:
Georg Brandlc37f2882007-12-04 17:46:27 +00002412
Georg Brandl8ec7f652007-08-15 14:28:01 +00002413Formatter Objects
2414-----------------
2415
Georg Brandl430effb2009-01-01 13:05:13 +00002416.. currentmodule:: logging
2417
Georg Brandl8ec7f652007-08-15 14:28:01 +00002418:class:`Formatter`\ s have the following attributes and methods. They are
2419responsible for converting a :class:`LogRecord` to (usually) a string which can
2420be interpreted by either a human or an external system. The base
2421:class:`Formatter` allows a formatting string to be specified. If none is
2422supplied, the default value of ``'%(message)s'`` is used.
2423
2424A Formatter can be initialized with a format string which makes use of knowledge
2425of the :class:`LogRecord` attributes - such as the default value mentioned above
2426making use of the fact that the user's message and arguments are pre-formatted
2427into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti062d2b52009-12-19 22:41:49 +00002428standard Python %-style mapping keys. See section :ref:`string-formatting`
Georg Brandl8ec7f652007-08-15 14:28:01 +00002429for more information on string formatting.
2430
2431Currently, the useful mapping keys in a :class:`LogRecord` are:
2432
2433+-------------------------+-----------------------------------------------+
2434| Format | Description |
2435+=========================+===============================================+
2436| ``%(name)s`` | Name of the logger (logging channel). |
2437+-------------------------+-----------------------------------------------+
2438| ``%(levelno)s`` | Numeric logging level for the message |
2439| | (:const:`DEBUG`, :const:`INFO`, |
2440| | :const:`WARNING`, :const:`ERROR`, |
2441| | :const:`CRITICAL`). |
2442+-------------------------+-----------------------------------------------+
2443| ``%(levelname)s`` | Text logging level for the message |
2444| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2445| | ``'ERROR'``, ``'CRITICAL'``). |
2446+-------------------------+-----------------------------------------------+
2447| ``%(pathname)s`` | Full pathname of the source file where the |
2448| | logging call was issued (if available). |
2449+-------------------------+-----------------------------------------------+
2450| ``%(filename)s`` | Filename portion of pathname. |
2451+-------------------------+-----------------------------------------------+
2452| ``%(module)s`` | Module (name portion of filename). |
2453+-------------------------+-----------------------------------------------+
2454| ``%(funcName)s`` | Name of function containing the logging call. |
2455+-------------------------+-----------------------------------------------+
2456| ``%(lineno)d`` | Source line number where the logging call was |
2457| | issued (if available). |
2458+-------------------------+-----------------------------------------------+
2459| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2460| | (as returned by :func:`time.time`). |
2461+-------------------------+-----------------------------------------------+
2462| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2463| | created, relative to the time the logging |
2464| | module was loaded. |
2465+-------------------------+-----------------------------------------------+
2466| ``%(asctime)s`` | Human-readable time when the |
2467| | :class:`LogRecord` was created. By default |
2468| | this is of the form "2003-07-08 16:49:45,896" |
2469| | (the numbers after the comma are millisecond |
2470| | portion of the time). |
2471+-------------------------+-----------------------------------------------+
2472| ``%(msecs)d`` | Millisecond portion of the time when the |
2473| | :class:`LogRecord` was created. |
2474+-------------------------+-----------------------------------------------+
2475| ``%(thread)d`` | Thread ID (if available). |
2476+-------------------------+-----------------------------------------------+
2477| ``%(threadName)s`` | Thread name (if available). |
2478+-------------------------+-----------------------------------------------+
2479| ``%(process)d`` | Process ID (if available). |
2480+-------------------------+-----------------------------------------------+
2481| ``%(message)s`` | The logged message, computed as ``msg % |
2482| | args``. |
2483+-------------------------+-----------------------------------------------+
2484
2485.. versionchanged:: 2.5
2486 *funcName* was added.
2487
2488
2489.. class:: Formatter([fmt[, datefmt]])
2490
2491 Returns a new instance of the :class:`Formatter` class. The instance is
2492 initialized with a format string for the message as a whole, as well as a format
2493 string for the date/time portion of a message. If no *fmt* is specified,
2494 ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
2495 is used.
2496
2497
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002498 .. method:: format(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002499
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002500 The record's attribute dictionary is used as the operand to a string
2501 formatting operation. Returns the resulting string. Before formatting the
2502 dictionary, a couple of preparatory steps are carried out. The *message*
2503 attribute of the record is computed using *msg* % *args*. If the
2504 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2505 to format the event time. If there is exception information, it is
2506 formatted using :meth:`formatException` and appended to the message. Note
2507 that the formatted exception information is cached in attribute
2508 *exc_text*. This is useful because the exception information can be
2509 pickled and sent across the wire, but you should be careful if you have
2510 more than one :class:`Formatter` subclass which customizes the formatting
2511 of exception information. In this case, you will have to clear the cached
2512 value after a formatter has done its formatting, so that the next
2513 formatter to handle the event doesn't use the cached value but
2514 recalculates it afresh.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002515
2516
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002517 .. method:: formatTime(record[, datefmt])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002518
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002519 This method should be called from :meth:`format` by a formatter which
2520 wants to make use of a formatted time. This method can be overridden in
2521 formatters to provide for any specific requirement, but the basic behavior
2522 is as follows: if *datefmt* (a string) is specified, it is used with
2523 :func:`time.strftime` to format the creation time of the
2524 record. Otherwise, the ISO8601 format is used. The resulting string is
2525 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002526
2527
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002528 .. method:: formatException(exc_info)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002529
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002530 Formats the specified exception information (a standard exception tuple as
2531 returned by :func:`sys.exc_info`) as a string. This default implementation
2532 just uses :func:`traceback.print_exception`. The resulting string is
2533 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002534
Vinay Sajip4b782332009-01-19 06:49:19 +00002535.. _filter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002536
2537Filter Objects
2538--------------
2539
Vinay Sajip4b782332009-01-19 06:49:19 +00002540Filters can be used by :class:`Handler`\ s and :class:`Logger`\ s for
Georg Brandl8ec7f652007-08-15 14:28:01 +00002541more sophisticated filtering than is provided by levels. The base filter class
2542only allows events which are below a certain point in the logger hierarchy. For
2543example, a filter initialized with "A.B" will allow events logged by loggers
2544"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2545initialized with the empty string, all events are passed.
2546
2547
2548.. class:: Filter([name])
2549
2550 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2551 names a logger which, together with its children, will have its events allowed
2552 through the filter. If no name is specified, allows every event.
2553
2554
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002555 .. method:: filter(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002556
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002557 Is the specified record to be logged? Returns zero for no, nonzero for
2558 yes. If deemed appropriate, the record may be modified in-place by this
2559 method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002560
Vinay Sajip4b782332009-01-19 06:49:19 +00002561.. _log-record:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002562
2563LogRecord Objects
2564-----------------
2565
2566:class:`LogRecord` instances are created every time something is logged. They
2567contain all the information pertinent to the event being logged. The main
2568information passed in is in msg and args, which are combined using msg % args to
2569create the message field of the record. The record also includes information
2570such as when the record was created, the source line where the logging call was
2571made, and any exception information to be logged.
2572
2573
2574.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
2575
2576 Returns an instance of :class:`LogRecord` initialized with interesting
2577 information. The *name* is the logger name; *lvl* is the numeric level;
2578 *pathname* is the absolute pathname of the source file in which the logging
2579 call was made; *lineno* is the line number in that file where the logging
2580 call is found; *msg* is the user-supplied message (a format string); *args*
2581 is the tuple which, together with *msg*, makes up the user message; and
2582 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2583 (or :const:`None`, if no exception information is available). The *func* is
2584 the name of the function from which the logging call was made. If not
2585 specified, it defaults to ``None``.
2586
2587 .. versionchanged:: 2.5
2588 *func* was added.
2589
2590
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002591 .. method:: getMessage()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002592
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002593 Returns the message for this :class:`LogRecord` instance after merging any
2594 user-supplied arguments with the message.
2595
Vinay Sajip4b782332009-01-19 06:49:19 +00002596.. _logger-adapter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002597
Vinay Sajipc7403352008-01-18 15:54:14 +00002598LoggerAdapter Objects
2599---------------------
2600
2601.. versionadded:: 2.6
2602
2603:class:`LoggerAdapter` instances are used to conveniently pass contextual
Vinay Sajip733024a2008-01-21 17:39:22 +00002604information into logging calls. For a usage example , see the section on
2605`adding contextual information to your logging output`__.
2606
2607__ context-info_
Vinay Sajipc7403352008-01-18 15:54:14 +00002608
2609.. class:: LoggerAdapter(logger, extra)
2610
2611 Returns an instance of :class:`LoggerAdapter` initialized with an
2612 underlying :class:`Logger` instance and a dict-like object.
2613
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002614 .. method:: process(msg, kwargs)
Vinay Sajipc7403352008-01-18 15:54:14 +00002615
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002616 Modifies the message and/or keyword arguments passed to a logging call in
2617 order to insert contextual information. This implementation takes the object
2618 passed as *extra* to the constructor and adds it to *kwargs* using key
2619 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2620 (possibly modified) versions of the arguments passed in.
Vinay Sajipc7403352008-01-18 15:54:14 +00002621
2622In addition to the above, :class:`LoggerAdapter` supports all the logging
2623methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2624:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2625methods have the same signatures as their counterparts in :class:`Logger`, so
2626you can use the two types of instances interchangeably.
2627
Vinay Sajip804899b2010-03-22 15:29:01 +00002628.. versionchanged:: 2.7
2629
2630The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method
2631delegates to the underlying logger.
2632
Georg Brandl8ec7f652007-08-15 14:28:01 +00002633
2634Thread Safety
2635-------------
2636
2637The logging module is intended to be thread-safe without any special work
2638needing to be done by its clients. It achieves this though using threading
2639locks; there is one lock to serialize access to the module's shared data, and
2640each handler also creates a lock to serialize access to its underlying I/O.
2641
Vinay Sajip353a85f2009-04-03 21:58:16 +00002642If you are implementing asynchronous signal handlers using the :mod:`signal`
2643module, you may not be able to use logging from within such handlers. This is
2644because lock implementations in the :mod:`threading` module are not always
2645re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002646
Vinay Sajip61afd262010-02-19 23:53:17 +00002647
2648Integration with the warnings module
2649------------------------------------
2650
2651The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2652with the :mod:`warnings` module.
2653
2654.. function:: captureWarnings(capture)
2655
2656 This function is used to turn the capture of warnings by logging on and
2657 off.
2658
Georg Brandlf6d367452010-03-12 10:02:03 +00002659 If *capture* is ``True``, warnings issued by the :mod:`warnings` module
Vinay Sajip61afd262010-02-19 23:53:17 +00002660 will be redirected to the logging system. Specifically, a warning will be
2661 formatted using :func:`warnings.formatwarning` and the resulting string
Georg Brandlf6d367452010-03-12 10:02:03 +00002662 logged to a logger named "py.warnings" with a severity of ``WARNING``.
Vinay Sajip61afd262010-02-19 23:53:17 +00002663
Georg Brandlf6d367452010-03-12 10:02:03 +00002664 If *capture* is ``False``, the redirection of warnings to the logging system
Vinay Sajip61afd262010-02-19 23:53:17 +00002665 will stop, and warnings will be redirected to their original destinations
Georg Brandlf6d367452010-03-12 10:02:03 +00002666 (i.e. those in effect before ``captureWarnings(True)`` was called).
Vinay Sajip61afd262010-02-19 23:53:17 +00002667
2668
Georg Brandl8ec7f652007-08-15 14:28:01 +00002669Configuration
2670-------------
2671
2672
2673.. _logging-config-api:
2674
2675Configuration functions
2676^^^^^^^^^^^^^^^^^^^^^^^
2677
Georg Brandl8ec7f652007-08-15 14:28:01 +00002678The following functions configure the logging module. They are located in the
2679:mod:`logging.config` module. Their use is optional --- you can configure the
2680logging module using these functions or by making calls to the main API (defined
2681in :mod:`logging` itself) and defining handlers which are declared either in
2682:mod:`logging` or :mod:`logging.handlers`.
2683
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002684.. function:: dictConfig(config)
2685
2686 Takes the logging configuration from a dictionary. The contents of
2687 this dictionary are described in :ref:`logging-config-dictschema`
2688 below.
2689
2690 If an error is encountered during configuration, this function will
2691 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2692 or :exc:`ImportError` with a suitably descriptive message. The
2693 following is a (possibly incomplete) list of conditions which will
2694 raise an error:
2695
2696 * A ``level`` which is not a string or which is a string not
2697 corresponding to an actual logging level.
2698 * A ``propagate`` value which is not a boolean.
2699 * An id which does not have a corresponding destination.
2700 * A non-existent handler id found during an incremental call.
2701 * An invalid logger name.
2702 * Inability to resolve to an internal or external object.
2703
2704 Parsing is performed by the :class:`DictConfigurator` class, whose
2705 constructor is passed the dictionary used for configuration, and
2706 has a :meth:`configure` method. The :mod:`logging.config` module
2707 has a callable attribute :attr:`dictConfigClass`
2708 which is initially set to :class:`DictConfigurator`.
2709 You can replace the value of :attr:`dictConfigClass` with a
2710 suitable implementation of your own.
2711
2712 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2713 the specified dictionary, and then calls the :meth:`configure` method on
2714 the returned object to put the configuration into effect::
2715
2716 def dictConfig(config):
2717 dictConfigClass(config).configure()
2718
2719 For example, a subclass of :class:`DictConfigurator` could call
2720 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2721 set up custom prefixes which would be usable in the subsequent
2722 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2723 this new subclass, and then :func:`dictConfig` could be called exactly as
2724 in the default, uncustomized state.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002725
2726.. function:: fileConfig(fname[, defaults])
2727
Vinay Sajip51104862009-01-02 18:53:04 +00002728 Reads the logging configuration from a :mod:`ConfigParser`\-format file named
2729 *fname*. This function can be called several times from an application,
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002730 allowing an end user to select from various pre-canned
Vinay Sajip51104862009-01-02 18:53:04 +00002731 configurations (if the developer provides a mechanism to present the choices
2732 and load the chosen configuration). Defaults to be passed to the ConfigParser
2733 can be specified in the *defaults* argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002734
Georg Brandl8ec7f652007-08-15 14:28:01 +00002735.. function:: listen([port])
2736
2737 Starts up a socket server on the specified port, and listens for new
2738 configurations. If no port is specified, the module's default
2739 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2740 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2741 :class:`Thread` instance on which you can call :meth:`start` to start the
2742 server, and which you can :meth:`join` when appropriate. To stop the server,
Georg Brandlc37f2882007-12-04 17:46:27 +00002743 call :func:`stopListening`.
2744
2745 To send a configuration to the socket, read in the configuration file and
2746 send it to the socket as a string of bytes preceded by a four-byte length
2747 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002748
2749
2750.. function:: stopListening()
2751
Georg Brandlc37f2882007-12-04 17:46:27 +00002752 Stops the listening server which was created with a call to :func:`listen`.
2753 This is typically called before calling :meth:`join` on the return value from
Georg Brandl8ec7f652007-08-15 14:28:01 +00002754 :func:`listen`.
2755
2756
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002757.. _logging-config-dictschema:
2758
2759Configuration dictionary schema
2760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2761
2762Describing a logging configuration requires listing the various
2763objects to create and the connections between them; for example, you
2764may create a handler named "console" and then say that the logger
2765named "startup" will send its messages to the "console" handler.
2766These objects aren't limited to those provided by the :mod:`logging`
2767module because you might write your own formatter or handler class.
2768The parameters to these classes may also need to include external
2769objects such as ``sys.stderr``. The syntax for describing these
2770objects and connections is defined in :ref:`logging-config-dict-connections`
2771below.
2772
2773Dictionary Schema Details
2774"""""""""""""""""""""""""
2775
2776The dictionary passed to :func:`dictConfig` must contain the following
2777keys:
2778
2779* `version` - to be set to an integer value representing the schema
2780 version. The only valid value at present is 1, but having this key
2781 allows the schema to evolve while still preserving backwards
2782 compatibility.
2783
2784All other keys are optional, but if present they will be interpreted
2785as described below. In all cases below where a 'configuring dict' is
2786mentioned, it will be checked for the special ``'()'`` key to see if a
Andrew M. Kuchling1b553472010-05-16 23:31:16 +00002787custom instantiation is required. If so, the mechanism described in
2788:ref:`logging-config-dict-userdef` below is used to create an instance;
2789otherwise, the context is used to determine what to instantiate.
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002790
2791* `formatters` - the corresponding value will be a dict in which each
2792 key is a formatter id and each value is a dict describing how to
2793 configure the corresponding Formatter instance.
2794
2795 The configuring dict is searched for keys ``format`` and ``datefmt``
2796 (with defaults of ``None``) and these are used to construct a
2797 :class:`logging.Formatter` instance.
2798
2799* `filters` - the corresponding value will be a dict in which each key
2800 is a filter id and each value is a dict describing how to configure
2801 the corresponding Filter instance.
2802
2803 The configuring dict is searched for the key ``name`` (defaulting to the
2804 empty string) and this is used to construct a :class:`logging.Filter`
2805 instance.
2806
2807* `handlers` - the corresponding value will be a dict in which each
2808 key is a handler id and each value is a dict describing how to
2809 configure the corresponding Handler instance.
2810
2811 The configuring dict is searched for the following keys:
2812
2813 * ``class`` (mandatory). This is the fully qualified name of the
2814 handler class.
2815
2816 * ``level`` (optional). The level of the handler.
2817
2818 * ``formatter`` (optional). The id of the formatter for this
2819 handler.
2820
2821 * ``filters`` (optional). A list of ids of the filters for this
2822 handler.
2823
2824 All *other* keys are passed through as keyword arguments to the
2825 handler's constructor. For example, given the snippet::
2826
2827 handlers:
2828 console:
2829 class : logging.StreamHandler
2830 formatter: brief
2831 level : INFO
2832 filters: [allow_foo]
2833 stream : ext://sys.stdout
2834 file:
2835 class : logging.handlers.RotatingFileHandler
2836 formatter: precise
2837 filename: logconfig.log
2838 maxBytes: 1024
2839 backupCount: 3
2840
2841 the handler with id ``console`` is instantiated as a
2842 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
2843 stream. The handler with id ``file`` is instantiated as a
2844 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
2845 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
2846
2847* `loggers` - the corresponding value will be a dict in which each key
2848 is a logger name and each value is a dict describing how to
2849 configure the corresponding Logger instance.
2850
2851 The configuring dict is searched for the following keys:
2852
2853 * ``level`` (optional). The level of the logger.
2854
2855 * ``propagate`` (optional). The propagation setting of the logger.
2856
2857 * ``filters`` (optional). A list of ids of the filters for this
2858 logger.
2859
2860 * ``handlers`` (optional). A list of ids of the handlers for this
2861 logger.
2862
2863 The specified loggers will be configured according to the level,
2864 propagation, filters and handlers specified.
2865
2866* `root` - this will be the configuration for the root logger.
2867 Processing of the configuration will be as for any logger, except
2868 that the ``propagate`` setting will not be applicable.
2869
2870* `incremental` - whether the configuration is to be interpreted as
2871 incremental to the existing configuration. This value defaults to
2872 ``False``, which means that the specified configuration replaces the
2873 existing configuration with the same semantics as used by the
2874 existing :func:`fileConfig` API.
2875
2876 If the specified value is ``True``, the configuration is processed
2877 as described in the section on :ref:`logging-config-dict-incremental`.
2878
2879* `disable_existing_loggers` - whether any existing loggers are to be
2880 disabled. This setting mirrors the parameter of the same name in
2881 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
2882 This value is ignored if `incremental` is ``True``.
2883
2884.. _logging-config-dict-incremental:
2885
2886Incremental Configuration
2887"""""""""""""""""""""""""
2888
2889It is difficult to provide complete flexibility for incremental
2890configuration. For example, because objects such as filters
2891and formatters are anonymous, once a configuration is set up, it is
2892not possible to refer to such anonymous objects when augmenting a
2893configuration.
2894
2895Furthermore, there is not a compelling case for arbitrarily altering
2896the object graph of loggers, handlers, filters, formatters at
2897run-time, once a configuration is set up; the verbosity of loggers and
2898handlers can be controlled just by setting levels (and, in the case of
2899loggers, propagation flags). Changing the object graph arbitrarily in
2900a safe way is problematic in a multi-threaded environment; while not
2901impossible, the benefits are not worth the complexity it adds to the
2902implementation.
2903
2904Thus, when the ``incremental`` key of a configuration dict is present
2905and is ``True``, the system will completely ignore any ``formatters`` and
2906``filters`` entries, and process only the ``level``
2907settings in the ``handlers`` entries, and the ``level`` and
2908``propagate`` settings in the ``loggers`` and ``root`` entries.
2909
2910Using a value in the configuration dict lets configurations to be sent
2911over the wire as pickled dicts to a socket listener. Thus, the logging
2912verbosity of a long-running application can be altered over time with
2913no need to stop and restart the application.
2914
2915.. _logging-config-dict-connections:
2916
2917Object connections
2918""""""""""""""""""
2919
2920The schema describes a set of logging objects - loggers,
2921handlers, formatters, filters - which are connected to each other in
2922an object graph. Thus, the schema needs to represent connections
2923between the objects. For example, say that, once configured, a
2924particular logger has attached to it a particular handler. For the
2925purposes of this discussion, we can say that the logger represents the
2926source, and the handler the destination, of a connection between the
2927two. Of course in the configured objects this is represented by the
2928logger holding a reference to the handler. In the configuration dict,
2929this is done by giving each destination object an id which identifies
2930it unambiguously, and then using the id in the source object's
2931configuration to indicate that a connection exists between the source
2932and the destination object with that id.
2933
2934So, for example, consider the following YAML snippet::
2935
2936 formatters:
2937 brief:
2938 # configuration for formatter with id 'brief' goes here
2939 precise:
2940 # configuration for formatter with id 'precise' goes here
2941 handlers:
2942 h1: #This is an id
2943 # configuration of handler with id 'h1' goes here
2944 formatter: brief
2945 h2: #This is another id
2946 # configuration of handler with id 'h2' goes here
2947 formatter: precise
2948 loggers:
2949 foo.bar.baz:
2950 # other configuration for logger 'foo.bar.baz'
2951 handlers: [h1, h2]
2952
2953(Note: YAML used here because it's a little more readable than the
2954equivalent Python source form for the dictionary.)
2955
2956The ids for loggers are the logger names which would be used
2957programmatically to obtain a reference to those loggers, e.g.
2958``foo.bar.baz``. The ids for Formatters and Filters can be any string
2959value (such as ``brief``, ``precise`` above) and they are transient,
2960in that they are only meaningful for processing the configuration
2961dictionary and used to determine connections between objects, and are
2962not persisted anywhere when the configuration call is complete.
2963
2964The above snippet indicates that logger named ``foo.bar.baz`` should
2965have two handlers attached to it, which are described by the handler
2966ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
2967``brief``, and the formatter for ``h2`` is that described by id
2968``precise``.
2969
2970
2971.. _logging-config-dict-userdef:
2972
2973User-defined objects
2974""""""""""""""""""""
2975
2976The schema supports user-defined objects for handlers, filters and
2977formatters. (Loggers do not need to have different types for
2978different instances, so there is no support in this configuration
2979schema for user-defined logger classes.)
2980
2981Objects to be configured are described by dictionaries
2982which detail their configuration. In some places, the logging system
2983will be able to infer from the context how an object is to be
2984instantiated, but when a user-defined object is to be instantiated,
2985the system will not know how to do this. In order to provide complete
2986flexibility for user-defined object instantiation, the user needs
2987to provide a 'factory' - a callable which is called with a
2988configuration dictionary and which returns the instantiated object.
2989This is signalled by an absolute import path to the factory being
2990made available under the special key ``'()'``. Here's a concrete
2991example::
2992
2993 formatters:
2994 brief:
2995 format: '%(message)s'
2996 default:
2997 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
2998 datefmt: '%Y-%m-%d %H:%M:%S'
2999 custom:
3000 (): my.package.customFormatterFactory
3001 bar: baz
3002 spam: 99.9
3003 answer: 42
3004
3005The above YAML snippet defines three formatters. The first, with id
3006``brief``, is a standard :class:`logging.Formatter` instance with the
3007specified format string. The second, with id ``default``, has a
3008longer format and also defines the time format explicitly, and will
3009result in a :class:`logging.Formatter` initialized with those two format
3010strings. Shown in Python source form, the ``brief`` and ``default``
3011formatters have configuration sub-dictionaries::
3012
3013 {
3014 'format' : '%(message)s'
3015 }
3016
3017and::
3018
3019 {
3020 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3021 'datefmt' : '%Y-%m-%d %H:%M:%S'
3022 }
3023
3024respectively, and as these dictionaries do not contain the special key
3025``'()'``, the instantiation is inferred from the context: as a result,
3026standard :class:`logging.Formatter` instances are created. The
3027configuration sub-dictionary for the third formatter, with id
3028``custom``, is::
3029
3030 {
3031 '()' : 'my.package.customFormatterFactory',
3032 'bar' : 'baz',
3033 'spam' : 99.9,
3034 'answer' : 42
3035 }
3036
3037and this contains the special key ``'()'``, which means that
3038user-defined instantiation is wanted. In this case, the specified
3039factory callable will be used. If it is an actual callable it will be
3040used directly - otherwise, if you specify a string (as in the example)
3041the actual callable will be located using normal import mechanisms.
3042The callable will be called with the **remaining** items in the
3043configuration sub-dictionary as keyword arguments. In the above
3044example, the formatter with id ``custom`` will be assumed to be
3045returned by the call::
3046
3047 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3048
3049The key ``'()'`` has been used as the special key because it is not a
3050valid keyword parameter name, and so will not clash with the names of
3051the keyword arguments used in the call. The ``'()'`` also serves as a
3052mnemonic that the corresponding value is a callable.
3053
3054
3055.. _logging-config-dict-externalobj:
3056
3057Access to external objects
3058""""""""""""""""""""""""""
3059
3060There are times where a configuration needs to refer to objects
3061external to the configuration, for example ``sys.stderr``. If the
3062configuration dict is constructed using Python code, this is
3063straightforward, but a problem arises when the configuration is
3064provided via a text file (e.g. JSON, YAML). In a text file, there is
3065no standard way to distinguish ``sys.stderr`` from the literal string
3066``'sys.stderr'``. To facilitate this distinction, the configuration
3067system looks for certain special prefixes in string values and
3068treat them specially. For example, if the literal string
3069``'ext://sys.stderr'`` is provided as a value in the configuration,
3070then the ``ext://`` will be stripped off and the remainder of the
3071value processed using normal import mechanisms.
3072
3073The handling of such prefixes is done in a way analogous to protocol
3074handling: there is a generic mechanism to look for prefixes which
3075match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3076whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3077in a prefix-dependent manner and the result of the processing replaces
3078the string value. If the prefix is not recognised, then the string
3079value will be left as-is.
3080
3081
3082.. _logging-config-dict-internalobj:
3083
3084Access to internal objects
3085""""""""""""""""""""""""""
3086
3087As well as external objects, there is sometimes also a need to refer
3088to objects in the configuration. This will be done implicitly by the
3089configuration system for things that it knows about. For example, the
3090string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3091automatically be converted to the value ``logging.DEBUG``, and the
3092``handlers``, ``filters`` and ``formatter`` entries will take an
3093object id and resolve to the appropriate destination object.
3094
3095However, a more generic mechanism is needed for user-defined
3096objects which are not known to the :mod:`logging` module. For
3097example, consider :class:`logging.handlers.MemoryHandler`, which takes
3098a ``target`` argument which is another handler to delegate to. Since
3099the system already knows about this class, then in the configuration,
3100the given ``target`` just needs to be the object id of the relevant
3101target handler, and the system will resolve to the handler from the
3102id. If, however, a user defines a ``my.package.MyHandler`` which has
3103an ``alternate`` handler, the configuration system would not know that
3104the ``alternate`` referred to a handler. To cater for this, a generic
3105resolution system allows the user to specify::
3106
3107 handlers:
3108 file:
3109 # configuration of file handler goes here
3110
3111 custom:
3112 (): my.package.MyHandler
3113 alternate: cfg://handlers.file
3114
3115The literal string ``'cfg://handlers.file'`` will be resolved in an
3116analogous way to strings with the ``ext://`` prefix, but looking
3117in the configuration itself rather than the import namespace. The
3118mechanism allows access by dot or by index, in a similar way to
3119that provided by ``str.format``. Thus, given the following snippet::
3120
3121 handlers:
3122 email:
3123 class: logging.handlers.SMTPHandler
3124 mailhost: localhost
3125 fromaddr: my_app@domain.tld
3126 toaddrs:
3127 - support_team@domain.tld
3128 - dev_team@domain.tld
3129 subject: Houston, we have a problem.
3130
3131in the configuration, the string ``'cfg://handlers'`` would resolve to
3132the dict with key ``handlers``, the string ``'cfg://handlers.email``
3133would resolve to the dict with key ``email`` in the ``handlers`` dict,
3134and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3135resolve to ``'dev_team.domain.tld'`` and the string
3136``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3137``'support_team@domain.tld'``. The ``subject`` value could be accessed
3138using either ``'cfg://handlers.email.subject'`` or, equivalently,
3139``'cfg://handlers.email[subject]'``. The latter form only needs to be
3140used if the key contains spaces or non-alphanumeric characters. If an
3141index value consists only of decimal digits, access will be attempted
3142using the corresponding integer value, falling back to the string
3143value if needed.
3144
3145Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3146resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3147If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3148the system will attempt to retrieve the value from
3149``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3150to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3151fails.
3152
Georg Brandl8ec7f652007-08-15 14:28:01 +00003153.. _logging-config-fileformat:
3154
3155Configuration file format
3156^^^^^^^^^^^^^^^^^^^^^^^^^
3157
Georg Brandl392c6fc2008-05-25 07:25:25 +00003158The configuration file format understood by :func:`fileConfig` is based on
Vinay Sajip51104862009-01-02 18:53:04 +00003159:mod:`ConfigParser` functionality. The file must contain sections called
3160``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3161entities of each type which are defined in the file. For each such entity,
3162there is a separate section which identifies how that entity is configured.
3163Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant
3164configuration details are held in a section ``[logger_log01]``. Similarly, a
3165handler called ``hand01`` in the ``[handlers]`` section will have its
3166configuration held in a section called ``[handler_hand01]``, while a formatter
3167called ``form01`` in the ``[formatters]`` section will have its configuration
3168specified in a section called ``[formatter_form01]``. The root logger
3169configuration must be specified in a section called ``[logger_root]``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003170
3171Examples of these sections in the file are given below. ::
3172
3173 [loggers]
3174 keys=root,log02,log03,log04,log05,log06,log07
3175
3176 [handlers]
3177 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3178
3179 [formatters]
3180 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3181
3182The root logger must specify a level and a list of handlers. An example of a
3183root logger section is given below. ::
3184
3185 [logger_root]
3186 level=NOTSET
3187 handlers=hand01
3188
3189The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3190``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3191logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3192package's namespace.
3193
3194The ``handlers`` entry is a comma-separated list of handler names, which must
3195appear in the ``[handlers]`` section. These names must appear in the
3196``[handlers]`` section and have corresponding sections in the configuration
3197file.
3198
3199For loggers other than the root logger, some additional information is required.
3200This is illustrated by the following example. ::
3201
3202 [logger_parser]
3203 level=DEBUG
3204 handlers=hand01
3205 propagate=1
3206 qualname=compiler.parser
3207
3208The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3209except that if a non-root logger's level is specified as ``NOTSET``, the system
3210consults loggers higher up the hierarchy to determine the effective level of the
3211logger. The ``propagate`` entry is set to 1 to indicate that messages must
3212propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3213indicate that messages are **not** propagated to handlers up the hierarchy. The
3214``qualname`` entry is the hierarchical channel name of the logger, that is to
3215say the name used by the application to get the logger.
3216
3217Sections which specify handler configuration are exemplified by the following.
3218::
3219
3220 [handler_hand01]
3221 class=StreamHandler
3222 level=NOTSET
3223 formatter=form01
3224 args=(sys.stdout,)
3225
3226The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3227in the ``logging`` package's namespace). The ``level`` is interpreted as for
3228loggers, and ``NOTSET`` is taken to mean "log everything".
3229
Vinay Sajip2a649f92008-07-18 09:00:35 +00003230.. versionchanged:: 2.6
3231 Added support for resolving the handler's class as a dotted module and class
3232 name.
3233
Georg Brandl8ec7f652007-08-15 14:28:01 +00003234The ``formatter`` entry indicates the key name of the formatter for this
3235handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3236If a name is specified, it must appear in the ``[formatters]`` section and have
3237a corresponding section in the configuration file.
3238
3239The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3240package's namespace, is the list of arguments to the constructor for the handler
3241class. Refer to the constructors for the relevant handlers, or to the examples
3242below, to see how typical entries are constructed. ::
3243
3244 [handler_hand02]
3245 class=FileHandler
3246 level=DEBUG
3247 formatter=form02
3248 args=('python.log', 'w')
3249
3250 [handler_hand03]
3251 class=handlers.SocketHandler
3252 level=INFO
3253 formatter=form03
3254 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3255
3256 [handler_hand04]
3257 class=handlers.DatagramHandler
3258 level=WARN
3259 formatter=form04
3260 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3261
3262 [handler_hand05]
3263 class=handlers.SysLogHandler
3264 level=ERROR
3265 formatter=form05
3266 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3267
3268 [handler_hand06]
3269 class=handlers.NTEventLogHandler
3270 level=CRITICAL
3271 formatter=form06
3272 args=('Python Application', '', 'Application')
3273
3274 [handler_hand07]
3275 class=handlers.SMTPHandler
3276 level=WARN
3277 formatter=form07
3278 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3279
3280 [handler_hand08]
3281 class=handlers.MemoryHandler
3282 level=NOTSET
3283 formatter=form08
3284 target=
3285 args=(10, ERROR)
3286
3287 [handler_hand09]
3288 class=handlers.HTTPHandler
3289 level=NOTSET
3290 formatter=form09
3291 args=('localhost:9022', '/log', 'GET')
3292
3293Sections which specify formatter configuration are typified by the following. ::
3294
3295 [formatter_form01]
3296 format=F1 %(asctime)s %(levelname)s %(message)s
3297 datefmt=
3298 class=logging.Formatter
3299
3300The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Georg Brandlb19be572007-12-29 10:57:00 +00003301the :func:`strftime`\ -compatible date/time format string. If empty, the
3302package substitutes ISO8601 format date/times, which is almost equivalent to
3303specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3304also specifies milliseconds, which are appended to the result of using the above
3305format string, with a comma separator. An example time in ISO8601 format is
3306``2003-01-23 00:29:50,411``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003307
3308The ``class`` entry is optional. It indicates the name of the formatter's class
3309(as a dotted module and class name.) This option is useful for instantiating a
3310:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3311exception tracebacks in an expanded or condensed format.
3312
Georg Brandlc37f2882007-12-04 17:46:27 +00003313
3314Configuration server example
3315^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3316
3317Here is an example of a module using the logging configuration server::
3318
3319 import logging
3320 import logging.config
3321 import time
3322 import os
3323
3324 # read initial config file
3325 logging.config.fileConfig("logging.conf")
3326
3327 # create and start listener on port 9999
3328 t = logging.config.listen(9999)
3329 t.start()
3330
3331 logger = logging.getLogger("simpleExample")
3332
3333 try:
3334 # loop through logging calls to see the difference
3335 # new configurations make, until Ctrl+C is pressed
3336 while True:
3337 logger.debug("debug message")
3338 logger.info("info message")
3339 logger.warn("warn message")
3340 logger.error("error message")
3341 logger.critical("critical message")
3342 time.sleep(5)
3343 except KeyboardInterrupt:
3344 # cleanup
3345 logging.config.stopListening()
3346 t.join()
3347
3348And here is a script that takes a filename and sends that file to the server,
3349properly preceded with the binary-encoded length, as the new logging
3350configuration::
3351
3352 #!/usr/bin/env python
Benjamin Petersona7b55a32009-02-20 03:31:23 +00003353 import socket, sys, struct
Georg Brandlc37f2882007-12-04 17:46:27 +00003354
3355 data_to_send = open(sys.argv[1], "r").read()
3356
3357 HOST = 'localhost'
3358 PORT = 9999
3359 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3360 print "connecting..."
3361 s.connect((HOST, PORT))
3362 print "sending config..."
3363 s.send(struct.pack(">L", len(data_to_send)))
3364 s.send(data_to_send)
3365 s.close()
3366 print "complete"
3367
3368
3369More examples
3370-------------
3371
3372Multiple handlers and formatters
3373^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3374
3375Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3376or maximum quota for the number of handlers you may add. Sometimes it will be
3377beneficial for an application to log all messages of all severities to a text
3378file while simultaneously logging errors or above to the console. To set this
3379up, simply configure the appropriate handlers. The logging calls in the
3380application code will remain unchanged. Here is a slight modification to the
3381previous simple module-based configuration example::
3382
3383 import logging
3384
3385 logger = logging.getLogger("simple_example")
3386 logger.setLevel(logging.DEBUG)
3387 # create file handler which logs even debug messages
3388 fh = logging.FileHandler("spam.log")
3389 fh.setLevel(logging.DEBUG)
3390 # create console handler with a higher log level
3391 ch = logging.StreamHandler()
3392 ch.setLevel(logging.ERROR)
3393 # create formatter and add it to the handlers
3394 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3395 ch.setFormatter(formatter)
3396 fh.setFormatter(formatter)
3397 # add the handlers to logger
3398 logger.addHandler(ch)
3399 logger.addHandler(fh)
3400
3401 # "application" code
3402 logger.debug("debug message")
3403 logger.info("info message")
3404 logger.warn("warn message")
3405 logger.error("error message")
3406 logger.critical("critical message")
3407
3408Notice that the "application" code does not care about multiple handlers. All
3409that changed was the addition and configuration of a new handler named *fh*.
3410
3411The ability to create new handlers with higher- or lower-severity filters can be
3412very helpful when writing and testing an application. Instead of using many
3413``print`` statements for debugging, use ``logger.debug``: Unlike the print
3414statements, which you will have to delete or comment out later, the logger.debug
3415statements can remain intact in the source code and remain dormant until you
3416need them again. At that time, the only change that needs to happen is to
3417modify the severity level of the logger and/or handler to debug.
3418
3419
3420Using logging in multiple modules
3421^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3422
3423It was mentioned above that multiple calls to
3424``logging.getLogger('someLogger')`` return a reference to the same logger
3425object. This is true not only within the same module, but also across modules
3426as long as it is in the same Python interpreter process. It is true for
3427references to the same object; additionally, application code can define and
3428configure a parent logger in one module and create (but not configure) a child
3429logger in a separate module, and all logger calls to the child will pass up to
3430the parent. Here is a main module::
3431
3432 import logging
3433 import auxiliary_module
3434
3435 # create logger with "spam_application"
3436 logger = logging.getLogger("spam_application")
3437 logger.setLevel(logging.DEBUG)
3438 # create file handler which logs even debug messages
3439 fh = logging.FileHandler("spam.log")
3440 fh.setLevel(logging.DEBUG)
3441 # create console handler with a higher log level
3442 ch = logging.StreamHandler()
3443 ch.setLevel(logging.ERROR)
3444 # create formatter and add it to the handlers
3445 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3446 fh.setFormatter(formatter)
3447 ch.setFormatter(formatter)
3448 # add the handlers to the logger
3449 logger.addHandler(fh)
3450 logger.addHandler(ch)
3451
3452 logger.info("creating an instance of auxiliary_module.Auxiliary")
3453 a = auxiliary_module.Auxiliary()
3454 logger.info("created an instance of auxiliary_module.Auxiliary")
3455 logger.info("calling auxiliary_module.Auxiliary.do_something")
3456 a.do_something()
3457 logger.info("finished auxiliary_module.Auxiliary.do_something")
3458 logger.info("calling auxiliary_module.some_function()")
3459 auxiliary_module.some_function()
3460 logger.info("done with auxiliary_module.some_function()")
3461
3462Here is the auxiliary module::
3463
3464 import logging
3465
3466 # create logger
3467 module_logger = logging.getLogger("spam_application.auxiliary")
3468
3469 class Auxiliary:
3470 def __init__(self):
3471 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3472 self.logger.info("creating an instance of Auxiliary")
3473 def do_something(self):
3474 self.logger.info("doing something")
3475 a = 1 + 1
3476 self.logger.info("done doing something")
3477
3478 def some_function():
3479 module_logger.info("received a call to \"some_function\"")
3480
3481The output looks like this::
3482
Vinay Sajipe28fa292008-01-07 15:30:36 +00003483 2005-03-23 23:47:11,663 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003484 creating an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003485 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003486 creating an instance of Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003487 2005-03-23 23:47:11,665 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003488 created an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003489 2005-03-23 23:47:11,668 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003490 calling auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003491 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003492 doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003493 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003494 done doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003495 2005-03-23 23:47:11,670 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003496 finished auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003497 2005-03-23 23:47:11,671 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003498 calling auxiliary_module.some_function()
Vinay Sajipe28fa292008-01-07 15:30:36 +00003499 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003500 received a call to "some_function"
Vinay Sajipe28fa292008-01-07 15:30:36 +00003501 2005-03-23 23:47:11,673 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003502 done with auxiliary_module.some_function()
3503