blob: cba14f10ab9cdafed32dfdac99a53bc4b743705f [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
17Logging is performed by calling methods on instances of the :class:`Logger`
18class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +000019conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +000020separators. For example, a logger named "scan" is the parent of loggers
21"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
22and indicate the area of an application in which a logged message originates.
23
24Logged messages also have levels of importance associated with them. The default
25levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
26:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
27importance of a logged message by calling an appropriate method of
28:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
29:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
30constrained to use these levels: you can specify your own and use a more general
31:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
32
Christian Heimes8b0facf2007-12-04 19:30:01 +000033
34Logging tutorial
35----------------
36
37The key benefit of having the logging API provided by a standard library module
38is that all Python modules can participate in logging, so your application log
39can include messages from third-party modules.
40
41It is, of course, possible to log messages with different verbosity levels or to
42different destinations. Support for writing log messages to files, HTTP
43GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Christian Heimesc3f30c42008-02-22 16:37:40 +000044mechanisms are all supported by the standard module. You can also create your
Christian Heimes8b0facf2007-12-04 19:30:01 +000045own log destination class if you have special requirements not met by any of the
46built-in classes.
47
48Simple examples
49^^^^^^^^^^^^^^^
50
51.. sectionauthor:: Doug Hellmann
52.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
53
54Most applications are probably going to want to log to a file, so let's start
55with that case. Using the :func:`basicConfig` function, we can set up the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056default handler so that debug messages are written to a file (in the example,
57we assume that you have the appropriate permissions to create a file called
58*example.log* in the current directory)::
Christian Heimes8b0facf2007-12-04 19:30:01 +000059
60 import logging
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000061 LOG_FILENAME = 'example.log'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Christian Heimes8b0facf2007-12-04 19:30:01 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smith5c01a8d2009-06-04 18:20:51 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Christian Heimes8b0facf2007-12-04 19:30:01 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000080 LOG_FILENAME = 'logging_rotatingfile_example.out'
Christian Heimes8b0facf2007-12-04 19:30:01 +000081
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
Georg Brandlf6945182008-02-01 11:56:49 +0000100 print(filename)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000105 logging_rotatingfile_example.out
106 logging_rotatingfile_example.out.1
107 logging_rotatingfile_example.out.2
108 logging_rotatingfile_example.out.3
109 logging_rotatingfile_example.out.4
110 logging_rotatingfile_example.out.5
Christian Heimes8b0facf2007-12-04 19:30:01 +0000111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112The most current file is always :file:`logging_rotatingfile_example.out`,
Christian Heimes8b0facf2007-12-04 19:30:01 +0000113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smith5c01a8d2009-06-04 18:20:51 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipb6d065f2009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Christian Heimesdcca98d2008-02-25 13:19:43 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000249name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000270requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
294defines the interface that all handlers should have and establishes some
295default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000303instantiate formatter classes, although you could likely subclass the formatter
304if your application needs special behavior. The constructor takes two optional
305arguments: a message format string and a date format string. If there is no
306message format string, the default is to use the raw message. If there is no
307date format string, the default date format is::
308
309 %Y-%m-%d %H:%M:%S
310
311with the milliseconds tacked on at the end.
312
313The message format string uses ``%(<dictionary key>)s`` styled string
314substitution; the possible keys are documented in :ref:`formatter-objects`.
315
316The following message format string will log the time in a human-readable
317format, the severity of the message, and the contents of the message, in that
318order::
319
320 "%(asctime)s - %(levelname)s - %(message)s"
321
322
323Configuring Logging
324^^^^^^^^^^^^^^^^^^^
325
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000326Programmers can configure logging in three ways:
327
3281. Creating loggers, handlers, and formatters explicitly using Python
329 code that calls the configuration methods listed above.
3302. Creating a logging config file and reading it using the :func:`fileConfig`
331 function.
3323. Creating a dictionary of configuration information and passing it
333 to the :func:`dictConfig` function.
334
335The following example configures a very simple logger, a console
336handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000337
338 import logging
339
340 # create logger
341 logger = logging.getLogger("simple_example")
342 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000343
Christian Heimes8b0facf2007-12-04 19:30:01 +0000344 # create console handler and set level to debug
345 ch = logging.StreamHandler()
346 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000347
Christian Heimes8b0facf2007-12-04 19:30:01 +0000348 # create formatter
349 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000350
Christian Heimes8b0facf2007-12-04 19:30:01 +0000351 # add formatter to ch
352 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000353
Christian Heimes8b0facf2007-12-04 19:30:01 +0000354 # add ch to logger
355 logger.addHandler(ch)
356
357 # "application" code
358 logger.debug("debug message")
359 logger.info("info message")
360 logger.warn("warn message")
361 logger.error("error message")
362 logger.critical("critical message")
363
364Running this module from the command line produces the following output::
365
366 $ python simple_logging_module.py
367 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
368 2005-03-19 15:10:26,620 - simple_example - INFO - info message
369 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
370 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
371 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
372
373The following Python module creates a logger, handler, and formatter nearly
374identical to those in the example listed above, with the only difference being
375the names of the objects::
376
377 import logging
378 import logging.config
379
380 logging.config.fileConfig("logging.conf")
381
382 # create logger
383 logger = logging.getLogger("simpleExample")
384
385 # "application" code
386 logger.debug("debug message")
387 logger.info("info message")
388 logger.warn("warn message")
389 logger.error("error message")
390 logger.critical("critical message")
391
392Here is the logging.conf file::
393
394 [loggers]
395 keys=root,simpleExample
396
397 [handlers]
398 keys=consoleHandler
399
400 [formatters]
401 keys=simpleFormatter
402
403 [logger_root]
404 level=DEBUG
405 handlers=consoleHandler
406
407 [logger_simpleExample]
408 level=DEBUG
409 handlers=consoleHandler
410 qualname=simpleExample
411 propagate=0
412
413 [handler_consoleHandler]
414 class=StreamHandler
415 level=DEBUG
416 formatter=simpleFormatter
417 args=(sys.stdout,)
418
419 [formatter_simpleFormatter]
420 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
421 datefmt=
422
423The output is nearly identical to that of the non-config-file-based example::
424
425 $ python simple_logging_config.py
426 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
427 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
428 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
429 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
430 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
431
432You can see that the config file approach has a few advantages over the Python
433code approach, mainly separation of configuration and code and the ability of
434noncoders to easily modify the logging properties.
435
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000436Note that the class names referenced in config files need to be either relative
437to the logging module, or absolute values which can be resolved using normal
438import mechanisms. Thus, you could use either `handlers.WatchedFileHandler`
439(relative to the logging module) or `mypackage.mymodule.MyHandler` (for a
440class defined in package `mypackage` and module `mymodule`, where `mypackage`
441is available on the Python import path).
442
Benjamin Peterson56894b52010-06-28 00:16:12 +0000443In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000444dictionaries to hold configuration information. This provides a superset of the
445functionality of the config-file-based approach outlined above, and is the
446recommended configuration method for new applications and deployments. Because
447a Python dictionary is used to hold configuration information, and since you
448can populate that dictionary using different means, you have more options for
449configuration. For example, you can use a configuration file in JSON format,
450or, if you have access to YAML processing functionality, a file in YAML
451format, to populate the configuration dictionary. Or, of course, you can
452construct the dictionary in Python code, receive it in pickled form over a
453socket, or use whatever approach makes sense for your application.
454
455Here's an example of the same configuration as above, in YAML format for
456the new dictionary-based approach::
457
458 version: 1
459 formatters:
460 simple:
461 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
462 handlers:
463 console:
464 class: logging.StreamHandler
465 level: DEBUG
466 formatter: simple
467 stream: ext://sys.stdout
468 loggers:
469 simpleExample:
470 level: DEBUG
471 handlers: [console]
472 propagate: no
473 root:
474 level: DEBUG
475 handlers: [console]
476
477For more information about logging using a dictionary, see
478:ref:`logging-config-api`.
479
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000480.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000481
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000482Configuring Logging for a Library
483^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
484
485When developing a library which uses logging, some consideration needs to be
486given to its configuration. If the using application does not use logging, and
487library code makes logging calls, then a one-off message "No handlers could be
488found for logger X.Y.Z" is printed to the console. This message is intended
489to catch mistakes in logging configuration, but will confuse an application
490developer who is not aware of logging by the library.
491
492In addition to documenting how a library uses logging, a good way to configure
493library logging so that it does not cause a spurious message is to add a
494handler which does nothing. This avoids the message being printed, since a
495handler will be found: it just doesn't produce any output. If the library user
496configures logging for application use, presumably that configuration will add
497some handlers, and if levels are suitably configured then logging calls made
498in library code will send output to those handlers, as normal.
499
500A do-nothing handler can be simply defined as follows::
501
502 import logging
503
504 class NullHandler(logging.Handler):
505 def emit(self, record):
506 pass
507
508An instance of this handler should be added to the top-level logger of the
509logging namespace used by the library. If all logging by a library *foo* is
510done using loggers with names matching "foo.x.y", then the code::
511
512 import logging
513
514 h = NullHandler()
515 logging.getLogger("foo").addHandler(h)
516
517should have the desired effect. If an organisation produces a number of
518libraries, then the logger name specified can be "orgname.foo" rather than
519just "foo".
520
Georg Brandlf9734072008-12-07 15:30:06 +0000521.. versionadded:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +0000522 The :class:`NullHandler` class was not present in previous versions, but is
523 now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000524
525
Christian Heimes8b0facf2007-12-04 19:30:01 +0000526
527Logging Levels
528--------------
529
Georg Brandl116aa622007-08-15 14:28:22 +0000530The numeric values of logging levels are given in the following table. These are
531primarily of interest if you want to define your own levels, and need them to
532have specific values relative to the predefined levels. If you define a level
533with the same numeric value, it overwrites the predefined value; the predefined
534name is lost.
535
536+--------------+---------------+
537| Level | Numeric value |
538+==============+===============+
539| ``CRITICAL`` | 50 |
540+--------------+---------------+
541| ``ERROR`` | 40 |
542+--------------+---------------+
543| ``WARNING`` | 30 |
544+--------------+---------------+
545| ``INFO`` | 20 |
546+--------------+---------------+
547| ``DEBUG`` | 10 |
548+--------------+---------------+
549| ``NOTSET`` | 0 |
550+--------------+---------------+
551
552Levels can also be associated with loggers, being set either by the developer or
553through loading a saved logging configuration. When a logging method is called
554on a logger, the logger compares its own level with the level associated with
555the method call. If the logger's level is higher than the method call's, no
556logging message is actually generated. This is the basic mechanism controlling
557the verbosity of logging output.
558
559Logging messages are encoded as instances of the :class:`LogRecord` class. When
560a logger decides to actually log an event, a :class:`LogRecord` instance is
561created from the logging message.
562
563Logging messages are subjected to a dispatch mechanism through the use of
564:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
565class. Handlers are responsible for ensuring that a logged message (in the form
566of a :class:`LogRecord`) ends up in a particular location (or set of locations)
567which is useful for the target audience for that message (such as end users,
568support desk staff, system administrators, developers). Handlers are passed
569:class:`LogRecord` instances intended for particular destinations. Each logger
570can have zero, one or more handlers associated with it (via the
571:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
572directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000573of the logger* are called to dispatch the message (unless the *propagate* flag
574for a logger is set to a false value, at which point the passing to ancestor
575handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577Just as for loggers, handlers can have levels associated with them. A handler's
578level acts as a filter in the same way as a logger's level does. If a handler
579decides to actually dispatch an event, the :meth:`emit` method is used to send
580the message to its destination. Most user-defined subclasses of :class:`Handler`
581will need to override this :meth:`emit`.
582
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000583Useful Handlers
584---------------
585
Georg Brandl116aa622007-08-15 14:28:22 +0000586In addition to the base :class:`Handler` class, many useful subclasses are
587provided:
588
589#. :class:`StreamHandler` instances send error messages to streams (file-like
590 objects).
591
592#. :class:`FileHandler` instances send error messages to disk files.
593
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000594.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000595
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000596#. :class:`BaseRotatingHandler` is the base class for handlers that
597 rotate log files at a certain point. It is not meant to be instantiated
598 directly. Instead, use :class:`RotatingFileHandler` or
599 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000600
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000601#. :class:`RotatingFileHandler` instances send error messages to disk
602 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000603
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000604#. :class:`TimedRotatingFileHandler` instances send error messages to
605 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000607#. :class:`SocketHandler` instances send error messages to TCP/IP
608 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000609
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000610#. :class:`DatagramHandler` instances send error messages to UDP
611 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000612
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000613#. :class:`SMTPHandler` instances send error messages to a designated
614 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000615
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000616#. :class:`SysLogHandler` instances send error messages to a Unix
617 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000619#. :class:`NTEventLogHandler` instances send error messages to a
620 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000622#. :class:`MemoryHandler` instances send error messages to a buffer
623 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000624
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000625#. :class:`HTTPHandler` instances send error messages to an HTTP
626 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000628#. :class:`WatchedFileHandler` instances watch the file they are
629 logging to. If the file changes, it is closed and reopened using the file
630 name. This handler is only useful on Unix-like systems; Windows does not
631 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000632
633.. currentmodule:: logging
634
Georg Brandlf9734072008-12-07 15:30:06 +0000635#. :class:`NullHandler` instances do nothing with error messages. They are used
636 by library developers who want to use logging, but want to avoid the "No
637 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000638 the library user has not configured logging. See :ref:`library-config` for
639 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000640
641.. versionadded:: 3.1
642
643The :class:`NullHandler` class was not present in previous versions.
644
Vinay Sajipa17775f2008-12-30 07:32:59 +0000645The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
646classes are defined in the core logging package. The other handlers are
647defined in a sub- module, :mod:`logging.handlers`. (There is also another
648sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000649
650Logged messages are formatted for presentation through instances of the
651:class:`Formatter` class. They are initialized with a format string suitable for
652use with the % operator and a dictionary.
653
654For formatting multiple messages in a batch, instances of
655:class:`BufferingFormatter` can be used. In addition to the format string (which
656is applied to each message in the batch), there is provision for header and
657trailer format strings.
658
659When filtering based on logger level and/or handler level is not enough,
660instances of :class:`Filter` can be added to both :class:`Logger` and
661:class:`Handler` instances (through their :meth:`addFilter` method). Before
662deciding to process a message further, both loggers and handlers consult all
663their filters for permission. If any filter returns a false value, the message
664is not processed further.
665
666The basic :class:`Filter` functionality allows filtering by specific logger
667name. If this feature is used, messages sent to the named logger and its
668children are allowed through the filter, and all others dropped.
669
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000670Module-Level Functions
671----------------------
672
Georg Brandl116aa622007-08-15 14:28:22 +0000673In addition to the classes described above, there are a number of module- level
674functions.
675
676
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000677.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000679 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000680 logger which is the root logger of the hierarchy. If specified, the name is
681 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
682 Choice of these names is entirely up to the developer who is using logging.
683
684 All calls to this function with a given name return the same logger instance.
685 This means that logger instances never need to be passed between different parts
686 of an application.
687
688
689.. function:: getLoggerClass()
690
691 Return either the standard :class:`Logger` class, or the last class passed to
692 :func:`setLoggerClass`. This function may be called from within a new class
693 definition, to ensure that installing a customised :class:`Logger` class will
694 not undo customisations already applied by other code. For example::
695
696 class MyLogger(logging.getLoggerClass()):
697 # ... override behaviour here
698
699
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000700.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
703 message format string, and the *args* are the arguments which are merged into
704 *msg* using the string formatting operator. (Note that this means that you can
705 use keywords in the format string, together with a single dictionary argument.)
706
707 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
708 which, if it does not evaluate as false, causes exception information to be
709 added to the logging message. If an exception tuple (in the format returned by
710 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
711 is called to get the exception information.
712
713 The other optional keyword argument is *extra* which can be used to pass a
714 dictionary which is used to populate the __dict__ of the LogRecord created for
715 the logging event with user-defined attributes. These custom attributes can then
716 be used as you like. For example, they could be incorporated into logged
717 messages. For example::
718
719 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
720 logging.basicConfig(format=FORMAT)
721 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
722 logging.warning("Protocol problem: %s", "connection reset", extra=d)
723
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000724 would print something like ::
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
727
728 The keys in the dictionary passed in *extra* should not clash with the keys used
729 by the logging system. (See the :class:`Formatter` documentation for more
730 information on which keys are used by the logging system.)
731
732 If you choose to use these attributes in logged messages, you need to exercise
733 some care. In the above example, for instance, the :class:`Formatter` has been
734 set up with a format string which expects 'clientip' and 'user' in the attribute
735 dictionary of the LogRecord. If these are missing, the message will not be
736 logged because a string formatting exception will occur. So in this case, you
737 always need to pass the *extra* dictionary with these keys.
738
739 While this might be annoying, this feature is intended for use in specialized
740 circumstances, such as multi-threaded servers where the same code executes in
741 many contexts, and interesting conditions which arise are dependent on this
742 context (such as remote client IP address and authenticated user name, in the
743 above example). In such circumstances, it is likely that specialized
744 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
745
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000747.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000748
749 Logs a message with level :const:`INFO` on the root logger. The arguments are
750 interpreted as for :func:`debug`.
751
752
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000753.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755 Logs a message with level :const:`WARNING` on the root logger. The arguments are
756 interpreted as for :func:`debug`.
757
758
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000759.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000760
761 Logs a message with level :const:`ERROR` on the root logger. The arguments are
762 interpreted as for :func:`debug`.
763
764
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000765.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000766
767 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
768 are interpreted as for :func:`debug`.
769
770
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000771.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000772
773 Logs a message with level :const:`ERROR` on the root logger. The arguments are
774 interpreted as for :func:`debug`. Exception info is added to the logging
775 message. This function should only be called from an exception handler.
776
777
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000778.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000779
780 Logs a message with level *level* on the root logger. The other arguments are
781 interpreted as for :func:`debug`.
782
783
784.. function:: disable(lvl)
785
786 Provides an overriding level *lvl* for all loggers which takes precedence over
787 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000788 output down across the whole application, this function can be useful. Its
789 effect is to disable all logging calls of severity *lvl* and below, so that
790 if you call it with a value of INFO, then all INFO and DEBUG events would be
791 discarded, whereas those of severity WARNING and above would be processed
792 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794
795.. function:: addLevelName(lvl, levelName)
796
797 Associates level *lvl* with text *levelName* in an internal dictionary, which is
798 used to map numeric levels to a textual representation, for example when a
799 :class:`Formatter` formats a message. This function can also be used to define
800 your own levels. The only constraints are that all levels used must be
801 registered using this function, levels should be positive integers and they
802 should increase in increasing order of severity.
803
804
805.. function:: getLevelName(lvl)
806
807 Returns the textual representation of logging level *lvl*. If the level is one
808 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
809 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
810 have associated levels with names using :func:`addLevelName` then the name you
811 have associated with *lvl* is returned. If a numeric value corresponding to one
812 of the defined levels is passed in, the corresponding string representation is
813 returned. Otherwise, the string "Level %s" % lvl is returned.
814
815
816.. function:: makeLogRecord(attrdict)
817
818 Creates and returns a new :class:`LogRecord` instance whose attributes are
819 defined by *attrdict*. This function is useful for taking a pickled
820 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
821 it as a :class:`LogRecord` instance at the receiving end.
822
823
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000824.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826 Does basic configuration for the logging system by creating a
827 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000828 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000829 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
830 if no handlers are defined for the root logger.
831
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000832 This function does nothing if the root logger already has handlers
833 configured for it.
834
Georg Brandl116aa622007-08-15 14:28:22 +0000835 The following keyword arguments are supported.
836
837 +--------------+---------------------------------------------+
838 | Format | Description |
839 +==============+=============================================+
840 | ``filename`` | Specifies that a FileHandler be created, |
841 | | using the specified filename, rather than a |
842 | | StreamHandler. |
843 +--------------+---------------------------------------------+
844 | ``filemode`` | Specifies the mode to open the file, if |
845 | | filename is specified (if filemode is |
846 | | unspecified, it defaults to 'a'). |
847 +--------------+---------------------------------------------+
848 | ``format`` | Use the specified format string for the |
849 | | handler. |
850 +--------------+---------------------------------------------+
851 | ``datefmt`` | Use the specified date/time format. |
852 +--------------+---------------------------------------------+
853 | ``level`` | Set the root logger level to the specified |
854 | | level. |
855 +--------------+---------------------------------------------+
856 | ``stream`` | Use the specified stream to initialize the |
857 | | StreamHandler. Note that this argument is |
858 | | incompatible with 'filename' - if both are |
859 | | present, 'stream' is ignored. |
860 +--------------+---------------------------------------------+
861
862
863.. function:: shutdown()
864
865 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000866 closing all handlers. This should be called at application exit and no
867 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869
870.. function:: setLoggerClass(klass)
871
872 Tells the logging system to use the class *klass* when instantiating a logger.
873 The class should define :meth:`__init__` such that only a name argument is
874 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
875 function is typically called before any loggers are instantiated by applications
876 which need to use custom logger behavior.
877
878
879.. seealso::
880
881 :pep:`282` - A Logging System
882 The proposal which described this feature for inclusion in the Python standard
883 library.
884
Christian Heimes255f53b2007-12-08 15:33:56 +0000885 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000886 This is the original source for the :mod:`logging` package. The version of the
887 package available from this site is suitable for use with Python 1.5.2, 2.1.x
888 and 2.2.x, which do not include the :mod:`logging` package in the standard
889 library.
890
891
892Logger Objects
893--------------
894
895Loggers have the following attributes and methods. Note that Loggers are never
896instantiated directly, but always through the module-level function
897``logging.getLogger(name)``.
898
899
900.. attribute:: Logger.propagate
901
902 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000903 its child loggers to the handlers of higher level (ancestor) loggers. The
904 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906
907.. method:: Logger.setLevel(lvl)
908
909 Sets the threshold for this logger to *lvl*. Logging messages which are less
910 severe than *lvl* will be ignored. When a logger is created, the level is set to
911 :const:`NOTSET` (which causes all messages to be processed when the logger is
912 the root logger, or delegation to the parent when the logger is a non-root
913 logger). Note that the root logger is created with level :const:`WARNING`.
914
915 The term "delegation to the parent" means that if a logger has a level of
916 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
917 a level other than NOTSET is found, or the root is reached.
918
919 If an ancestor is found with a level other than NOTSET, then that ancestor's
920 level is treated as the effective level of the logger where the ancestor search
921 began, and is used to determine how a logging event is handled.
922
923 If the root is reached, and it has a level of NOTSET, then all messages will be
924 processed. Otherwise, the root's level will be used as the effective level.
925
926
927.. method:: Logger.isEnabledFor(lvl)
928
929 Indicates if a message of severity *lvl* would be processed by this logger.
930 This method checks first the module-level level set by
931 ``logging.disable(lvl)`` and then the logger's effective level as determined
932 by :meth:`getEffectiveLevel`.
933
934
935.. method:: Logger.getEffectiveLevel()
936
937 Indicates the effective level for this logger. If a value other than
938 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
939 the hierarchy is traversed towards the root until a value other than
940 :const:`NOTSET` is found, and that value is returned.
941
942
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000943.. method:: Logger.getChild(suffix)
944
945 Returns a logger which is a descendant to this logger, as determined by the suffix.
946 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
947 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
948 convenience method, useful when the parent logger is named using e.g. ``__name__``
949 rather than a literal string.
950
951 .. versionadded:: 3.2
952
Georg Brandl67b21b72010-08-17 15:07:14 +0000953
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000954.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
957 message format string, and the *args* are the arguments which are merged into
958 *msg* using the string formatting operator. (Note that this means that you can
959 use keywords in the format string, together with a single dictionary argument.)
960
961 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
962 which, if it does not evaluate as false, causes exception information to be
963 added to the logging message. If an exception tuple (in the format returned by
964 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
965 is called to get the exception information.
966
967 The other optional keyword argument is *extra* which can be used to pass a
968 dictionary which is used to populate the __dict__ of the LogRecord created for
969 the logging event with user-defined attributes. These custom attributes can then
970 be used as you like. For example, they could be incorporated into logged
971 messages. For example::
972
973 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
974 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000975 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +0000976 logger = logging.getLogger("tcpserver")
977 logger.warning("Protocol problem: %s", "connection reset", extra=d)
978
979 would print something like ::
980
981 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
982
983 The keys in the dictionary passed in *extra* should not clash with the keys used
984 by the logging system. (See the :class:`Formatter` documentation for more
985 information on which keys are used by the logging system.)
986
987 If you choose to use these attributes in logged messages, you need to exercise
988 some care. In the above example, for instance, the :class:`Formatter` has been
989 set up with a format string which expects 'clientip' and 'user' in the attribute
990 dictionary of the LogRecord. If these are missing, the message will not be
991 logged because a string formatting exception will occur. So in this case, you
992 always need to pass the *extra* dictionary with these keys.
993
994 While this might be annoying, this feature is intended for use in specialized
995 circumstances, such as multi-threaded servers where the same code executes in
996 many contexts, and interesting conditions which arise are dependent on this
997 context (such as remote client IP address and authenticated user name, in the
998 above example). In such circumstances, it is likely that specialized
999 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1000
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001002.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004 Logs a message with level :const:`INFO` on this logger. The arguments are
1005 interpreted as for :meth:`debug`.
1006
1007
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001008.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001009
1010 Logs a message with level :const:`WARNING` on this logger. The arguments are
1011 interpreted as for :meth:`debug`.
1012
1013
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001014.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001015
1016 Logs a message with level :const:`ERROR` on this logger. The arguments are
1017 interpreted as for :meth:`debug`.
1018
1019
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001020.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001021
1022 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1023 interpreted as for :meth:`debug`.
1024
1025
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001026.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001027
1028 Logs a message with integer level *lvl* on this logger. The other arguments are
1029 interpreted as for :meth:`debug`.
1030
1031
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001032.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034 Logs a message with level :const:`ERROR` on this logger. The arguments are
1035 interpreted as for :meth:`debug`. Exception info is added to the logging
1036 message. This method should only be called from an exception handler.
1037
1038
1039.. method:: Logger.addFilter(filt)
1040
1041 Adds the specified filter *filt* to this logger.
1042
1043
1044.. method:: Logger.removeFilter(filt)
1045
1046 Removes the specified filter *filt* from this logger.
1047
1048
1049.. method:: Logger.filter(record)
1050
1051 Applies this logger's filters to the record and returns a true value if the
1052 record is to be processed.
1053
1054
1055.. method:: Logger.addHandler(hdlr)
1056
1057 Adds the specified handler *hdlr* to this logger.
1058
1059
1060.. method:: Logger.removeHandler(hdlr)
1061
1062 Removes the specified handler *hdlr* from this logger.
1063
1064
1065.. method:: Logger.findCaller()
1066
1067 Finds the caller's source filename and line number. Returns the filename, line
1068 number and function name as a 3-element tuple.
1069
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071.. method:: Logger.handle(record)
1072
1073 Handles a record by passing it to all handlers associated with this logger and
1074 its ancestors (until a false value of *propagate* is found). This method is used
1075 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001076 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001077
1078
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001079.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001080
1081 This is a factory method which can be overridden in subclasses to create
1082 specialized :class:`LogRecord` instances.
1083
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085.. _minimal-example:
1086
1087Basic example
1088-------------
1089
Georg Brandl116aa622007-08-15 14:28:22 +00001090The :mod:`logging` package provides a lot of flexibility, and its configuration
1091can appear daunting. This section demonstrates that simple use of the logging
1092package is possible.
1093
1094The simplest example shows logging to the console::
1095
1096 import logging
1097
1098 logging.debug('A debug message')
1099 logging.info('Some information')
1100 logging.warning('A shot across the bows')
1101
1102If you run the above script, you'll see this::
1103
1104 WARNING:root:A shot across the bows
1105
1106Because no particular logger was specified, the system used the root logger. The
1107debug and info messages didn't appear because by default, the root logger is
1108configured to only handle messages with a severity of WARNING or above. The
1109message format is also a configuration default, as is the output destination of
1110the messages - ``sys.stderr``. The severity level, the message format and
1111destination can be easily changed, as shown in the example below::
1112
1113 import logging
1114
1115 logging.basicConfig(level=logging.DEBUG,
1116 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001117 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001118 filemode='w')
1119 logging.debug('A debug message')
1120 logging.info('Some information')
1121 logging.warning('A shot across the bows')
1122
1123The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001124which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001125something like the following::
1126
1127 2004-07-02 13:00:08,743 DEBUG A debug message
1128 2004-07-02 13:00:08,743 INFO Some information
1129 2004-07-02 13:00:08,743 WARNING A shot across the bows
1130
1131This time, all messages with a severity of DEBUG or above were handled, and the
1132format of the messages was also changed, and output went to the specified file
1133rather than the console.
1134
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001135.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001136
1137Formatting uses the old Python string formatting - see section
1138:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001139specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1140documentation.
1141
1142+-------------------+-----------------------------------------------+
1143| Format | Description |
1144+===================+===============================================+
1145| ``%(name)s`` | Name of the logger (logging channel). |
1146+-------------------+-----------------------------------------------+
1147| ``%(levelname)s`` | Text logging level for the message |
1148| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1149| | ``'ERROR'``, ``'CRITICAL'``). |
1150+-------------------+-----------------------------------------------+
1151| ``%(asctime)s`` | Human-readable time when the |
1152| | :class:`LogRecord` was created. By default |
1153| | this is of the form "2003-07-08 16:49:45,896" |
1154| | (the numbers after the comma are millisecond |
1155| | portion of the time). |
1156+-------------------+-----------------------------------------------+
1157| ``%(message)s`` | The logged message. |
1158+-------------------+-----------------------------------------------+
1159
1160To change the date/time format, you can pass an additional keyword parameter,
1161*datefmt*, as in the following::
1162
1163 import logging
1164
1165 logging.basicConfig(level=logging.DEBUG,
1166 format='%(asctime)s %(levelname)-8s %(message)s',
1167 datefmt='%a, %d %b %Y %H:%M:%S',
1168 filename='/temp/myapp.log',
1169 filemode='w')
1170 logging.debug('A debug message')
1171 logging.info('Some information')
1172 logging.warning('A shot across the bows')
1173
1174which would result in output like ::
1175
1176 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1177 Fri, 02 Jul 2004 13:06:18 INFO Some information
1178 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1179
1180The date format string follows the requirements of :func:`strftime` - see the
1181documentation for the :mod:`time` module.
1182
1183If, instead of sending logging output to the console or a file, you'd rather use
1184a file-like object which you have created separately, you can pass it to
1185:func:`basicConfig` using the *stream* keyword argument. Note that if both
1186*stream* and *filename* keyword arguments are passed, the *stream* argument is
1187ignored.
1188
1189Of course, you can put variable information in your output. To do this, simply
1190have the message be a format string and pass in additional arguments containing
1191the variable information, as in the following example::
1192
1193 import logging
1194
1195 logging.basicConfig(level=logging.DEBUG,
1196 format='%(asctime)s %(levelname)-8s %(message)s',
1197 datefmt='%a, %d %b %Y %H:%M:%S',
1198 filename='/temp/myapp.log',
1199 filemode='w')
1200 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1201
1202which would result in ::
1203
1204 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1205
1206
1207.. _multiple-destinations:
1208
1209Logging to multiple destinations
1210--------------------------------
1211
1212Let's say you want to log to console and file with different message formats and
1213in differing circumstances. Say you want to log messages with levels of DEBUG
1214and higher to file, and those messages at level INFO and higher to the console.
1215Let's also assume that the file should contain timestamps, but the console
1216messages should not. Here's how you can achieve this::
1217
1218 import logging
1219
1220 # set up logging to file - see previous section for more details
1221 logging.basicConfig(level=logging.DEBUG,
1222 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1223 datefmt='%m-%d %H:%M',
1224 filename='/temp/myapp.log',
1225 filemode='w')
1226 # define a Handler which writes INFO messages or higher to the sys.stderr
1227 console = logging.StreamHandler()
1228 console.setLevel(logging.INFO)
1229 # set a format which is simpler for console use
1230 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1231 # tell the handler to use this format
1232 console.setFormatter(formatter)
1233 # add the handler to the root logger
1234 logging.getLogger('').addHandler(console)
1235
1236 # Now, we can log to the root logger, or any other logger. First the root...
1237 logging.info('Jackdaws love my big sphinx of quartz.')
1238
1239 # Now, define a couple of other loggers which might represent areas in your
1240 # application:
1241
1242 logger1 = logging.getLogger('myapp.area1')
1243 logger2 = logging.getLogger('myapp.area2')
1244
1245 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1246 logger1.info('How quickly daft jumping zebras vex.')
1247 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1248 logger2.error('The five boxing wizards jump quickly.')
1249
1250When you run this, on the console you will see ::
1251
1252 root : INFO Jackdaws love my big sphinx of quartz.
1253 myapp.area1 : INFO How quickly daft jumping zebras vex.
1254 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1255 myapp.area2 : ERROR The five boxing wizards jump quickly.
1256
1257and in the file you will see something like ::
1258
1259 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1260 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1261 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1262 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1263 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1264
1265As you can see, the DEBUG message only shows up in the file. The other messages
1266are sent to both destinations.
1267
1268This example uses console and file handlers, but you can use any number and
1269combination of handlers you choose.
1270
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001271.. _logging-exceptions:
1272
1273Exceptions raised during logging
1274--------------------------------
1275
1276The logging package is designed to swallow exceptions which occur while logging
1277in production. This is so that errors which occur while handling logging events
1278- such as logging misconfiguration, network or other similar errors - do not
1279cause the application using logging to terminate prematurely.
1280
1281:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1282swallowed. Other exceptions which occur during the :meth:`emit` method of a
1283:class:`Handler` subclass are passed to its :meth:`handleError` method.
1284
1285The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001286to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1287traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001288
Georg Brandlef871f62010-03-12 10:06:40 +00001289**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001290during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001291occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001292usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
Christian Heimes790c8232008-01-07 21:14:23 +00001294.. _context-info:
1295
1296Adding contextual information to your logging output
1297----------------------------------------------------
1298
1299Sometimes you want logging output to contain contextual information in
1300addition to the parameters passed to the logging call. For example, in a
1301networked application, it may be desirable to log client-specific information
1302in the log (e.g. remote client's username, or IP address). Although you could
1303use the *extra* parameter to achieve this, it's not always convenient to pass
1304the information in this way. While it might be tempting to create
1305:class:`Logger` instances on a per-connection basis, this is not a good idea
1306because these instances are not garbage collected. While this is not a problem
1307in practice, when the number of :class:`Logger` instances is dependent on the
1308level of granularity you want to use in logging an application, it could
1309be hard to manage if the number of :class:`Logger` instances becomes
1310effectively unbounded.
1311
Christian Heimes04c420f2008-01-18 18:40:46 +00001312An easy way in which you can pass contextual information to be output along
1313with logging event information is to use the :class:`LoggerAdapter` class.
1314This class is designed to look like a :class:`Logger`, so that you can call
1315:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1316:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1317same signatures as their counterparts in :class:`Logger`, so you can use the
1318two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001319
Christian Heimes04c420f2008-01-18 18:40:46 +00001320When you create an instance of :class:`LoggerAdapter`, you pass it a
1321:class:`Logger` instance and a dict-like object which contains your contextual
1322information. When you call one of the logging methods on an instance of
1323:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1324:class:`Logger` passed to its constructor, and arranges to pass the contextual
1325information in the delegated call. Here's a snippet from the code of
1326:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001327
Christian Heimes04c420f2008-01-18 18:40:46 +00001328 def debug(self, msg, *args, **kwargs):
1329 """
1330 Delegate a debug call to the underlying logger, after adding
1331 contextual information from this adapter instance.
1332 """
1333 msg, kwargs = self.process(msg, kwargs)
1334 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001335
Christian Heimes04c420f2008-01-18 18:40:46 +00001336The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1337information is added to the logging output. It's passed the message and
1338keyword arguments of the logging call, and it passes back (potentially)
1339modified versions of these to use in the call to the underlying logger. The
1340default implementation of this method leaves the message alone, but inserts
1341an "extra" key in the keyword argument whose value is the dict-like object
1342passed to the constructor. Of course, if you had passed an "extra" keyword
1343argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001344
Christian Heimes04c420f2008-01-18 18:40:46 +00001345The advantage of using "extra" is that the values in the dict-like object are
1346merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1347customized strings with your :class:`Formatter` instances which know about
1348the keys of the dict-like object. If you need a different method, e.g. if you
1349want to prepend or append the contextual information to the message string,
1350you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1351to do what you need. Here's an example script which uses this class, which
1352also illustrates what dict-like behaviour is needed from an arbitrary
1353"dict-like" object for use in the constructor::
1354
Christian Heimes587c2bf2008-01-19 16:21:02 +00001355 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001356
Christian Heimes587c2bf2008-01-19 16:21:02 +00001357 class ConnInfo:
1358 """
1359 An example class which shows how an arbitrary class can be used as
1360 the 'extra' context information repository passed to a LoggerAdapter.
1361 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001362
Christian Heimes587c2bf2008-01-19 16:21:02 +00001363 def __getitem__(self, name):
1364 """
1365 To allow this instance to look like a dict.
1366 """
1367 from random import choice
1368 if name == "ip":
1369 result = choice(["127.0.0.1", "192.168.0.1"])
1370 elif name == "user":
1371 result = choice(["jim", "fred", "sheila"])
1372 else:
1373 result = self.__dict__.get(name, "?")
1374 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001375
Christian Heimes587c2bf2008-01-19 16:21:02 +00001376 def __iter__(self):
1377 """
1378 To allow iteration over keys, which will be merged into
1379 the LogRecord dict before formatting and output.
1380 """
1381 keys = ["ip", "user"]
1382 keys.extend(self.__dict__.keys())
1383 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001384
Christian Heimes587c2bf2008-01-19 16:21:02 +00001385 if __name__ == "__main__":
1386 from random import choice
1387 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1388 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1389 { "ip" : "123.231.231.123", "user" : "sheila" })
1390 logging.basicConfig(level=logging.DEBUG,
1391 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1392 a1.debug("A debug message")
1393 a1.info("An info message with %s", "some parameters")
1394 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1395 for x in range(10):
1396 lvl = choice(levels)
1397 lvlname = logging.getLevelName(lvl)
1398 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001399
1400When this script is run, the output should look something like this::
1401
Christian Heimes587c2bf2008-01-19 16:21:02 +00001402 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1403 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1404 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
1405 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
1406 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
1407 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
1408 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
1409 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
1410 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
1411 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
1412 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
1413 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Christian Heimes04c420f2008-01-18 18:40:46 +00001414
Christian Heimes790c8232008-01-07 21:14:23 +00001415
Vinay Sajipd31f3632010-06-29 15:31:15 +00001416.. _multiple-processes:
1417
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001418Logging to a single file from multiple processes
1419------------------------------------------------
1420
1421Although logging is thread-safe, and logging to a single file from multiple
1422threads in a single process *is* supported, logging to a single file from
1423*multiple processes* is *not* supported, because there is no standard way to
1424serialize access to a single file across multiple processes in Python. If you
1425need to log to a single file from multiple processes, the best way of doing
1426this is to have all the processes log to a :class:`SocketHandler`, and have a
1427separate process which implements a socket server which reads from the socket
1428and logs to file. (If you prefer, you can dedicate one thread in one of the
1429existing processes to perform this function.) The following section documents
1430this approach in more detail and includes a working socket receiver which can
1431be used as a starting point for you to adapt in your own applications.
1432
Vinay Sajip5a92b132009-08-15 23:35:08 +00001433If you are using a recent version of Python which includes the
1434:mod:`multiprocessing` module, you can write your own handler which uses the
1435:class:`Lock` class from this module to serialize access to the file from
1436your processes. The existing :class:`FileHandler` and subclasses do not make
1437use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001438Note that at present, the :mod:`multiprocessing` module does not provide
1439working lock functionality on all platforms (see
1440http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001441
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001442
Georg Brandl116aa622007-08-15 14:28:22 +00001443.. _network-logging:
1444
1445Sending and receiving logging events across a network
1446-----------------------------------------------------
1447
1448Let's say you want to send logging events across a network, and handle them at
1449the receiving end. A simple way of doing this is attaching a
1450:class:`SocketHandler` instance to the root logger at the sending end::
1451
1452 import logging, logging.handlers
1453
1454 rootLogger = logging.getLogger('')
1455 rootLogger.setLevel(logging.DEBUG)
1456 socketHandler = logging.handlers.SocketHandler('localhost',
1457 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1458 # don't bother with a formatter, since a socket handler sends the event as
1459 # an unformatted pickle
1460 rootLogger.addHandler(socketHandler)
1461
1462 # Now, we can log to the root logger, or any other logger. First the root...
1463 logging.info('Jackdaws love my big sphinx of quartz.')
1464
1465 # Now, define a couple of other loggers which might represent areas in your
1466 # application:
1467
1468 logger1 = logging.getLogger('myapp.area1')
1469 logger2 = logging.getLogger('myapp.area2')
1470
1471 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1472 logger1.info('How quickly daft jumping zebras vex.')
1473 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1474 logger2.error('The five boxing wizards jump quickly.')
1475
Alexandre Vassalottice261952008-05-12 02:31:37 +00001476At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001477module. Here is a basic working example::
1478
Georg Brandla35f4b92009-05-31 16:41:59 +00001479 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001480 import logging
1481 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001482 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001483 import struct
1484
1485
Alexandre Vassalottice261952008-05-12 02:31:37 +00001486 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001487 """Handler for a streaming logging request.
1488
1489 This basically logs the record using whatever logging policy is
1490 configured locally.
1491 """
1492
1493 def handle(self):
1494 """
1495 Handle multiple requests - each expected to be a 4-byte length,
1496 followed by the LogRecord in pickle format. Logs the record
1497 according to whatever policy is configured locally.
1498 """
Collin Winter46334482007-09-10 00:49:57 +00001499 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001500 chunk = self.connection.recv(4)
1501 if len(chunk) < 4:
1502 break
1503 slen = struct.unpack(">L", chunk)[0]
1504 chunk = self.connection.recv(slen)
1505 while len(chunk) < slen:
1506 chunk = chunk + self.connection.recv(slen - len(chunk))
1507 obj = self.unPickle(chunk)
1508 record = logging.makeLogRecord(obj)
1509 self.handleLogRecord(record)
1510
1511 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001512 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001513
1514 def handleLogRecord(self, record):
1515 # if a name is specified, we use the named logger rather than the one
1516 # implied by the record.
1517 if self.server.logname is not None:
1518 name = self.server.logname
1519 else:
1520 name = record.name
1521 logger = logging.getLogger(name)
1522 # N.B. EVERY record gets logged. This is because Logger.handle
1523 # is normally called AFTER logger-level filtering. If you want
1524 # to do filtering, do it at the client end to save wasting
1525 # cycles and network bandwidth!
1526 logger.handle(record)
1527
Alexandre Vassalottice261952008-05-12 02:31:37 +00001528 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001529 """simple TCP socket-based logging receiver suitable for testing.
1530 """
1531
1532 allow_reuse_address = 1
1533
1534 def __init__(self, host='localhost',
1535 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1536 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001537 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001538 self.abort = 0
1539 self.timeout = 1
1540 self.logname = None
1541
1542 def serve_until_stopped(self):
1543 import select
1544 abort = 0
1545 while not abort:
1546 rd, wr, ex = select.select([self.socket.fileno()],
1547 [], [],
1548 self.timeout)
1549 if rd:
1550 self.handle_request()
1551 abort = self.abort
1552
1553 def main():
1554 logging.basicConfig(
1555 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1556 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001557 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001558 tcpserver.serve_until_stopped()
1559
1560 if __name__ == "__main__":
1561 main()
1562
1563First run the server, and then the client. On the client side, nothing is
1564printed on the console; on the server side, you should see something like::
1565
1566 About to start TCP server...
1567 59 root INFO Jackdaws love my big sphinx of quartz.
1568 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1569 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1570 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1571 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1572
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001573Note that there are some security issues with pickle in some scenarios. If
1574these affect you, you can use an alternative serialization scheme by overriding
1575the :meth:`makePickle` method and implementing your alternative there, as
1576well as adapting the above script to use your alternative serialization.
1577
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001578Using arbitrary objects as messages
1579-----------------------------------
1580
1581In the preceding sections and examples, it has been assumed that the message
1582passed when logging the event is a string. However, this is not the only
1583possibility. You can pass an arbitrary object as a message, and its
1584:meth:`__str__` method will be called when the logging system needs to convert
1585it to a string representation. In fact, if you want to, you can avoid
1586computing a string representation altogether - for example, the
1587:class:`SocketHandler` emits an event by pickling it and sending it over the
1588wire.
1589
1590Optimization
1591------------
1592
1593Formatting of message arguments is deferred until it cannot be avoided.
1594However, computing the arguments passed to the logging method can also be
1595expensive, and you may want to avoid doing it if the logger will just throw
1596away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1597method which takes a level argument and returns true if the event would be
1598created by the Logger for that level of call. You can write code like this::
1599
1600 if logger.isEnabledFor(logging.DEBUG):
1601 logger.debug("Message with %s, %s", expensive_func1(),
1602 expensive_func2())
1603
1604so that if the logger's threshold is set above ``DEBUG``, the calls to
1605:func:`expensive_func1` and :func:`expensive_func2` are never made.
1606
1607There are other optimizations which can be made for specific applications which
1608need more precise control over what logging information is collected. Here's a
1609list of things you can do to avoid processing during logging which you don't
1610need:
1611
1612+-----------------------------------------------+----------------------------------------+
1613| What you don't want to collect | How to avoid collecting it |
1614+===============================================+========================================+
1615| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1616+-----------------------------------------------+----------------------------------------+
1617| Threading information. | Set ``logging.logThreads`` to ``0``. |
1618+-----------------------------------------------+----------------------------------------+
1619| Process information. | Set ``logging.logProcesses`` to ``0``. |
1620+-----------------------------------------------+----------------------------------------+
1621
1622Also note that the core logging module only includes the basic handlers. If
1623you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1624take up any memory.
1625
1626.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001627
1628Handler Objects
1629---------------
1630
1631Handlers have the following attributes and methods. Note that :class:`Handler`
1632is never instantiated directly; this class acts as a base for more useful
1633subclasses. However, the :meth:`__init__` method in subclasses needs to call
1634:meth:`Handler.__init__`.
1635
1636
1637.. method:: Handler.__init__(level=NOTSET)
1638
1639 Initializes the :class:`Handler` instance by setting its level, setting the list
1640 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1641 serializing access to an I/O mechanism.
1642
1643
1644.. method:: Handler.createLock()
1645
1646 Initializes a thread lock which can be used to serialize access to underlying
1647 I/O functionality which may not be threadsafe.
1648
1649
1650.. method:: Handler.acquire()
1651
1652 Acquires the thread lock created with :meth:`createLock`.
1653
1654
1655.. method:: Handler.release()
1656
1657 Releases the thread lock acquired with :meth:`acquire`.
1658
1659
1660.. method:: Handler.setLevel(lvl)
1661
1662 Sets the threshold for this handler to *lvl*. Logging messages which are less
1663 severe than *lvl* will be ignored. When a handler is created, the level is set
1664 to :const:`NOTSET` (which causes all messages to be processed).
1665
1666
1667.. method:: Handler.setFormatter(form)
1668
1669 Sets the :class:`Formatter` for this handler to *form*.
1670
1671
1672.. method:: Handler.addFilter(filt)
1673
1674 Adds the specified filter *filt* to this handler.
1675
1676
1677.. method:: Handler.removeFilter(filt)
1678
1679 Removes the specified filter *filt* from this handler.
1680
1681
1682.. method:: Handler.filter(record)
1683
1684 Applies this handler's filters to the record and returns a true value if the
1685 record is to be processed.
1686
1687
1688.. method:: Handler.flush()
1689
1690 Ensure all logging output has been flushed. This version does nothing and is
1691 intended to be implemented by subclasses.
1692
1693
1694.. method:: Handler.close()
1695
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001696 Tidy up any resources used by the handler. This version does no output but
1697 removes the handler from an internal list of handlers which is closed when
1698 :func:`shutdown` is called. Subclasses should ensure that this gets called
1699 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001700
1701
1702.. method:: Handler.handle(record)
1703
1704 Conditionally emits the specified logging record, depending on filters which may
1705 have been added to the handler. Wraps the actual emission of the record with
1706 acquisition/release of the I/O thread lock.
1707
1708
1709.. method:: Handler.handleError(record)
1710
1711 This method should be called from handlers when an exception is encountered
1712 during an :meth:`emit` call. By default it does nothing, which means that
1713 exceptions get silently ignored. This is what is mostly wanted for a logging
1714 system - most users will not care about errors in the logging system, they are
1715 more interested in application errors. You could, however, replace this with a
1716 custom handler if you wish. The specified record is the one which was being
1717 processed when the exception occurred.
1718
1719
1720.. method:: Handler.format(record)
1721
1722 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1723 default formatter for the module.
1724
1725
1726.. method:: Handler.emit(record)
1727
1728 Do whatever it takes to actually log the specified logging record. This version
1729 is intended to be implemented by subclasses and so raises a
1730 :exc:`NotImplementedError`.
1731
1732
Vinay Sajipd31f3632010-06-29 15:31:15 +00001733.. _stream-handler:
1734
Georg Brandl116aa622007-08-15 14:28:22 +00001735StreamHandler
1736^^^^^^^^^^^^^
1737
1738The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1739sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1740file-like object (or, more precisely, any object which supports :meth:`write`
1741and :meth:`flush` methods).
1742
1743
Benjamin Peterson1baf4652009-12-31 03:11:23 +00001744.. currentmodule:: logging
1745
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001746.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001747
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001748 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00001749 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1750 will be used.
1751
1752
Benjamin Petersone41251e2008-04-25 01:59:09 +00001753 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00001754
Benjamin Petersone41251e2008-04-25 01:59:09 +00001755 If a formatter is specified, it is used to format the record. The record
1756 is then written to the stream with a trailing newline. If exception
1757 information is present, it is formatted using
1758 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00001759
1760
Benjamin Petersone41251e2008-04-25 01:59:09 +00001761 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00001762
Benjamin Petersone41251e2008-04-25 01:59:09 +00001763 Flushes the stream by calling its :meth:`flush` method. Note that the
1764 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001765 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00001766
1767
Vinay Sajipd31f3632010-06-29 15:31:15 +00001768.. _file-handler:
1769
Georg Brandl116aa622007-08-15 14:28:22 +00001770FileHandler
1771^^^^^^^^^^^
1772
1773The :class:`FileHandler` class, located in the core :mod:`logging` package,
1774sends logging output to a disk file. It inherits the output functionality from
1775:class:`StreamHandler`.
1776
1777
Vinay Sajipd31f3632010-06-29 15:31:15 +00001778.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001779
1780 Returns a new instance of the :class:`FileHandler` class. The specified file is
1781 opened and used as the stream for logging. If *mode* is not specified,
1782 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00001783 with that encoding. If *delay* is true, then file opening is deferred until the
1784 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00001785
1786
Benjamin Petersone41251e2008-04-25 01:59:09 +00001787 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00001788
Benjamin Petersone41251e2008-04-25 01:59:09 +00001789 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00001790
1791
Benjamin Petersone41251e2008-04-25 01:59:09 +00001792 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00001793
Benjamin Petersone41251e2008-04-25 01:59:09 +00001794 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00001795
Vinay Sajipd31f3632010-06-29 15:31:15 +00001796.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001797
Vinay Sajipaa672eb2009-01-02 18:53:45 +00001798NullHandler
1799^^^^^^^^^^^
1800
1801.. versionadded:: 3.1
1802
1803The :class:`NullHandler` class, located in the core :mod:`logging` package,
1804does not do any formatting or output. It is essentially a "no-op" handler
1805for use by library developers.
1806
1807
1808.. class:: NullHandler()
1809
1810 Returns a new instance of the :class:`NullHandler` class.
1811
1812
1813 .. method:: emit(record)
1814
1815 This method does nothing.
1816
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00001817See :ref:`library-config` for more information on how to use
1818:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00001819
Vinay Sajipd31f3632010-06-29 15:31:15 +00001820.. _watched-file-handler:
1821
Georg Brandl116aa622007-08-15 14:28:22 +00001822WatchedFileHandler
1823^^^^^^^^^^^^^^^^^^
1824
Benjamin Peterson058e31e2009-01-16 03:54:08 +00001825.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00001826
Georg Brandl116aa622007-08-15 14:28:22 +00001827The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1828module, is a :class:`FileHandler` which watches the file it is logging to. If
1829the file changes, it is closed and reopened using the file name.
1830
1831A file change can happen because of usage of programs such as *newsyslog* and
1832*logrotate* which perform log file rotation. This handler, intended for use
1833under Unix/Linux, watches the file to see if it has changed since the last emit.
1834(A file is deemed to have changed if its device or inode have changed.) If the
1835file has changed, the old file stream is closed, and the file opened to get a
1836new stream.
1837
1838This handler is not appropriate for use under Windows, because under Windows
1839open log files cannot be moved or renamed - logging opens the files with
1840exclusive locks - and so there is no need for such a handler. Furthermore,
1841*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1842this value.
1843
1844
Christian Heimese7a15bb2008-01-24 16:21:45 +00001845.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00001846
1847 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1848 file is opened and used as the stream for logging. If *mode* is not specified,
1849 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00001850 with that encoding. If *delay* is true, then file opening is deferred until the
1851 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00001852
1853
Benjamin Petersone41251e2008-04-25 01:59:09 +00001854 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00001855
Benjamin Petersone41251e2008-04-25 01:59:09 +00001856 Outputs the record to the file, but first checks to see if the file has
1857 changed. If it has, the existing stream is flushed and closed and the
1858 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00001859
Vinay Sajipd31f3632010-06-29 15:31:15 +00001860.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001861
1862RotatingFileHandler
1863^^^^^^^^^^^^^^^^^^^
1864
1865The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1866module, supports rotation of disk log files.
1867
1868
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001869.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001870
1871 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1872 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00001873 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
1874 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 Brandl116aa622007-08-15 14:28:22 +00001876
1877 You can use the *maxBytes* and *backupCount* values to allow the file to
1878 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1879 the file is closed and a new file is silently opened for output. Rollover occurs
1880 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1881 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1882 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1883 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1884 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1885 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1886 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1887 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1888 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1889
1890
Benjamin Petersone41251e2008-04-25 01:59:09 +00001891 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00001892
Benjamin Petersone41251e2008-04-25 01:59:09 +00001893 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001894
1895
Benjamin Petersone41251e2008-04-25 01:59:09 +00001896 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00001897
Benjamin Petersone41251e2008-04-25 01:59:09 +00001898 Outputs the record to the file, catering for rollover as described
1899 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00001900
Vinay Sajipd31f3632010-06-29 15:31:15 +00001901.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001902
1903TimedRotatingFileHandler
1904^^^^^^^^^^^^^^^^^^^^^^^^
1905
1906The :class:`TimedRotatingFileHandler` class, located in the
1907:mod:`logging.handlers` module, supports rotation of disk log files at certain
1908timed intervals.
1909
1910
Vinay Sajipd31f3632010-06-29 15:31:15 +00001911.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001912
1913 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1914 specified file is opened and used as the stream for logging. On rotating it also
1915 sets the filename suffix. Rotating happens based on the product of *when* and
1916 *interval*.
1917
1918 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00001919 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00001920
Christian Heimesb558a2e2008-03-02 22:46:37 +00001921 +----------------+-----------------------+
1922 | Value | Type of interval |
1923 +================+=======================+
1924 | ``'S'`` | Seconds |
1925 +----------------+-----------------------+
1926 | ``'M'`` | Minutes |
1927 +----------------+-----------------------+
1928 | ``'H'`` | Hours |
1929 +----------------+-----------------------+
1930 | ``'D'`` | Days |
1931 +----------------+-----------------------+
1932 | ``'W'`` | Week day (0=Monday) |
1933 +----------------+-----------------------+
1934 | ``'midnight'`` | Roll over at midnight |
1935 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001936
Christian Heimesb558a2e2008-03-02 22:46:37 +00001937 The system will save old log files by appending extensions to the filename.
1938 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001939 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00001940 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00001941
1942 When computing the next rollover time for the first time (when the handler
1943 is created), the last modification time of an existing log file, or else
1944 the current time, is used to compute when the next rotation will occur.
1945
Georg Brandl0c77a822008-06-10 16:37:50 +00001946 If the *utc* argument is true, times in UTC will be used; otherwise
1947 local time is used.
1948
1949 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001950 will be kept, and if more would be created when rollover occurs, the oldest
1951 one is deleted. The deletion logic uses the interval to determine which
1952 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00001953
Vinay Sajipd31f3632010-06-29 15:31:15 +00001954 If *delay* is true, then file opening is deferred until the first call to
1955 :meth:`emit`.
1956
Georg Brandl116aa622007-08-15 14:28:22 +00001957
Benjamin Petersone41251e2008-04-25 01:59:09 +00001958 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00001959
Benjamin Petersone41251e2008-04-25 01:59:09 +00001960 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001961
1962
Benjamin Petersone41251e2008-04-25 01:59:09 +00001963 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00001964
Benjamin Petersone41251e2008-04-25 01:59:09 +00001965 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001966
1967
Vinay Sajipd31f3632010-06-29 15:31:15 +00001968.. _socket-handler:
1969
Georg Brandl116aa622007-08-15 14:28:22 +00001970SocketHandler
1971^^^^^^^^^^^^^
1972
1973The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
1974sends logging output to a network socket. The base class uses a TCP socket.
1975
1976
1977.. class:: SocketHandler(host, port)
1978
1979 Returns a new instance of the :class:`SocketHandler` class intended to
1980 communicate with a remote machine whose address is given by *host* and *port*.
1981
1982
Benjamin Petersone41251e2008-04-25 01:59:09 +00001983 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00001984
Benjamin Petersone41251e2008-04-25 01:59:09 +00001985 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00001986
1987
Benjamin Petersone41251e2008-04-25 01:59:09 +00001988 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00001989
Benjamin Petersone41251e2008-04-25 01:59:09 +00001990 Pickles the record's attribute dictionary and writes it to the socket in
1991 binary format. If there is an error with the socket, silently drops the
1992 packet. If the connection was previously lost, re-establishes the
1993 connection. To unpickle the record at the receiving end into a
1994 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00001995
1996
Benjamin Petersone41251e2008-04-25 01:59:09 +00001997 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00001998
Benjamin Petersone41251e2008-04-25 01:59:09 +00001999 Handles an error which has occurred during :meth:`emit`. The most likely
2000 cause is a lost connection. Closes the socket so that we can retry on the
2001 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002002
2003
Benjamin Petersone41251e2008-04-25 01:59:09 +00002004 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002005
Benjamin Petersone41251e2008-04-25 01:59:09 +00002006 This is a factory method which allows subclasses to define the precise
2007 type of socket they want. The default implementation creates a TCP socket
2008 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002009
2010
Benjamin Petersone41251e2008-04-25 01:59:09 +00002011 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002012
Benjamin Petersone41251e2008-04-25 01:59:09 +00002013 Pickles the record's attribute dictionary in binary format with a length
2014 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002015
Vinay Sajipd31f3632010-06-29 15:31:15 +00002016 Note that pickles aren't completely secure. If you are concerned about
2017 security, you may want to override this method to implement a more secure
2018 mechanism. For example, you can sign pickles using HMAC and then verify
2019 them on the receiving end, or alternatively you can disable unpickling of
2020 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002021
Benjamin Petersone41251e2008-04-25 01:59:09 +00002022 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002023
Benjamin Petersone41251e2008-04-25 01:59:09 +00002024 Send a pickled string *packet* to the socket. This function allows for
2025 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002026
2027
Vinay Sajipd31f3632010-06-29 15:31:15 +00002028.. _datagram-handler:
2029
Georg Brandl116aa622007-08-15 14:28:22 +00002030DatagramHandler
2031^^^^^^^^^^^^^^^
2032
2033The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2034module, inherits from :class:`SocketHandler` to support sending logging messages
2035over UDP sockets.
2036
2037
2038.. class:: DatagramHandler(host, port)
2039
2040 Returns a new instance of the :class:`DatagramHandler` class intended to
2041 communicate with a remote machine whose address is given by *host* and *port*.
2042
2043
Benjamin Petersone41251e2008-04-25 01:59:09 +00002044 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002045
Benjamin Petersone41251e2008-04-25 01:59:09 +00002046 Pickles the record's attribute dictionary and writes it to the socket in
2047 binary format. If there is an error with the socket, silently drops the
2048 packet. To unpickle the record at the receiving end into a
2049 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002050
2051
Benjamin Petersone41251e2008-04-25 01:59:09 +00002052 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002053
Benjamin Petersone41251e2008-04-25 01:59:09 +00002054 The factory method of :class:`SocketHandler` is here overridden to create
2055 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002056
2057
Benjamin Petersone41251e2008-04-25 01:59:09 +00002058 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002059
Benjamin Petersone41251e2008-04-25 01:59:09 +00002060 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002061
2062
Vinay Sajipd31f3632010-06-29 15:31:15 +00002063.. _syslog-handler:
2064
Georg Brandl116aa622007-08-15 14:28:22 +00002065SysLogHandler
2066^^^^^^^^^^^^^
2067
2068The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2069supports sending logging messages to a remote or local Unix syslog.
2070
2071
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002072.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002073
2074 Returns a new instance of the :class:`SysLogHandler` class intended to
2075 communicate with a remote Unix machine whose address is given by *address* in
2076 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002077 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002078 alternative to providing a ``(host, port)`` tuple is providing an address as a
2079 string, for example "/dev/log". In this case, a Unix domain socket is used to
2080 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002081 :const:`LOG_USER` is used. The type of socket opened depends on the
2082 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2083 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2084 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2085
2086 .. versionchanged:: 3.2
2087 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002088
2089
Benjamin Petersone41251e2008-04-25 01:59:09 +00002090 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002091
Benjamin Petersone41251e2008-04-25 01:59:09 +00002092 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002093
2094
Benjamin Petersone41251e2008-04-25 01:59:09 +00002095 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002096
Benjamin Petersone41251e2008-04-25 01:59:09 +00002097 The record is formatted, and then sent to the syslog server. If exception
2098 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002099
2100
Benjamin Petersone41251e2008-04-25 01:59:09 +00002101 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002102
Benjamin Petersone41251e2008-04-25 01:59:09 +00002103 Encodes the facility and priority into an integer. You can pass in strings
2104 or integers - if strings are passed, internal mapping dictionaries are
2105 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002106
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002107 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2108 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002109
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002110 **Priorities**
2111
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002112 +--------------------------+---------------+
2113 | Name (string) | Symbolic value|
2114 +==========================+===============+
2115 | ``alert`` | LOG_ALERT |
2116 +--------------------------+---------------+
2117 | ``crit`` or ``critical`` | LOG_CRIT |
2118 +--------------------------+---------------+
2119 | ``debug`` | LOG_DEBUG |
2120 +--------------------------+---------------+
2121 | ``emerg`` or ``panic`` | LOG_EMERG |
2122 +--------------------------+---------------+
2123 | ``err`` or ``error`` | LOG_ERR |
2124 +--------------------------+---------------+
2125 | ``info`` | LOG_INFO |
2126 +--------------------------+---------------+
2127 | ``notice`` | LOG_NOTICE |
2128 +--------------------------+---------------+
2129 | ``warn`` or ``warning`` | LOG_WARNING |
2130 +--------------------------+---------------+
2131
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002132 **Facilities**
2133
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002134 +---------------+---------------+
2135 | Name (string) | Symbolic value|
2136 +===============+===============+
2137 | ``auth`` | LOG_AUTH |
2138 +---------------+---------------+
2139 | ``authpriv`` | LOG_AUTHPRIV |
2140 +---------------+---------------+
2141 | ``cron`` | LOG_CRON |
2142 +---------------+---------------+
2143 | ``daemon`` | LOG_DAEMON |
2144 +---------------+---------------+
2145 | ``ftp`` | LOG_FTP |
2146 +---------------+---------------+
2147 | ``kern`` | LOG_KERN |
2148 +---------------+---------------+
2149 | ``lpr`` | LOG_LPR |
2150 +---------------+---------------+
2151 | ``mail`` | LOG_MAIL |
2152 +---------------+---------------+
2153 | ``news`` | LOG_NEWS |
2154 +---------------+---------------+
2155 | ``syslog`` | LOG_SYSLOG |
2156 +---------------+---------------+
2157 | ``user`` | LOG_USER |
2158 +---------------+---------------+
2159 | ``uucp`` | LOG_UUCP |
2160 +---------------+---------------+
2161 | ``local0`` | LOG_LOCAL0 |
2162 +---------------+---------------+
2163 | ``local1`` | LOG_LOCAL1 |
2164 +---------------+---------------+
2165 | ``local2`` | LOG_LOCAL2 |
2166 +---------------+---------------+
2167 | ``local3`` | LOG_LOCAL3 |
2168 +---------------+---------------+
2169 | ``local4`` | LOG_LOCAL4 |
2170 +---------------+---------------+
2171 | ``local5`` | LOG_LOCAL5 |
2172 +---------------+---------------+
2173 | ``local6`` | LOG_LOCAL6 |
2174 +---------------+---------------+
2175 | ``local7`` | LOG_LOCAL7 |
2176 +---------------+---------------+
2177
2178 .. method:: mapPriority(levelname)
2179
2180 Maps a logging level name to a syslog priority name.
2181 You may need to override this if you are using custom levels, or
2182 if the default algorithm is not suitable for your needs. The
2183 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2184 ``CRITICAL`` to the equivalent syslog names, and all other level
2185 names to "warning".
2186
2187.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002188
2189NTEventLogHandler
2190^^^^^^^^^^^^^^^^^
2191
2192The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2193module, supports sending logging messages to a local Windows NT, Windows 2000 or
2194Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2195extensions for Python installed.
2196
2197
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002198.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002199
2200 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2201 used to define the application name as it appears in the event log. An
2202 appropriate registry entry is created using this name. The *dllname* should give
2203 the fully qualified pathname of a .dll or .exe which contains message
2204 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2205 - this is installed with the Win32 extensions and contains some basic
2206 placeholder message definitions. Note that use of these placeholders will make
2207 your event logs big, as the entire message source is held in the log. If you
2208 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2209 contains the message definitions you want to use in the event log). The
2210 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2211 defaults to ``'Application'``.
2212
2213
Benjamin Petersone41251e2008-04-25 01:59:09 +00002214 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002215
Benjamin Petersone41251e2008-04-25 01:59:09 +00002216 At this point, you can remove the application name from the registry as a
2217 source of event log entries. However, if you do this, you will not be able
2218 to see the events as you intended in the Event Log Viewer - it needs to be
2219 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002220 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002221
2222
Benjamin Petersone41251e2008-04-25 01:59:09 +00002223 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002224
Benjamin Petersone41251e2008-04-25 01:59:09 +00002225 Determines the message ID, event category and event type, and then logs
2226 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002227
2228
Benjamin Petersone41251e2008-04-25 01:59:09 +00002229 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002230
Benjamin Petersone41251e2008-04-25 01:59:09 +00002231 Returns the event category for the record. Override this if you want to
2232 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002233
2234
Benjamin Petersone41251e2008-04-25 01:59:09 +00002235 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002236
Benjamin Petersone41251e2008-04-25 01:59:09 +00002237 Returns the event type for the record. Override this if you want to
2238 specify your own types. This version does a mapping using the handler's
2239 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2240 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2241 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2242 your own levels, you will either need to override this method or place a
2243 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002244
2245
Benjamin Petersone41251e2008-04-25 01:59:09 +00002246 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002247
Benjamin Petersone41251e2008-04-25 01:59:09 +00002248 Returns the message ID for the record. If you are using your own messages,
2249 you could do this by having the *msg* passed to the logger being an ID
2250 rather than a format string. Then, in here, you could use a dictionary
2251 lookup to get the message ID. This version returns 1, which is the base
2252 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002253
Vinay Sajipd31f3632010-06-29 15:31:15 +00002254.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002255
2256SMTPHandler
2257^^^^^^^^^^^
2258
2259The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2260supports sending logging messages to an email address via SMTP.
2261
2262
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002263.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002264
2265 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2266 initialized with the from and to addresses and subject line of the email. The
2267 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2268 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2269 the standard SMTP port is used. If your SMTP server requires authentication, you
2270 can specify a (username, password) tuple for the *credentials* argument.
2271
Georg Brandl116aa622007-08-15 14:28:22 +00002272
Benjamin Petersone41251e2008-04-25 01:59:09 +00002273 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002274
Benjamin Petersone41251e2008-04-25 01:59:09 +00002275 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002276
2277
Benjamin Petersone41251e2008-04-25 01:59:09 +00002278 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002279
Benjamin Petersone41251e2008-04-25 01:59:09 +00002280 If you want to specify a subject line which is record-dependent, override
2281 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002282
Vinay Sajipd31f3632010-06-29 15:31:15 +00002283.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002284
2285MemoryHandler
2286^^^^^^^^^^^^^
2287
2288The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2289supports buffering of logging records in memory, periodically flushing them to a
2290:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2291event of a certain severity or greater is seen.
2292
2293:class:`MemoryHandler` is a subclass of the more general
2294:class:`BufferingHandler`, which is an abstract class. This buffers logging
2295records in memory. Whenever each record is added to the buffer, a check is made
2296by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2297should, then :meth:`flush` is expected to do the needful.
2298
2299
2300.. class:: BufferingHandler(capacity)
2301
2302 Initializes the handler with a buffer of the specified capacity.
2303
2304
Benjamin Petersone41251e2008-04-25 01:59:09 +00002305 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002306
Benjamin Petersone41251e2008-04-25 01:59:09 +00002307 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2308 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002309
2310
Benjamin Petersone41251e2008-04-25 01:59:09 +00002311 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002312
Benjamin Petersone41251e2008-04-25 01:59:09 +00002313 You can override this to implement custom flushing behavior. This version
2314 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002315
2316
Benjamin Petersone41251e2008-04-25 01:59:09 +00002317 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002318
Benjamin Petersone41251e2008-04-25 01:59:09 +00002319 Returns true if the buffer is up to capacity. This method can be
2320 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002321
2322
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002323.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002324
2325 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2326 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2327 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2328 set using :meth:`setTarget` before this handler does anything useful.
2329
2330
Benjamin Petersone41251e2008-04-25 01:59:09 +00002331 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002332
Benjamin Petersone41251e2008-04-25 01:59:09 +00002333 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2334 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002335
2336
Benjamin Petersone41251e2008-04-25 01:59:09 +00002337 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002338
Benjamin Petersone41251e2008-04-25 01:59:09 +00002339 For a :class:`MemoryHandler`, flushing means just sending the buffered
2340 records to the target, if there is one. Override if you want different
2341 behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002342
2343
Benjamin Petersone41251e2008-04-25 01:59:09 +00002344 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002345
Benjamin Petersone41251e2008-04-25 01:59:09 +00002346 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002347
2348
Benjamin Petersone41251e2008-04-25 01:59:09 +00002349 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002350
Benjamin Petersone41251e2008-04-25 01:59:09 +00002351 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002352
2353
Vinay Sajipd31f3632010-06-29 15:31:15 +00002354.. _http-handler:
2355
Georg Brandl116aa622007-08-15 14:28:22 +00002356HTTPHandler
2357^^^^^^^^^^^
2358
2359The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2360supports sending logging messages to a Web server, using either ``GET`` or
2361``POST`` semantics.
2362
2363
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002364.. class:: HTTPHandler(host, url, method='GET')
Georg Brandl116aa622007-08-15 14:28:22 +00002365
2366 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2367 initialized with a host address, url and HTTP method. The *host* can be of the
2368 form ``host:port``, should you need to use a specific port number. If no
2369 *method* is specified, ``GET`` is used.
2370
2371
Benjamin Petersone41251e2008-04-25 01:59:09 +00002372 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002373
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002374 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002375
2376
Christian Heimes8b0facf2007-12-04 19:30:01 +00002377.. _formatter-objects:
2378
Georg Brandl116aa622007-08-15 14:28:22 +00002379Formatter Objects
2380-----------------
2381
Benjamin Peterson75edad02009-01-01 15:05:06 +00002382.. currentmodule:: logging
2383
Georg Brandl116aa622007-08-15 14:28:22 +00002384:class:`Formatter`\ s have the following attributes and methods. They are
2385responsible for converting a :class:`LogRecord` to (usually) a string which can
2386be interpreted by either a human or an external system. The base
2387:class:`Formatter` allows a formatting string to be specified. If none is
2388supplied, the default value of ``'%(message)s'`` is used.
2389
2390A Formatter can be initialized with a format string which makes use of knowledge
2391of the :class:`LogRecord` attributes - such as the default value mentioned above
2392making use of the fact that the user's message and arguments are pre-formatted
2393into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002394standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00002395for more information on string formatting.
2396
2397Currently, the useful mapping keys in a :class:`LogRecord` are:
2398
2399+-------------------------+-----------------------------------------------+
2400| Format | Description |
2401+=========================+===============================================+
2402| ``%(name)s`` | Name of the logger (logging channel). |
2403+-------------------------+-----------------------------------------------+
2404| ``%(levelno)s`` | Numeric logging level for the message |
2405| | (:const:`DEBUG`, :const:`INFO`, |
2406| | :const:`WARNING`, :const:`ERROR`, |
2407| | :const:`CRITICAL`). |
2408+-------------------------+-----------------------------------------------+
2409| ``%(levelname)s`` | Text logging level for the message |
2410| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2411| | ``'ERROR'``, ``'CRITICAL'``). |
2412+-------------------------+-----------------------------------------------+
2413| ``%(pathname)s`` | Full pathname of the source file where the |
2414| | logging call was issued (if available). |
2415+-------------------------+-----------------------------------------------+
2416| ``%(filename)s`` | Filename portion of pathname. |
2417+-------------------------+-----------------------------------------------+
2418| ``%(module)s`` | Module (name portion of filename). |
2419+-------------------------+-----------------------------------------------+
2420| ``%(funcName)s`` | Name of function containing the logging call. |
2421+-------------------------+-----------------------------------------------+
2422| ``%(lineno)d`` | Source line number where the logging call was |
2423| | issued (if available). |
2424+-------------------------+-----------------------------------------------+
2425| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2426| | (as returned by :func:`time.time`). |
2427+-------------------------+-----------------------------------------------+
2428| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2429| | created, relative to the time the logging |
2430| | module was loaded. |
2431+-------------------------+-----------------------------------------------+
2432| ``%(asctime)s`` | Human-readable time when the |
2433| | :class:`LogRecord` was created. By default |
2434| | this is of the form "2003-07-08 16:49:45,896" |
2435| | (the numbers after the comma are millisecond |
2436| | portion of the time). |
2437+-------------------------+-----------------------------------------------+
2438| ``%(msecs)d`` | Millisecond portion of the time when the |
2439| | :class:`LogRecord` was created. |
2440+-------------------------+-----------------------------------------------+
2441| ``%(thread)d`` | Thread ID (if available). |
2442+-------------------------+-----------------------------------------------+
2443| ``%(threadName)s`` | Thread name (if available). |
2444+-------------------------+-----------------------------------------------+
2445| ``%(process)d`` | Process ID (if available). |
2446+-------------------------+-----------------------------------------------+
2447| ``%(message)s`` | The logged message, computed as ``msg % |
2448| | args``. |
2449+-------------------------+-----------------------------------------------+
2450
Georg Brandl116aa622007-08-15 14:28:22 +00002451
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002452.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002453
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002454 Returns a new instance of the :class:`Formatter` class. The instance is
2455 initialized with a format string for the message as a whole, as well as a
2456 format string for the date/time portion of a message. If no *fmt* is
2457 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
2458 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00002459
2460
Benjamin Petersone41251e2008-04-25 01:59:09 +00002461 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002462
Benjamin Petersone41251e2008-04-25 01:59:09 +00002463 The record's attribute dictionary is used as the operand to a string
2464 formatting operation. Returns the resulting string. Before formatting the
2465 dictionary, a couple of preparatory steps are carried out. The *message*
2466 attribute of the record is computed using *msg* % *args*. If the
2467 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2468 to format the event time. If there is exception information, it is
2469 formatted using :meth:`formatException` and appended to the message. Note
2470 that the formatted exception information is cached in attribute
2471 *exc_text*. This is useful because the exception information can be
2472 pickled and sent across the wire, but you should be careful if you have
2473 more than one :class:`Formatter` subclass which customizes the formatting
2474 of exception information. In this case, you will have to clear the cached
2475 value after a formatter has done its formatting, so that the next
2476 formatter to handle the event doesn't use the cached value but
2477 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00002478
2479
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002480 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002481
Benjamin Petersone41251e2008-04-25 01:59:09 +00002482 This method should be called from :meth:`format` by a formatter which
2483 wants to make use of a formatted time. This method can be overridden in
2484 formatters to provide for any specific requirement, but the basic behavior
2485 is as follows: if *datefmt* (a string) is specified, it is used with
2486 :func:`time.strftime` to format the creation time of the
2487 record. Otherwise, the ISO8601 format is used. The resulting string is
2488 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00002489
2490
Benjamin Petersone41251e2008-04-25 01:59:09 +00002491 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00002492
Benjamin Petersone41251e2008-04-25 01:59:09 +00002493 Formats the specified exception information (a standard exception tuple as
2494 returned by :func:`sys.exc_info`) as a string. This default implementation
2495 just uses :func:`traceback.print_exception`. The resulting string is
2496 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00002497
Vinay Sajipd31f3632010-06-29 15:31:15 +00002498.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00002499
2500Filter Objects
2501--------------
2502
2503:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
2504more sophisticated filtering than is provided by levels. The base filter class
2505only allows events which are below a certain point in the logger hierarchy. For
2506example, a filter initialized with "A.B" will allow events logged by loggers
2507"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2508initialized with the empty string, all events are passed.
2509
2510
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002511.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00002512
2513 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2514 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002515 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00002516
2517
Benjamin Petersone41251e2008-04-25 01:59:09 +00002518 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002519
Benjamin Petersone41251e2008-04-25 01:59:09 +00002520 Is the specified record to be logged? Returns zero for no, nonzero for
2521 yes. If deemed appropriate, the record may be modified in-place by this
2522 method.
Georg Brandl116aa622007-08-15 14:28:22 +00002523
Vinay Sajipd31f3632010-06-29 15:31:15 +00002524.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00002525
2526LogRecord Objects
2527-----------------
2528
2529:class:`LogRecord` instances are created every time something is logged. They
2530contain all the information pertinent to the event being logged. The main
2531information passed in is in msg and args, which are combined using msg % args to
2532create the message field of the record. The record also includes information
2533such as when the record was created, the source line where the logging call was
2534made, and any exception information to be logged.
2535
2536
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002537.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002538
2539 Returns an instance of :class:`LogRecord` initialized with interesting
2540 information. The *name* is the logger name; *lvl* is the numeric level;
2541 *pathname* is the absolute pathname of the source file in which the logging
2542 call was made; *lineno* is the line number in that file where the logging
2543 call is found; *msg* is the user-supplied message (a format string); *args*
2544 is the tuple which, together with *msg*, makes up the user message; and
2545 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2546 (or :const:`None`, if no exception information is available). The *func* is
2547 the name of the function from which the logging call was made. If not
2548 specified, it defaults to ``None``.
2549
Georg Brandl116aa622007-08-15 14:28:22 +00002550
Benjamin Petersone41251e2008-04-25 01:59:09 +00002551 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00002552
Benjamin Petersone41251e2008-04-25 01:59:09 +00002553 Returns the message for this :class:`LogRecord` instance after merging any
2554 user-supplied arguments with the message.
2555
Vinay Sajipd31f3632010-06-29 15:31:15 +00002556.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00002557
Christian Heimes04c420f2008-01-18 18:40:46 +00002558LoggerAdapter Objects
2559---------------------
2560
Christian Heimes04c420f2008-01-18 18:40:46 +00002561:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00002562information into logging calls. For a usage example , see the section on
2563`adding contextual information to your logging output`__.
2564
2565__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00002566
2567.. class:: LoggerAdapter(logger, extra)
2568
2569 Returns an instance of :class:`LoggerAdapter` initialized with an
2570 underlying :class:`Logger` instance and a dict-like object.
2571
Benjamin Petersone41251e2008-04-25 01:59:09 +00002572 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00002573
Benjamin Petersone41251e2008-04-25 01:59:09 +00002574 Modifies the message and/or keyword arguments passed to a logging call in
2575 order to insert contextual information. This implementation takes the object
2576 passed as *extra* to the constructor and adds it to *kwargs* using key
2577 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2578 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00002579
2580In addition to the above, :class:`LoggerAdapter` supports all the logging
2581methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2582:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2583methods have the same signatures as their counterparts in :class:`Logger`, so
2584you can use the two types of instances interchangeably.
2585
Ezio Melotti4d5195b2010-04-20 10:57:44 +00002586.. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00002587 The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This
2588 method delegates to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002589
Georg Brandl116aa622007-08-15 14:28:22 +00002590
2591Thread Safety
2592-------------
2593
2594The logging module is intended to be thread-safe without any special work
2595needing to be done by its clients. It achieves this though using threading
2596locks; there is one lock to serialize access to the module's shared data, and
2597each handler also creates a lock to serialize access to its underlying I/O.
2598
Benjamin Petersond23f8222009-04-05 19:13:16 +00002599If you are implementing asynchronous signal handlers using the :mod:`signal`
2600module, you may not be able to use logging from within such handlers. This is
2601because lock implementations in the :mod:`threading` module are not always
2602re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00002603
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002604
2605Integration with the warnings module
2606------------------------------------
2607
2608The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2609with the :mod:`warnings` module.
2610
2611.. function:: captureWarnings(capture)
2612
2613 This function is used to turn the capture of warnings by logging on and
2614 off.
2615
2616 If `capture` is `True`, warnings issued by the :mod:`warnings` module
2617 will be redirected to the logging system. Specifically, a warning will be
2618 formatted using :func:`warnings.formatwarning` and the resulting string
2619 logged to a logger named "py.warnings" with a severity of `WARNING`.
2620
2621 If `capture` is `False`, the redirection of warnings to the logging system
2622 will stop, and warnings will be redirected to their original destinations
2623 (i.e. those in effect before `captureWarnings(True)` was called).
2624
2625
Georg Brandl116aa622007-08-15 14:28:22 +00002626Configuration
2627-------------
2628
2629
2630.. _logging-config-api:
2631
2632Configuration functions
2633^^^^^^^^^^^^^^^^^^^^^^^
2634
Georg Brandl116aa622007-08-15 14:28:22 +00002635The following functions configure the logging module. They are located in the
2636:mod:`logging.config` module. Their use is optional --- you can configure the
2637logging module using these functions or by making calls to the main API (defined
2638in :mod:`logging` itself) and defining handlers which are declared either in
2639:mod:`logging` or :mod:`logging.handlers`.
2640
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002641.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00002642
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002643 Takes the logging configuration from a dictionary. The contents of
2644 this dictionary are described in :ref:`logging-config-dictschema`
2645 below.
2646
2647 If an error is encountered during configuration, this function will
2648 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2649 or :exc:`ImportError` with a suitably descriptive message. The
2650 following is a (possibly incomplete) list of conditions which will
2651 raise an error:
2652
2653 * A ``level`` which is not a string or which is a string not
2654 corresponding to an actual logging level.
2655 * A ``propagate`` value which is not a boolean.
2656 * An id which does not have a corresponding destination.
2657 * A non-existent handler id found during an incremental call.
2658 * An invalid logger name.
2659 * Inability to resolve to an internal or external object.
2660
2661 Parsing is performed by the :class:`DictConfigurator` class, whose
2662 constructor is passed the dictionary used for configuration, and
2663 has a :meth:`configure` method. The :mod:`logging.config` module
2664 has a callable attribute :attr:`dictConfigClass`
2665 which is initially set to :class:`DictConfigurator`.
2666 You can replace the value of :attr:`dictConfigClass` with a
2667 suitable implementation of your own.
2668
2669 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2670 the specified dictionary, and then calls the :meth:`configure` method on
2671 the returned object to put the configuration into effect::
2672
2673 def dictConfig(config):
2674 dictConfigClass(config).configure()
2675
2676 For example, a subclass of :class:`DictConfigurator` could call
2677 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2678 set up custom prefixes which would be usable in the subsequent
2679 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2680 this new subclass, and then :func:`dictConfig` could be called exactly as
2681 in the default, uncustomized state.
2682
2683.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00002684
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00002685 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002686 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002687 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00002688 configurations (if the developer provides a mechanism to present the choices
2689 and load the chosen configuration). Defaults to be passed to the ConfigParser
2690 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00002691
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002692
2693.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00002694
2695 Starts up a socket server on the specified port, and listens for new
2696 configurations. If no port is specified, the module's default
2697 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2698 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2699 :class:`Thread` instance on which you can call :meth:`start` to start the
2700 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00002701 call :func:`stopListening`.
2702
2703 To send a configuration to the socket, read in the configuration file and
2704 send it to the socket as a string of bytes preceded by a four-byte length
2705 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002706
2707
2708.. function:: stopListening()
2709
Christian Heimes8b0facf2007-12-04 19:30:01 +00002710 Stops the listening server which was created with a call to :func:`listen`.
2711 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00002712 :func:`listen`.
2713
2714
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002715.. _logging-config-dictschema:
2716
2717Configuration dictionary schema
2718^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2719
2720Describing a logging configuration requires listing the various
2721objects to create and the connections between them; for example, you
2722may create a handler named "console" and then say that the logger
2723named "startup" will send its messages to the "console" handler.
2724These objects aren't limited to those provided by the :mod:`logging`
2725module because you might write your own formatter or handler class.
2726The parameters to these classes may also need to include external
2727objects such as ``sys.stderr``. The syntax for describing these
2728objects and connections is defined in :ref:`logging-config-dict-connections`
2729below.
2730
2731Dictionary Schema Details
2732"""""""""""""""""""""""""
2733
2734The dictionary passed to :func:`dictConfig` must contain the following
2735keys:
2736
2737* `version` - to be set to an integer value representing the schema
2738 version. The only valid value at present is 1, but having this key
2739 allows the schema to evolve while still preserving backwards
2740 compatibility.
2741
2742All other keys are optional, but if present they will be interpreted
2743as described below. In all cases below where a 'configuring dict' is
2744mentioned, it will be checked for the special ``'()'`` key to see if a
2745custom instantiation is required. If so, the mechanism described in
2746:ref:`logging-config-dict-userdef` below is used to create an instance;
2747otherwise, the context is used to determine what to instantiate.
2748
2749* `formatters` - the corresponding value will be a dict in which each
2750 key is a formatter id and each value is a dict describing how to
2751 configure the corresponding Formatter instance.
2752
2753 The configuring dict is searched for keys ``format`` and ``datefmt``
2754 (with defaults of ``None``) and these are used to construct a
2755 :class:`logging.Formatter` instance.
2756
2757* `filters` - the corresponding value will be a dict in which each key
2758 is a filter id and each value is a dict describing how to configure
2759 the corresponding Filter instance.
2760
2761 The configuring dict is searched for the key ``name`` (defaulting to the
2762 empty string) and this is used to construct a :class:`logging.Filter`
2763 instance.
2764
2765* `handlers` - the corresponding value will be a dict in which each
2766 key is a handler id and each value is a dict describing how to
2767 configure the corresponding Handler instance.
2768
2769 The configuring dict is searched for the following keys:
2770
2771 * ``class`` (mandatory). This is the fully qualified name of the
2772 handler class.
2773
2774 * ``level`` (optional). The level of the handler.
2775
2776 * ``formatter`` (optional). The id of the formatter for this
2777 handler.
2778
2779 * ``filters`` (optional). A list of ids of the filters for this
2780 handler.
2781
2782 All *other* keys are passed through as keyword arguments to the
2783 handler's constructor. For example, given the snippet::
2784
2785 handlers:
2786 console:
2787 class : logging.StreamHandler
2788 formatter: brief
2789 level : INFO
2790 filters: [allow_foo]
2791 stream : ext://sys.stdout
2792 file:
2793 class : logging.handlers.RotatingFileHandler
2794 formatter: precise
2795 filename: logconfig.log
2796 maxBytes: 1024
2797 backupCount: 3
2798
2799 the handler with id ``console`` is instantiated as a
2800 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
2801 stream. The handler with id ``file`` is instantiated as a
2802 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
2803 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
2804
2805* `loggers` - the corresponding value will be a dict in which each key
2806 is a logger name and each value is a dict describing how to
2807 configure the corresponding Logger instance.
2808
2809 The configuring dict is searched for the following keys:
2810
2811 * ``level`` (optional). The level of the logger.
2812
2813 * ``propagate`` (optional). The propagation setting of the logger.
2814
2815 * ``filters`` (optional). A list of ids of the filters for this
2816 logger.
2817
2818 * ``handlers`` (optional). A list of ids of the handlers for this
2819 logger.
2820
2821 The specified loggers will be configured according to the level,
2822 propagation, filters and handlers specified.
2823
2824* `root` - this will be the configuration for the root logger.
2825 Processing of the configuration will be as for any logger, except
2826 that the ``propagate`` setting will not be applicable.
2827
2828* `incremental` - whether the configuration is to be interpreted as
2829 incremental to the existing configuration. This value defaults to
2830 ``False``, which means that the specified configuration replaces the
2831 existing configuration with the same semantics as used by the
2832 existing :func:`fileConfig` API.
2833
2834 If the specified value is ``True``, the configuration is processed
2835 as described in the section on :ref:`logging-config-dict-incremental`.
2836
2837* `disable_existing_loggers` - whether any existing loggers are to be
2838 disabled. This setting mirrors the parameter of the same name in
2839 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
2840 This value is ignored if `incremental` is ``True``.
2841
2842.. _logging-config-dict-incremental:
2843
2844Incremental Configuration
2845"""""""""""""""""""""""""
2846
2847It is difficult to provide complete flexibility for incremental
2848configuration. For example, because objects such as filters
2849and formatters are anonymous, once a configuration is set up, it is
2850not possible to refer to such anonymous objects when augmenting a
2851configuration.
2852
2853Furthermore, there is not a compelling case for arbitrarily altering
2854the object graph of loggers, handlers, filters, formatters at
2855run-time, once a configuration is set up; the verbosity of loggers and
2856handlers can be controlled just by setting levels (and, in the case of
2857loggers, propagation flags). Changing the object graph arbitrarily in
2858a safe way is problematic in a multi-threaded environment; while not
2859impossible, the benefits are not worth the complexity it adds to the
2860implementation.
2861
2862Thus, when the ``incremental`` key of a configuration dict is present
2863and is ``True``, the system will completely ignore any ``formatters`` and
2864``filters`` entries, and process only the ``level``
2865settings in the ``handlers`` entries, and the ``level`` and
2866``propagate`` settings in the ``loggers`` and ``root`` entries.
2867
2868Using a value in the configuration dict lets configurations to be sent
2869over the wire as pickled dicts to a socket listener. Thus, the logging
2870verbosity of a long-running application can be altered over time with
2871no need to stop and restart the application.
2872
2873.. _logging-config-dict-connections:
2874
2875Object connections
2876""""""""""""""""""
2877
2878The schema describes a set of logging objects - loggers,
2879handlers, formatters, filters - which are connected to each other in
2880an object graph. Thus, the schema needs to represent connections
2881between the objects. For example, say that, once configured, a
2882particular logger has attached to it a particular handler. For the
2883purposes of this discussion, we can say that the logger represents the
2884source, and the handler the destination, of a connection between the
2885two. Of course in the configured objects this is represented by the
2886logger holding a reference to the handler. In the configuration dict,
2887this is done by giving each destination object an id which identifies
2888it unambiguously, and then using the id in the source object's
2889configuration to indicate that a connection exists between the source
2890and the destination object with that id.
2891
2892So, for example, consider the following YAML snippet::
2893
2894 formatters:
2895 brief:
2896 # configuration for formatter with id 'brief' goes here
2897 precise:
2898 # configuration for formatter with id 'precise' goes here
2899 handlers:
2900 h1: #This is an id
2901 # configuration of handler with id 'h1' goes here
2902 formatter: brief
2903 h2: #This is another id
2904 # configuration of handler with id 'h2' goes here
2905 formatter: precise
2906 loggers:
2907 foo.bar.baz:
2908 # other configuration for logger 'foo.bar.baz'
2909 handlers: [h1, h2]
2910
2911(Note: YAML used here because it's a little more readable than the
2912equivalent Python source form for the dictionary.)
2913
2914The ids for loggers are the logger names which would be used
2915programmatically to obtain a reference to those loggers, e.g.
2916``foo.bar.baz``. The ids for Formatters and Filters can be any string
2917value (such as ``brief``, ``precise`` above) and they are transient,
2918in that they are only meaningful for processing the configuration
2919dictionary and used to determine connections between objects, and are
2920not persisted anywhere when the configuration call is complete.
2921
2922The above snippet indicates that logger named ``foo.bar.baz`` should
2923have two handlers attached to it, which are described by the handler
2924ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
2925``brief``, and the formatter for ``h2`` is that described by id
2926``precise``.
2927
2928
2929.. _logging-config-dict-userdef:
2930
2931User-defined objects
2932""""""""""""""""""""
2933
2934The schema supports user-defined objects for handlers, filters and
2935formatters. (Loggers do not need to have different types for
2936different instances, so there is no support in this configuration
2937schema for user-defined logger classes.)
2938
2939Objects to be configured are described by dictionaries
2940which detail their configuration. In some places, the logging system
2941will be able to infer from the context how an object is to be
2942instantiated, but when a user-defined object is to be instantiated,
2943the system will not know how to do this. In order to provide complete
2944flexibility for user-defined object instantiation, the user needs
2945to provide a 'factory' - a callable which is called with a
2946configuration dictionary and which returns the instantiated object.
2947This is signalled by an absolute import path to the factory being
2948made available under the special key ``'()'``. Here's a concrete
2949example::
2950
2951 formatters:
2952 brief:
2953 format: '%(message)s'
2954 default:
2955 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
2956 datefmt: '%Y-%m-%d %H:%M:%S'
2957 custom:
2958 (): my.package.customFormatterFactory
2959 bar: baz
2960 spam: 99.9
2961 answer: 42
2962
2963The above YAML snippet defines three formatters. The first, with id
2964``brief``, is a standard :class:`logging.Formatter` instance with the
2965specified format string. The second, with id ``default``, has a
2966longer format and also defines the time format explicitly, and will
2967result in a :class:`logging.Formatter` initialized with those two format
2968strings. Shown in Python source form, the ``brief`` and ``default``
2969formatters have configuration sub-dictionaries::
2970
2971 {
2972 'format' : '%(message)s'
2973 }
2974
2975and::
2976
2977 {
2978 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
2979 'datefmt' : '%Y-%m-%d %H:%M:%S'
2980 }
2981
2982respectively, and as these dictionaries do not contain the special key
2983``'()'``, the instantiation is inferred from the context: as a result,
2984standard :class:`logging.Formatter` instances are created. The
2985configuration sub-dictionary for the third formatter, with id
2986``custom``, is::
2987
2988 {
2989 '()' : 'my.package.customFormatterFactory',
2990 'bar' : 'baz',
2991 'spam' : 99.9,
2992 'answer' : 42
2993 }
2994
2995and this contains the special key ``'()'``, which means that
2996user-defined instantiation is wanted. In this case, the specified
2997factory callable will be used. If it is an actual callable it will be
2998used directly - otherwise, if you specify a string (as in the example)
2999the actual callable will be located using normal import mechanisms.
3000The callable will be called with the **remaining** items in the
3001configuration sub-dictionary as keyword arguments. In the above
3002example, the formatter with id ``custom`` will be assumed to be
3003returned by the call::
3004
3005 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3006
3007The key ``'()'`` has been used as the special key because it is not a
3008valid keyword parameter name, and so will not clash with the names of
3009the keyword arguments used in the call. The ``'()'`` also serves as a
3010mnemonic that the corresponding value is a callable.
3011
3012
3013.. _logging-config-dict-externalobj:
3014
3015Access to external objects
3016""""""""""""""""""""""""""
3017
3018There are times where a configuration needs to refer to objects
3019external to the configuration, for example ``sys.stderr``. If the
3020configuration dict is constructed using Python code, this is
3021straightforward, but a problem arises when the configuration is
3022provided via a text file (e.g. JSON, YAML). In a text file, there is
3023no standard way to distinguish ``sys.stderr`` from the literal string
3024``'sys.stderr'``. To facilitate this distinction, the configuration
3025system looks for certain special prefixes in string values and
3026treat them specially. For example, if the literal string
3027``'ext://sys.stderr'`` is provided as a value in the configuration,
3028then the ``ext://`` will be stripped off and the remainder of the
3029value processed using normal import mechanisms.
3030
3031The handling of such prefixes is done in a way analogous to protocol
3032handling: there is a generic mechanism to look for prefixes which
3033match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3034whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3035in a prefix-dependent manner and the result of the processing replaces
3036the string value. If the prefix is not recognised, then the string
3037value will be left as-is.
3038
3039
3040.. _logging-config-dict-internalobj:
3041
3042Access to internal objects
3043""""""""""""""""""""""""""
3044
3045As well as external objects, there is sometimes also a need to refer
3046to objects in the configuration. This will be done implicitly by the
3047configuration system for things that it knows about. For example, the
3048string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3049automatically be converted to the value ``logging.DEBUG``, and the
3050``handlers``, ``filters`` and ``formatter`` entries will take an
3051object id and resolve to the appropriate destination object.
3052
3053However, a more generic mechanism is needed for user-defined
3054objects which are not known to the :mod:`logging` module. For
3055example, consider :class:`logging.handlers.MemoryHandler`, which takes
3056a ``target`` argument which is another handler to delegate to. Since
3057the system already knows about this class, then in the configuration,
3058the given ``target`` just needs to be the object id of the relevant
3059target handler, and the system will resolve to the handler from the
3060id. If, however, a user defines a ``my.package.MyHandler`` which has
3061an ``alternate`` handler, the configuration system would not know that
3062the ``alternate`` referred to a handler. To cater for this, a generic
3063resolution system allows the user to specify::
3064
3065 handlers:
3066 file:
3067 # configuration of file handler goes here
3068
3069 custom:
3070 (): my.package.MyHandler
3071 alternate: cfg://handlers.file
3072
3073The literal string ``'cfg://handlers.file'`` will be resolved in an
3074analogous way to strings with the ``ext://`` prefix, but looking
3075in the configuration itself rather than the import namespace. The
3076mechanism allows access by dot or by index, in a similar way to
3077that provided by ``str.format``. Thus, given the following snippet::
3078
3079 handlers:
3080 email:
3081 class: logging.handlers.SMTPHandler
3082 mailhost: localhost
3083 fromaddr: my_app@domain.tld
3084 toaddrs:
3085 - support_team@domain.tld
3086 - dev_team@domain.tld
3087 subject: Houston, we have a problem.
3088
3089in the configuration, the string ``'cfg://handlers'`` would resolve to
3090the dict with key ``handlers``, the string ``'cfg://handlers.email``
3091would resolve to the dict with key ``email`` in the ``handlers`` dict,
3092and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3093resolve to ``'dev_team.domain.tld'`` and the string
3094``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3095``'support_team@domain.tld'``. The ``subject`` value could be accessed
3096using either ``'cfg://handlers.email.subject'`` or, equivalently,
3097``'cfg://handlers.email[subject]'``. The latter form only needs to be
3098used if the key contains spaces or non-alphanumeric characters. If an
3099index value consists only of decimal digits, access will be attempted
3100using the corresponding integer value, falling back to the string
3101value if needed.
3102
3103Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3104resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3105If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3106the system will attempt to retrieve the value from
3107``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3108to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3109fails.
3110
Georg Brandl116aa622007-08-15 14:28:22 +00003111.. _logging-config-fileformat:
3112
3113Configuration file format
3114^^^^^^^^^^^^^^^^^^^^^^^^^
3115
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003116The configuration file format understood by :func:`fileConfig` is based on
3117:mod:`configparser` functionality. The file must contain sections called
3118``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3119entities of each type which are defined in the file. For each such entity, there
3120is a separate section which identifies how that entity is configured. Thus, for
3121a logger named ``log01`` in the ``[loggers]`` section, the relevant
3122configuration details are held in a section ``[logger_log01]``. Similarly, a
3123handler called ``hand01`` in the ``[handlers]`` section will have its
3124configuration held in a section called ``[handler_hand01]``, while a formatter
3125called ``form01`` in the ``[formatters]`` section will have its configuration
3126specified in a section called ``[formatter_form01]``. The root logger
3127configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003128
3129Examples of these sections in the file are given below. ::
3130
3131 [loggers]
3132 keys=root,log02,log03,log04,log05,log06,log07
3133
3134 [handlers]
3135 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3136
3137 [formatters]
3138 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3139
3140The root logger must specify a level and a list of handlers. An example of a
3141root logger section is given below. ::
3142
3143 [logger_root]
3144 level=NOTSET
3145 handlers=hand01
3146
3147The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3148``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3149logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3150package's namespace.
3151
3152The ``handlers`` entry is a comma-separated list of handler names, which must
3153appear in the ``[handlers]`` section. These names must appear in the
3154``[handlers]`` section and have corresponding sections in the configuration
3155file.
3156
3157For loggers other than the root logger, some additional information is required.
3158This is illustrated by the following example. ::
3159
3160 [logger_parser]
3161 level=DEBUG
3162 handlers=hand01
3163 propagate=1
3164 qualname=compiler.parser
3165
3166The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3167except that if a non-root logger's level is specified as ``NOTSET``, the system
3168consults loggers higher up the hierarchy to determine the effective level of the
3169logger. The ``propagate`` entry is set to 1 to indicate that messages must
3170propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3171indicate that messages are **not** propagated to handlers up the hierarchy. The
3172``qualname`` entry is the hierarchical channel name of the logger, that is to
3173say the name used by the application to get the logger.
3174
3175Sections which specify handler configuration are exemplified by the following.
3176::
3177
3178 [handler_hand01]
3179 class=StreamHandler
3180 level=NOTSET
3181 formatter=form01
3182 args=(sys.stdout,)
3183
3184The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3185in the ``logging`` package's namespace). The ``level`` is interpreted as for
3186loggers, and ``NOTSET`` is taken to mean "log everything".
3187
3188The ``formatter`` entry indicates the key name of the formatter for this
3189handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3190If a name is specified, it must appear in the ``[formatters]`` section and have
3191a corresponding section in the configuration file.
3192
3193The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3194package's namespace, is the list of arguments to the constructor for the handler
3195class. Refer to the constructors for the relevant handlers, or to the examples
3196below, to see how typical entries are constructed. ::
3197
3198 [handler_hand02]
3199 class=FileHandler
3200 level=DEBUG
3201 formatter=form02
3202 args=('python.log', 'w')
3203
3204 [handler_hand03]
3205 class=handlers.SocketHandler
3206 level=INFO
3207 formatter=form03
3208 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3209
3210 [handler_hand04]
3211 class=handlers.DatagramHandler
3212 level=WARN
3213 formatter=form04
3214 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3215
3216 [handler_hand05]
3217 class=handlers.SysLogHandler
3218 level=ERROR
3219 formatter=form05
3220 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3221
3222 [handler_hand06]
3223 class=handlers.NTEventLogHandler
3224 level=CRITICAL
3225 formatter=form06
3226 args=('Python Application', '', 'Application')
3227
3228 [handler_hand07]
3229 class=handlers.SMTPHandler
3230 level=WARN
3231 formatter=form07
3232 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3233
3234 [handler_hand08]
3235 class=handlers.MemoryHandler
3236 level=NOTSET
3237 formatter=form08
3238 target=
3239 args=(10, ERROR)
3240
3241 [handler_hand09]
3242 class=handlers.HTTPHandler
3243 level=NOTSET
3244 formatter=form09
3245 args=('localhost:9022', '/log', 'GET')
3246
3247Sections which specify formatter configuration are typified by the following. ::
3248
3249 [formatter_form01]
3250 format=F1 %(asctime)s %(levelname)s %(message)s
3251 datefmt=
3252 class=logging.Formatter
3253
3254The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003255the :func:`strftime`\ -compatible date/time format string. If empty, the
3256package substitutes ISO8601 format date/times, which is almost equivalent to
3257specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3258also specifies milliseconds, which are appended to the result of using the above
3259format string, with a comma separator. An example time in ISO8601 format is
3260``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00003261
3262The ``class`` entry is optional. It indicates the name of the formatter's class
3263(as a dotted module and class name.) This option is useful for instantiating a
3264:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3265exception tracebacks in an expanded or condensed format.
3266
Christian Heimes8b0facf2007-12-04 19:30:01 +00003267
3268Configuration server example
3269^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3270
3271Here is an example of a module using the logging configuration server::
3272
3273 import logging
3274 import logging.config
3275 import time
3276 import os
3277
3278 # read initial config file
3279 logging.config.fileConfig("logging.conf")
3280
3281 # create and start listener on port 9999
3282 t = logging.config.listen(9999)
3283 t.start()
3284
3285 logger = logging.getLogger("simpleExample")
3286
3287 try:
3288 # loop through logging calls to see the difference
3289 # new configurations make, until Ctrl+C is pressed
3290 while True:
3291 logger.debug("debug message")
3292 logger.info("info message")
3293 logger.warn("warn message")
3294 logger.error("error message")
3295 logger.critical("critical message")
3296 time.sleep(5)
3297 except KeyboardInterrupt:
3298 # cleanup
3299 logging.config.stopListening()
3300 t.join()
3301
3302And here is a script that takes a filename and sends that file to the server,
3303properly preceded with the binary-encoded length, as the new logging
3304configuration::
3305
3306 #!/usr/bin/env python
3307 import socket, sys, struct
3308
3309 data_to_send = open(sys.argv[1], "r").read()
3310
3311 HOST = 'localhost'
3312 PORT = 9999
3313 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00003314 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003315 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00003316 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003317 s.send(struct.pack(">L", len(data_to_send)))
3318 s.send(data_to_send)
3319 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00003320 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003321
3322
3323More examples
3324-------------
3325
3326Multiple handlers and formatters
3327^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3328
3329Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3330or maximum quota for the number of handlers you may add. Sometimes it will be
3331beneficial for an application to log all messages of all severities to a text
3332file while simultaneously logging errors or above to the console. To set this
3333up, simply configure the appropriate handlers. The logging calls in the
3334application code will remain unchanged. Here is a slight modification to the
3335previous simple module-based configuration example::
3336
3337 import logging
3338
3339 logger = logging.getLogger("simple_example")
3340 logger.setLevel(logging.DEBUG)
3341 # create file handler which logs even debug messages
3342 fh = logging.FileHandler("spam.log")
3343 fh.setLevel(logging.DEBUG)
3344 # create console handler with a higher log level
3345 ch = logging.StreamHandler()
3346 ch.setLevel(logging.ERROR)
3347 # create formatter and add it to the handlers
3348 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3349 ch.setFormatter(formatter)
3350 fh.setFormatter(formatter)
3351 # add the handlers to logger
3352 logger.addHandler(ch)
3353 logger.addHandler(fh)
3354
3355 # "application" code
3356 logger.debug("debug message")
3357 logger.info("info message")
3358 logger.warn("warn message")
3359 logger.error("error message")
3360 logger.critical("critical message")
3361
3362Notice that the "application" code does not care about multiple handlers. All
3363that changed was the addition and configuration of a new handler named *fh*.
3364
3365The ability to create new handlers with higher- or lower-severity filters can be
3366very helpful when writing and testing an application. Instead of using many
3367``print`` statements for debugging, use ``logger.debug``: Unlike the print
3368statements, which you will have to delete or comment out later, the logger.debug
3369statements can remain intact in the source code and remain dormant until you
3370need them again. At that time, the only change that needs to happen is to
3371modify the severity level of the logger and/or handler to debug.
3372
3373
3374Using logging in multiple modules
3375^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3376
3377It was mentioned above that multiple calls to
3378``logging.getLogger('someLogger')`` return a reference to the same logger
3379object. This is true not only within the same module, but also across modules
3380as long as it is in the same Python interpreter process. It is true for
3381references to the same object; additionally, application code can define and
3382configure a parent logger in one module and create (but not configure) a child
3383logger in a separate module, and all logger calls to the child will pass up to
3384the parent. Here is a main module::
3385
3386 import logging
3387 import auxiliary_module
3388
3389 # create logger with "spam_application"
3390 logger = logging.getLogger("spam_application")
3391 logger.setLevel(logging.DEBUG)
3392 # create file handler which logs even debug messages
3393 fh = logging.FileHandler("spam.log")
3394 fh.setLevel(logging.DEBUG)
3395 # create console handler with a higher log level
3396 ch = logging.StreamHandler()
3397 ch.setLevel(logging.ERROR)
3398 # create formatter and add it to the handlers
3399 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3400 fh.setFormatter(formatter)
3401 ch.setFormatter(formatter)
3402 # add the handlers to the logger
3403 logger.addHandler(fh)
3404 logger.addHandler(ch)
3405
3406 logger.info("creating an instance of auxiliary_module.Auxiliary")
3407 a = auxiliary_module.Auxiliary()
3408 logger.info("created an instance of auxiliary_module.Auxiliary")
3409 logger.info("calling auxiliary_module.Auxiliary.do_something")
3410 a.do_something()
3411 logger.info("finished auxiliary_module.Auxiliary.do_something")
3412 logger.info("calling auxiliary_module.some_function()")
3413 auxiliary_module.some_function()
3414 logger.info("done with auxiliary_module.some_function()")
3415
3416Here is the auxiliary module::
3417
3418 import logging
3419
3420 # create logger
3421 module_logger = logging.getLogger("spam_application.auxiliary")
3422
3423 class Auxiliary:
3424 def __init__(self):
3425 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3426 self.logger.info("creating an instance of Auxiliary")
3427 def do_something(self):
3428 self.logger.info("doing something")
3429 a = 1 + 1
3430 self.logger.info("done doing something")
3431
3432 def some_function():
3433 module_logger.info("received a call to \"some_function\"")
3434
3435The output looks like this::
3436
Christian Heimes043d6f62008-01-07 17:19:16 +00003437 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003438 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00003439 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003440 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00003441 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003442 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00003443 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003444 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00003445 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003446 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00003447 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003448 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00003449 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003450 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00003451 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003452 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00003453 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003454 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00003455 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00003456 done with auxiliary_module.some_function()
3457