blob: 6b2afeff14348c6d4d238ea21f86b5a0da0b4256 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl8ec7f652007-08-15 14:28:01 +000012.. index:: pair: Errors; logging
13
14.. versionadded:: 2.3
15
16This module defines functions and classes which implement a flexible error
17logging system for applications.
18
19Logging is performed by calling methods on instances of the :class:`Logger`
20class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandla7395032007-10-21 12:15:05 +000021conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl8ec7f652007-08-15 14:28:01 +000022separators. For example, a logger named "scan" is the parent of loggers
23"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
24and indicate the area of an application in which a logged message originates.
25
26Logged messages also have levels of importance associated with them. The default
27levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
28:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
29importance of a logged message by calling an appropriate method of
30:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
31:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
32constrained to use these levels: you can specify your own and use a more general
33:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
34
Georg Brandlc37f2882007-12-04 17:46:27 +000035
36Logging tutorial
37----------------
38
39The key benefit of having the logging API provided by a standard library module
40is that all Python modules can participate in logging, so your application log
41can include messages from third-party modules.
42
43It is, of course, possible to log messages with different verbosity levels or to
44different destinations. Support for writing log messages to files, HTTP
45GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Georg Brandl907a7202008-02-22 12:31:45 +000046mechanisms are all supported by the standard module. You can also create your
Georg Brandlc37f2882007-12-04 17:46:27 +000047own log destination class if you have special requirements not met by any of the
48built-in classes.
49
50Simple examples
51^^^^^^^^^^^^^^^
52
53.. sectionauthor:: Doug Hellmann
54.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
55
56Most applications are probably going to want to log to a file, so let's start
57with that case. Using the :func:`basicConfig` function, we can set up the
58default handler so that debug messages are written to a file::
59
60 import logging
61 LOG_FILENAME = '/tmp/logging_example.out'
Vinay Sajipf778bec2009-09-22 17:23:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Georg Brandlc37f2882007-12-04 17:46:27 +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 Smithe7dbebb2009-06-04 17:58:15 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Georg Brandlc37f2882007-12-04 17:46:27 +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
80 LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
81
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:
100 print filename
101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
105 /tmp/logging_rotatingfile_example.out
106 /tmp/logging_rotatingfile_example.out.1
107 /tmp/logging_rotatingfile_example.out.2
108 /tmp/logging_rotatingfile_example.out.3
109 /tmp/logging_rotatingfile_example.out.4
110 /tmp/logging_rotatingfile_example.out.5
111
112The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
113and 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 Smithe7dbebb2009-06-04 17:58:15 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Georg Brandlc37f2882007-12-04 17:46:27 +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 Sajipa7d44002009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Georg Brandlc37f2882007-12-04 17:46:27 +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
Brett Cannon499969a2008-02-25 05:33:07 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajip497256b2010-04-07 09:40:52 +0000249if it is provided, or ``root`` if not. The names are period-separated
Georg Brandlc37f2882007-12-04 17:46:27 +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
Vinay Sajipccd8bc82010-04-06 22:32:37 +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.
Georg Brandlc37f2882007-12-04 17:46:27 +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
Georg Brandl907a7202008-02-22 12:31:45 +0000270requires three individual handlers where each handler is responsible for sending
Georg Brandlc37f2882007-12-04 17:46:27 +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.
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Georg Brandlc37f2882007-12-04 17:46:27 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
Vinay Sajip497256b2010-04-07 09:40:52 +0000294defines the interface that all handlers should have and establishes some
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000295default behavior that child classes can use (or override).
Georg Brandlc37f2882007-12-04 17:46:27 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Brett Cannon499969a2008-02-25 05:33:07 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Georg Brandlc37f2882007-12-04 17:46:27 +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
Vinay Sajip4b782332009-01-19 06:49:19 +0000314substitution; the possible keys are documented in :ref:`formatter`.
Georg Brandlc37f2882007-12-04 17:46:27 +0000315
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
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +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
Vinay Sajipa38cd522010-05-18 08:16:27 +0000336handler, and a simple formatter using Python code::
Georg Brandlc37f2882007-12-04 17:46:27 +0000337
338 import logging
339
340 # create logger
341 logger = logging.getLogger("simple_example")
342 logger.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000343
Georg Brandlc37f2882007-12-04 17:46:27 +0000344 # create console handler and set level to debug
345 ch = logging.StreamHandler()
346 ch.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000347
Georg Brandlc37f2882007-12-04 17:46:27 +0000348 # create formatter
349 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000350
Georg Brandlc37f2882007-12-04 17:46:27 +0000351 # add formatter to ch
352 ch.setFormatter(formatter)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000353
Georg Brandlc37f2882007-12-04 17:46:27 +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
Vinay Sajip0e6e97d2010-02-04 20:23:45 +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
Georg Brandlf6d367452010-03-12 10:02:03 +0000438import mechanisms. Thus, you could use either :class:`handlers.WatchedFileHandler`
439(relative to the logging module) or :class:`mypackage.mymodule.MyHandler` (for a
440class defined in package :mod:`mypackage` and module :mod:`mymodule`, where
441:mod:`mypackage` is available on the Python import path).
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000442
Vinay Sajipc76defc2010-05-21 17:41:34 +0000443.. versionchanged:: 2.7
444
445In Python 2.7, a new means of configuring logging has been introduced, using
446dictionaries to hold configuration information. This provides a superset of the
447functionality of the config-file-based approach outlined above, and is the
448recommended configuration method for new applications and deployments. Because
449a Python dictionary is used to hold configuration information, and since you
450can populate that dictionary using different means, you have more options for
451configuration. For example, you can use a configuration file in JSON format,
452or, if you have access to YAML processing functionality, a file in YAML
453format, to populate the configuration dictionary. Or, of course, you can
454construct the dictionary in Python code, receive it in pickled form over a
455socket, or use whatever approach makes sense for your application.
456
457Here's an example of the same configuration as above, in YAML format for
458the new dictionary-based approach::
459
460 version: 1
461 formatters:
462 simple:
463 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
464 handlers:
465 console:
466 class: logging.StreamHandler
467 level: DEBUG
468 formatter: simple
469 stream: ext://sys.stdout
470 loggers:
471 simpleExample:
472 level: DEBUG
473 handlers: [console]
474 propagate: no
475 root:
476 level: DEBUG
477 handlers: [console]
478
479For more information about logging using a dictionary, see
480:ref:`logging-config-api`.
481
Vinay Sajip99505c82009-01-10 13:38:04 +0000482.. _library-config:
483
Vinay Sajip34bfda52008-09-01 15:08:07 +0000484Configuring Logging for a Library
485^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
486
487When developing a library which uses logging, some consideration needs to be
488given to its configuration. If the using application does not use logging, and
489library code makes logging calls, then a one-off message "No handlers could be
490found for logger X.Y.Z" is printed to the console. This message is intended
491to catch mistakes in logging configuration, but will confuse an application
492developer who is not aware of logging by the library.
493
494In addition to documenting how a library uses logging, a good way to configure
495library logging so that it does not cause a spurious message is to add a
496handler which does nothing. This avoids the message being printed, since a
497handler will be found: it just doesn't produce any output. If the library user
498configures logging for application use, presumably that configuration will add
499some handlers, and if levels are suitably configured then logging calls made
500in library code will send output to those handlers, as normal.
501
502A do-nothing handler can be simply defined as follows::
503
504 import logging
505
506 class NullHandler(logging.Handler):
507 def emit(self, record):
508 pass
509
510An instance of this handler should be added to the top-level logger of the
511logging namespace used by the library. If all logging by a library *foo* is
512done using loggers with names matching "foo.x.y", then the code::
513
514 import logging
515
516 h = NullHandler()
517 logging.getLogger("foo").addHandler(h)
518
519should have the desired effect. If an organisation produces a number of
520libraries, then the logger name specified can be "orgname.foo" rather than
521just "foo".
522
Vinay Sajip213faca2008-12-03 23:22:58 +0000523.. versionadded:: 2.7
524
525The :class:`NullHandler` class was not present in previous versions, but is now
526included, so that it need not be defined in library code.
527
528
Georg Brandlc37f2882007-12-04 17:46:27 +0000529
530Logging Levels
531--------------
532
Georg Brandl8ec7f652007-08-15 14:28:01 +0000533The numeric values of logging levels are given in the following table. These are
534primarily of interest if you want to define your own levels, and need them to
535have specific values relative to the predefined levels. If you define a level
536with the same numeric value, it overwrites the predefined value; the predefined
537name is lost.
538
539+--------------+---------------+
540| Level | Numeric value |
541+==============+===============+
542| ``CRITICAL`` | 50 |
543+--------------+---------------+
544| ``ERROR`` | 40 |
545+--------------+---------------+
546| ``WARNING`` | 30 |
547+--------------+---------------+
548| ``INFO`` | 20 |
549+--------------+---------------+
550| ``DEBUG`` | 10 |
551+--------------+---------------+
552| ``NOTSET`` | 0 |
553+--------------+---------------+
554
555Levels can also be associated with loggers, being set either by the developer or
556through loading a saved logging configuration. When a logging method is called
557on a logger, the logger compares its own level with the level associated with
558the method call. If the logger's level is higher than the method call's, no
559logging message is actually generated. This is the basic mechanism controlling
560the verbosity of logging output.
561
562Logging messages are encoded as instances of the :class:`LogRecord` class. When
563a logger decides to actually log an event, a :class:`LogRecord` instance is
564created from the logging message.
565
566Logging messages are subjected to a dispatch mechanism through the use of
567:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
568class. Handlers are responsible for ensuring that a logged message (in the form
569of a :class:`LogRecord`) ends up in a particular location (or set of locations)
570which is useful for the target audience for that message (such as end users,
571support desk staff, system administrators, developers). Handlers are passed
572:class:`LogRecord` instances intended for particular destinations. Each logger
573can have zero, one or more handlers associated with it (via the
574:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
575directly associated with a logger, *all handlers associated with all ancestors
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000576of the logger* are called to dispatch the message (unless the *propagate* flag
577for a logger is set to a false value, at which point the passing to ancestor
578handlers stops).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579
580Just as for loggers, handlers can have levels associated with them. A handler's
581level acts as a filter in the same way as a logger's level does. If a handler
582decides to actually dispatch an event, the :meth:`emit` method is used to send
583the message to its destination. Most user-defined subclasses of :class:`Handler`
584will need to override this :meth:`emit`.
585
Vinay Sajipb5902e62009-01-15 22:48:13 +0000586Useful Handlers
587---------------
588
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589In addition to the base :class:`Handler` class, many useful subclasses are
590provided:
591
Vinay Sajip4b782332009-01-19 06:49:19 +0000592#. :ref:`stream-handler` instances send error messages to streams (file-like
Georg Brandl8ec7f652007-08-15 14:28:01 +0000593 objects).
594
Vinay Sajip4b782332009-01-19 06:49:19 +0000595#. :ref:`file-handler` instances send error messages to disk files.
Vinay Sajipb1a15e42009-01-15 23:04:47 +0000596
Vinay Sajipb5902e62009-01-15 22:48:13 +0000597#. :class:`BaseRotatingHandler` is the base class for handlers that
Vinay Sajip99234c52009-01-12 20:36:18 +0000598 rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajip4b782332009-01-19 06:49:19 +0000599 directly. Instead, use :ref:`rotating-file-handler` or
600 :ref:`timed-rotating-file-handler`.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000601
Vinay Sajip4b782332009-01-19 06:49:19 +0000602#. :ref:`rotating-file-handler` instances send error messages to disk
Vinay Sajipb5902e62009-01-15 22:48:13 +0000603 files, with support for maximum log file sizes and log file rotation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000604
Vinay Sajip4b782332009-01-19 06:49:19 +0000605#. :ref:`timed-rotating-file-handler` instances send error messages to
Vinay Sajipb5902e62009-01-15 22:48:13 +0000606 disk files, rotating the log file at certain timed intervals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000607
Vinay Sajip4b782332009-01-19 06:49:19 +0000608#. :ref:`socket-handler` instances send error messages to TCP/IP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000609 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000610
Vinay Sajip4b782332009-01-19 06:49:19 +0000611#. :ref:`datagram-handler` instances send error messages to UDP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000612 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000613
Vinay Sajip4b782332009-01-19 06:49:19 +0000614#. :ref:`smtp-handler` instances send error messages to a designated
Vinay Sajipb5902e62009-01-15 22:48:13 +0000615 email address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000616
Vinay Sajip4b782332009-01-19 06:49:19 +0000617#. :ref:`syslog-handler` instances send error messages to a Unix
Vinay Sajipb5902e62009-01-15 22:48:13 +0000618 syslog daemon, possibly on a remote machine.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
Vinay Sajip4b782332009-01-19 06:49:19 +0000620#. :ref:`nt-eventlog-handler` instances send error messages to a
Vinay Sajipb5902e62009-01-15 22:48:13 +0000621 Windows NT/2000/XP event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000622
Vinay Sajip4b782332009-01-19 06:49:19 +0000623#. :ref:`memory-handler` instances send error messages to a buffer
Vinay Sajipb5902e62009-01-15 22:48:13 +0000624 in memory, which is flushed whenever specific criteria are met.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
Vinay Sajip4b782332009-01-19 06:49:19 +0000626#. :ref:`http-handler` instances send error messages to an HTTP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000627 server using either ``GET`` or ``POST`` semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000628
Vinay Sajip4b782332009-01-19 06:49:19 +0000629#. :ref:`watched-file-handler` instances watch the file they are
Vinay Sajipb5902e62009-01-15 22:48:13 +0000630 logging to. If the file changes, it is closed and reopened using the file
631 name. This handler is only useful on Unix-like systems; Windows does not
632 support the underlying mechanism used.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000633
Vinay Sajip4b782332009-01-19 06:49:19 +0000634#. :ref:`null-handler` instances do nothing with error messages. They are used
Vinay Sajip213faca2008-12-03 23:22:58 +0000635 by library developers who want to use logging, but want to avoid the "No
636 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip99505c82009-01-10 13:38:04 +0000637 the library user has not configured logging. See :ref:`library-config` for
638 more information.
Vinay Sajip213faca2008-12-03 23:22:58 +0000639
640.. versionadded:: 2.7
641
642The :class:`NullHandler` class was not present in previous versions.
643
Vinay Sajip7cc97552008-12-30 07:01:25 +0000644The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
645classes are defined in the core logging package. The other handlers are
646defined in a sub- module, :mod:`logging.handlers`. (There is also another
647sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000648
649Logged messages are formatted for presentation through instances of the
650:class:`Formatter` class. They are initialized with a format string suitable for
651use with the % operator and a dictionary.
652
653For formatting multiple messages in a batch, instances of
654:class:`BufferingFormatter` can be used. In addition to the format string (which
655is applied to each message in the batch), there is provision for header and
656trailer format strings.
657
658When filtering based on logger level and/or handler level is not enough,
659instances of :class:`Filter` can be added to both :class:`Logger` and
660:class:`Handler` instances (through their :meth:`addFilter` method). Before
661deciding to process a message further, both loggers and handlers consult all
662their filters for permission. If any filter returns a false value, the message
663is not processed further.
664
665The basic :class:`Filter` functionality allows filtering by specific logger
666name. If this feature is used, messages sent to the named logger and its
667children are allowed through the filter, and all others dropped.
668
Vinay Sajipb5902e62009-01-15 22:48:13 +0000669Module-Level Functions
670----------------------
671
Georg Brandl8ec7f652007-08-15 14:28:01 +0000672In addition to the classes described above, there are a number of module- level
673functions.
674
675
676.. function:: getLogger([name])
677
678 Return a logger with the specified name or, if no name is specified, return a
679 logger which is the root logger of the hierarchy. If specified, the name is
680 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
681 Choice of these names is entirely up to the developer who is using logging.
682
683 All calls to this function with a given name return the same logger instance.
684 This means that logger instances never need to be passed between different parts
685 of an application.
686
687
688.. function:: getLoggerClass()
689
690 Return either the standard :class:`Logger` class, or the last class passed to
691 :func:`setLoggerClass`. This function may be called from within a new class
692 definition, to ensure that installing a customised :class:`Logger` class will
693 not undo customisations already applied by other code. For example::
694
695 class MyLogger(logging.getLoggerClass()):
696 # ... override behaviour here
697
698
699.. function:: debug(msg[, *args[, **kwargs]])
700
701 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
702 message format string, and the *args* are the arguments which are merged into
703 *msg* using the string formatting operator. (Note that this means that you can
704 use keywords in the format string, together with a single dictionary argument.)
705
706 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
707 which, if it does not evaluate as false, causes exception information to be
708 added to the logging message. If an exception tuple (in the format returned by
709 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
710 is called to get the exception information.
711
712 The other optional keyword argument is *extra* which can be used to pass a
713 dictionary which is used to populate the __dict__ of the LogRecord created for
714 the logging event with user-defined attributes. These custom attributes can then
715 be used as you like. For example, they could be incorporated into logged
716 messages. For example::
717
718 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
719 logging.basicConfig(format=FORMAT)
720 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
721 logging.warning("Protocol problem: %s", "connection reset", extra=d)
722
723 would print something like ::
724
725 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
726
727 The keys in the dictionary passed in *extra* should not clash with the keys used
728 by the logging system. (See the :class:`Formatter` documentation for more
729 information on which keys are used by the logging system.)
730
731 If you choose to use these attributes in logged messages, you need to exercise
732 some care. In the above example, for instance, the :class:`Formatter` has been
733 set up with a format string which expects 'clientip' and 'user' in the attribute
734 dictionary of the LogRecord. If these are missing, the message will not be
735 logged because a string formatting exception will occur. So in this case, you
736 always need to pass the *extra* dictionary with these keys.
737
738 While this might be annoying, this feature is intended for use in specialized
739 circumstances, such as multi-threaded servers where the same code executes in
740 many contexts, and interesting conditions which arise are dependent on this
741 context (such as remote client IP address and authenticated user name, in the
742 above example). In such circumstances, it is likely that specialized
743 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
744
745 .. versionchanged:: 2.5
746 *extra* was added.
747
748
749.. function:: info(msg[, *args[, **kwargs]])
750
751 Logs a message with level :const:`INFO` on the root logger. The arguments are
752 interpreted as for :func:`debug`.
753
754
755.. function:: warning(msg[, *args[, **kwargs]])
756
757 Logs a message with level :const:`WARNING` on the root logger. The arguments are
758 interpreted as for :func:`debug`.
759
760
761.. function:: error(msg[, *args[, **kwargs]])
762
763 Logs a message with level :const:`ERROR` on the root logger. The arguments are
764 interpreted as for :func:`debug`.
765
766
767.. function:: critical(msg[, *args[, **kwargs]])
768
769 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
770 are interpreted as for :func:`debug`.
771
772
773.. function:: exception(msg[, *args])
774
775 Logs a message with level :const:`ERROR` on the root logger. The arguments are
776 interpreted as for :func:`debug`. Exception info is added to the logging
777 message. This function should only be called from an exception handler.
778
779
780.. function:: log(level, msg[, *args[, **kwargs]])
781
782 Logs a message with level *level* on the root logger. The other arguments are
783 interpreted as for :func:`debug`.
784
785
786.. function:: disable(lvl)
787
788 Provides an overriding level *lvl* for all loggers which takes precedence over
789 the logger's own level. When the need arises to temporarily throttle logging
Vinay Sajip2060e422010-03-17 15:05:57 +0000790 output down across the whole application, this function can be useful. Its
791 effect is to disable all logging calls of severity *lvl* and below, so that
792 if you call it with a value of INFO, then all INFO and DEBUG events would be
793 discarded, whereas those of severity WARNING and above would be processed
794 according to the logger's effective level.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795
796
797.. function:: addLevelName(lvl, levelName)
798
799 Associates level *lvl* with text *levelName* in an internal dictionary, which is
800 used to map numeric levels to a textual representation, for example when a
801 :class:`Formatter` formats a message. This function can also be used to define
802 your own levels. The only constraints are that all levels used must be
803 registered using this function, levels should be positive integers and they
804 should increase in increasing order of severity.
805
806
807.. function:: getLevelName(lvl)
808
809 Returns the textual representation of logging level *lvl*. If the level is one
810 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
811 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
812 have associated levels with names using :func:`addLevelName` then the name you
813 have associated with *lvl* is returned. If a numeric value corresponding to one
814 of the defined levels is passed in, the corresponding string representation is
815 returned. Otherwise, the string "Level %s" % lvl is returned.
816
817
818.. function:: makeLogRecord(attrdict)
819
820 Creates and returns a new :class:`LogRecord` instance whose attributes are
821 defined by *attrdict*. This function is useful for taking a pickled
822 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
823 it as a :class:`LogRecord` instance at the receiving end.
824
825
826.. function:: basicConfig([**kwargs])
827
828 Does basic configuration for the logging system by creating a
829 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000830 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
832 if no handlers are defined for the root logger.
833
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000834 This function does nothing if the root logger already has handlers
835 configured for it.
Georg Brandldfb5bbd2008-05-09 06:18:27 +0000836
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837 .. versionchanged:: 2.4
838 Formerly, :func:`basicConfig` did not take any keyword arguments.
839
840 The following keyword arguments are supported.
841
842 +--------------+---------------------------------------------+
843 | Format | Description |
844 +==============+=============================================+
845 | ``filename`` | Specifies that a FileHandler be created, |
846 | | using the specified filename, rather than a |
847 | | StreamHandler. |
848 +--------------+---------------------------------------------+
849 | ``filemode`` | Specifies the mode to open the file, if |
850 | | filename is specified (if filemode is |
851 | | unspecified, it defaults to 'a'). |
852 +--------------+---------------------------------------------+
853 | ``format`` | Use the specified format string for the |
854 | | handler. |
855 +--------------+---------------------------------------------+
856 | ``datefmt`` | Use the specified date/time format. |
857 +--------------+---------------------------------------------+
858 | ``level`` | Set the root logger level to the specified |
859 | | level. |
860 +--------------+---------------------------------------------+
861 | ``stream`` | Use the specified stream to initialize the |
862 | | StreamHandler. Note that this argument is |
863 | | incompatible with 'filename' - if both are |
864 | | present, 'stream' is ignored. |
865 +--------------+---------------------------------------------+
866
867
868.. function:: shutdown()
869
870 Informs the logging system to perform an orderly shutdown by flushing and
Vinay Sajip91f0ee42008-03-16 21:35:58 +0000871 closing all handlers. This should be called at application exit and no
872 further use of the logging system should be made after this call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000873
874
875.. function:: setLoggerClass(klass)
876
877 Tells the logging system to use the class *klass* when instantiating a logger.
878 The class should define :meth:`__init__` such that only a name argument is
879 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
880 function is typically called before any loggers are instantiated by applications
881 which need to use custom logger behavior.
882
883
884.. seealso::
885
886 :pep:`282` - A Logging System
887 The proposal which described this feature for inclusion in the Python standard
888 library.
889
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000890 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +0000891 This is the original source for the :mod:`logging` package. The version of the
892 package available from this site is suitable for use with Python 1.5.2, 2.1.x
893 and 2.2.x, which do not include the :mod:`logging` package in the standard
894 library.
895
Vinay Sajip4b782332009-01-19 06:49:19 +0000896.. _logger:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000897
898Logger Objects
899--------------
900
901Loggers have the following attributes and methods. Note that Loggers are never
902instantiated directly, but always through the module-level function
903``logging.getLogger(name)``.
904
905
906.. attribute:: Logger.propagate
907
908 If this evaluates to false, logging messages are not passed by this logger or by
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000909 its child loggers to the handlers of higher level (ancestor) loggers. The
910 constructor sets this attribute to 1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000911
912
913.. method:: Logger.setLevel(lvl)
914
915 Sets the threshold for this logger to *lvl*. Logging messages which are less
916 severe than *lvl* will be ignored. When a logger is created, the level is set to
917 :const:`NOTSET` (which causes all messages to be processed when the logger is
918 the root logger, or delegation to the parent when the logger is a non-root
919 logger). Note that the root logger is created with level :const:`WARNING`.
920
921 The term "delegation to the parent" means that if a logger has a level of
922 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
923 a level other than NOTSET is found, or the root is reached.
924
925 If an ancestor is found with a level other than NOTSET, then that ancestor's
926 level is treated as the effective level of the logger where the ancestor search
927 began, and is used to determine how a logging event is handled.
928
929 If the root is reached, and it has a level of NOTSET, then all messages will be
930 processed. Otherwise, the root's level will be used as the effective level.
931
932
933.. method:: Logger.isEnabledFor(lvl)
934
935 Indicates if a message of severity *lvl* would be processed by this logger.
936 This method checks first the module-level level set by
937 ``logging.disable(lvl)`` and then the logger's effective level as determined
938 by :meth:`getEffectiveLevel`.
939
940
941.. method:: Logger.getEffectiveLevel()
942
943 Indicates the effective level for this logger. If a value other than
944 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
945 the hierarchy is traversed towards the root until a value other than
946 :const:`NOTSET` is found, and that value is returned.
947
948
Vinay Sajip804899b2010-03-22 15:29:01 +0000949.. method:: Logger.getChild(suffix)
950
951 Returns a logger which is a descendant to this logger, as determined by the suffix.
952 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
953 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
954 convenience method, useful when the parent logger is named using e.g. ``__name__``
955 rather than a literal string.
956
957 .. versionadded:: 2.7
958
Georg Brandl8ec7f652007-08-15 14:28:01 +0000959.. method:: Logger.debug(msg[, *args[, **kwargs]])
960
961 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
962 message format string, and the *args* are the arguments which are merged into
963 *msg* using the string formatting operator. (Note that this means that you can
964 use keywords in the format string, together with a single dictionary argument.)
965
966 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
967 which, if it does not evaluate as false, causes exception information to be
968 added to the logging message. If an exception tuple (in the format returned by
969 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
970 is called to get the exception information.
971
972 The other optional keyword argument is *extra* which can be used to pass a
973 dictionary which is used to populate the __dict__ of the LogRecord created for
974 the logging event with user-defined attributes. These custom attributes can then
975 be used as you like. For example, they could be incorporated into logged
976 messages. For example::
977
978 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
979 logging.basicConfig(format=FORMAT)
Neal Norwitz53004282007-10-23 05:44:27 +0000980 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981 logger = logging.getLogger("tcpserver")
982 logger.warning("Protocol problem: %s", "connection reset", extra=d)
983
984 would print something like ::
985
986 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
987
988 The keys in the dictionary passed in *extra* should not clash with the keys used
989 by the logging system. (See the :class:`Formatter` documentation for more
990 information on which keys are used by the logging system.)
991
992 If you choose to use these attributes in logged messages, you need to exercise
993 some care. In the above example, for instance, the :class:`Formatter` has been
994 set up with a format string which expects 'clientip' and 'user' in the attribute
995 dictionary of the LogRecord. If these are missing, the message will not be
996 logged because a string formatting exception will occur. So in this case, you
997 always need to pass the *extra* dictionary with these keys.
998
999 While this might be annoying, this feature is intended for use in specialized
1000 circumstances, such as multi-threaded servers where the same code executes in
1001 many contexts, and interesting conditions which arise are dependent on this
1002 context (such as remote client IP address and authenticated user name, in the
1003 above example). In such circumstances, it is likely that specialized
1004 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1005
1006 .. versionchanged:: 2.5
1007 *extra* was added.
1008
1009
1010.. method:: Logger.info(msg[, *args[, **kwargs]])
1011
1012 Logs a message with level :const:`INFO` on this logger. The arguments are
1013 interpreted as for :meth:`debug`.
1014
1015
1016.. method:: Logger.warning(msg[, *args[, **kwargs]])
1017
1018 Logs a message with level :const:`WARNING` on this logger. The arguments are
1019 interpreted as for :meth:`debug`.
1020
1021
1022.. method:: Logger.error(msg[, *args[, **kwargs]])
1023
1024 Logs a message with level :const:`ERROR` on this logger. The arguments are
1025 interpreted as for :meth:`debug`.
1026
1027
1028.. method:: Logger.critical(msg[, *args[, **kwargs]])
1029
1030 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1031 interpreted as for :meth:`debug`.
1032
1033
1034.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
1035
1036 Logs a message with integer level *lvl* on this logger. The other arguments are
1037 interpreted as for :meth:`debug`.
1038
1039
1040.. method:: Logger.exception(msg[, *args])
1041
1042 Logs a message with level :const:`ERROR` on this logger. The arguments are
1043 interpreted as for :meth:`debug`. Exception info is added to the logging
1044 message. This method should only be called from an exception handler.
1045
1046
1047.. method:: Logger.addFilter(filt)
1048
1049 Adds the specified filter *filt* to this logger.
1050
1051
1052.. method:: Logger.removeFilter(filt)
1053
1054 Removes the specified filter *filt* from this logger.
1055
1056
1057.. method:: Logger.filter(record)
1058
1059 Applies this logger's filters to the record and returns a true value if the
1060 record is to be processed.
1061
1062
1063.. method:: Logger.addHandler(hdlr)
1064
1065 Adds the specified handler *hdlr* to this logger.
1066
1067
1068.. method:: Logger.removeHandler(hdlr)
1069
1070 Removes the specified handler *hdlr* from this logger.
1071
1072
1073.. method:: Logger.findCaller()
1074
1075 Finds the caller's source filename and line number. Returns the filename, line
1076 number and function name as a 3-element tuple.
1077
Matthias Klosef0e29182007-08-16 12:03:44 +00001078 .. versionchanged:: 2.4
Georg Brandl8ec7f652007-08-15 14:28:01 +00001079 The function name was added. In earlier versions, the filename and line number
1080 were returned as a 2-element tuple..
1081
1082
1083.. method:: Logger.handle(record)
1084
1085 Handles a record by passing it to all handlers associated with this logger and
1086 its ancestors (until a false value of *propagate* is found). This method is used
1087 for unpickled records received from a socket, as well as those created locally.
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001088 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089
1090
1091.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
1092
1093 This is a factory method which can be overridden in subclasses to create
1094 specialized :class:`LogRecord` instances.
1095
1096 .. versionchanged:: 2.5
1097 *func* and *extra* were added.
1098
1099
1100.. _minimal-example:
1101
1102Basic example
1103-------------
1104
1105.. versionchanged:: 2.4
1106 formerly :func:`basicConfig` did not take any keyword arguments.
1107
1108The :mod:`logging` package provides a lot of flexibility, and its configuration
1109can appear daunting. This section demonstrates that simple use of the logging
1110package is possible.
1111
1112The simplest example shows logging to the console::
1113
1114 import logging
1115
1116 logging.debug('A debug message')
1117 logging.info('Some information')
1118 logging.warning('A shot across the bows')
1119
1120If you run the above script, you'll see this::
1121
1122 WARNING:root:A shot across the bows
1123
1124Because no particular logger was specified, the system used the root logger. The
1125debug and info messages didn't appear because by default, the root logger is
1126configured to only handle messages with a severity of WARNING or above. The
1127message format is also a configuration default, as is the output destination of
1128the messages - ``sys.stderr``. The severity level, the message format and
1129destination can be easily changed, as shown in the example below::
1130
1131 import logging
1132
1133 logging.basicConfig(level=logging.DEBUG,
1134 format='%(asctime)s %(levelname)s %(message)s',
1135 filename='/tmp/myapp.log',
1136 filemode='w')
1137 logging.debug('A debug message')
1138 logging.info('Some information')
1139 logging.warning('A shot across the bows')
1140
1141The :meth:`basicConfig` method is used to change the configuration defaults,
1142which results in output (written to ``/tmp/myapp.log``) which should look
1143something like the following::
1144
1145 2004-07-02 13:00:08,743 DEBUG A debug message
1146 2004-07-02 13:00:08,743 INFO Some information
1147 2004-07-02 13:00:08,743 WARNING A shot across the bows
1148
1149This time, all messages with a severity of DEBUG or above were handled, and the
1150format of the messages was also changed, and output went to the specified file
1151rather than the console.
1152
1153Formatting uses standard Python string formatting - see section
1154:ref:`string-formatting`. The format string takes the following common
1155specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1156documentation.
1157
1158+-------------------+-----------------------------------------------+
1159| Format | Description |
1160+===================+===============================================+
1161| ``%(name)s`` | Name of the logger (logging channel). |
1162+-------------------+-----------------------------------------------+
1163| ``%(levelname)s`` | Text logging level for the message |
1164| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1165| | ``'ERROR'``, ``'CRITICAL'``). |
1166+-------------------+-----------------------------------------------+
1167| ``%(asctime)s`` | Human-readable time when the |
1168| | :class:`LogRecord` was created. By default |
1169| | this is of the form "2003-07-08 16:49:45,896" |
1170| | (the numbers after the comma are millisecond |
1171| | portion of the time). |
1172+-------------------+-----------------------------------------------+
1173| ``%(message)s`` | The logged message. |
1174+-------------------+-----------------------------------------------+
1175
1176To change the date/time format, you can pass an additional keyword parameter,
1177*datefmt*, as in the following::
1178
1179 import logging
1180
1181 logging.basicConfig(level=logging.DEBUG,
1182 format='%(asctime)s %(levelname)-8s %(message)s',
1183 datefmt='%a, %d %b %Y %H:%M:%S',
1184 filename='/temp/myapp.log',
1185 filemode='w')
1186 logging.debug('A debug message')
1187 logging.info('Some information')
1188 logging.warning('A shot across the bows')
1189
1190which would result in output like ::
1191
1192 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1193 Fri, 02 Jul 2004 13:06:18 INFO Some information
1194 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1195
1196The date format string follows the requirements of :func:`strftime` - see the
1197documentation for the :mod:`time` module.
1198
1199If, instead of sending logging output to the console or a file, you'd rather use
1200a file-like object which you have created separately, you can pass it to
1201:func:`basicConfig` using the *stream* keyword argument. Note that if both
1202*stream* and *filename* keyword arguments are passed, the *stream* argument is
1203ignored.
1204
1205Of course, you can put variable information in your output. To do this, simply
1206have the message be a format string and pass in additional arguments containing
1207the variable information, as in the following example::
1208
1209 import logging
1210
1211 logging.basicConfig(level=logging.DEBUG,
1212 format='%(asctime)s %(levelname)-8s %(message)s',
1213 datefmt='%a, %d %b %Y %H:%M:%S',
1214 filename='/temp/myapp.log',
1215 filemode='w')
1216 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1217
1218which would result in ::
1219
1220 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1221
1222
1223.. _multiple-destinations:
1224
1225Logging to multiple destinations
1226--------------------------------
1227
1228Let's say you want to log to console and file with different message formats and
1229in differing circumstances. Say you want to log messages with levels of DEBUG
1230and higher to file, and those messages at level INFO and higher to the console.
1231Let's also assume that the file should contain timestamps, but the console
1232messages should not. Here's how you can achieve this::
1233
1234 import logging
1235
1236 # set up logging to file - see previous section for more details
1237 logging.basicConfig(level=logging.DEBUG,
1238 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1239 datefmt='%m-%d %H:%M',
1240 filename='/temp/myapp.log',
1241 filemode='w')
1242 # define a Handler which writes INFO messages or higher to the sys.stderr
1243 console = logging.StreamHandler()
1244 console.setLevel(logging.INFO)
1245 # set a format which is simpler for console use
1246 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1247 # tell the handler to use this format
1248 console.setFormatter(formatter)
1249 # add the handler to the root logger
1250 logging.getLogger('').addHandler(console)
1251
1252 # Now, we can log to the root logger, or any other logger. First the root...
1253 logging.info('Jackdaws love my big sphinx of quartz.')
1254
1255 # Now, define a couple of other loggers which might represent areas in your
1256 # application:
1257
1258 logger1 = logging.getLogger('myapp.area1')
1259 logger2 = logging.getLogger('myapp.area2')
1260
1261 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1262 logger1.info('How quickly daft jumping zebras vex.')
1263 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1264 logger2.error('The five boxing wizards jump quickly.')
1265
1266When you run this, on the console you will see ::
1267
1268 root : INFO Jackdaws love my big sphinx of quartz.
1269 myapp.area1 : INFO How quickly daft jumping zebras vex.
1270 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1271 myapp.area2 : ERROR The five boxing wizards jump quickly.
1272
1273and in the file you will see something like ::
1274
1275 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1276 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1277 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1278 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1279 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1280
1281As you can see, the DEBUG message only shows up in the file. The other messages
1282are sent to both destinations.
1283
1284This example uses console and file handlers, but you can use any number and
1285combination of handlers you choose.
1286
Vinay Sajip333c6e72009-08-20 22:04:32 +00001287.. _logging-exceptions:
1288
1289Exceptions raised during logging
1290--------------------------------
1291
1292The logging package is designed to swallow exceptions which occur while logging
1293in production. This is so that errors which occur while handling logging events
1294- such as logging misconfiguration, network or other similar errors - do not
1295cause the application using logging to terminate prematurely.
1296
1297:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1298swallowed. Other exceptions which occur during the :meth:`emit` method of a
1299:class:`Handler` subclass are passed to its :meth:`handleError` method.
1300
1301The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlf6d367452010-03-12 10:02:03 +00001302to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1303traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip333c6e72009-08-20 22:04:32 +00001304
Georg Brandlf6d367452010-03-12 10:02:03 +00001305**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip333c6e72009-08-20 22:04:32 +00001306during development, you typically want to be notified of any exceptions that
Georg Brandlf6d367452010-03-12 10:02:03 +00001307occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip333c6e72009-08-20 22:04:32 +00001308usage.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001309
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001310.. _context-info:
1311
1312Adding contextual information to your logging output
1313----------------------------------------------------
1314
1315Sometimes you want logging output to contain contextual information in
1316addition to the parameters passed to the logging call. For example, in a
1317networked application, it may be desirable to log client-specific information
1318in the log (e.g. remote client's username, or IP address). Although you could
1319use the *extra* parameter to achieve this, it's not always convenient to pass
1320the information in this way. While it might be tempting to create
1321:class:`Logger` instances on a per-connection basis, this is not a good idea
1322because these instances are not garbage collected. While this is not a problem
1323in practice, when the number of :class:`Logger` instances is dependent on the
1324level of granularity you want to use in logging an application, it could
1325be hard to manage if the number of :class:`Logger` instances becomes
1326effectively unbounded.
1327
Vinay Sajipc7403352008-01-18 15:54:14 +00001328An easy way in which you can pass contextual information to be output along
1329with logging event information is to use the :class:`LoggerAdapter` class.
1330This class is designed to look like a :class:`Logger`, so that you can call
1331:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1332:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1333same signatures as their counterparts in :class:`Logger`, so you can use the
1334two types of instances interchangeably.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001335
Vinay Sajipc7403352008-01-18 15:54:14 +00001336When you create an instance of :class:`LoggerAdapter`, you pass it a
1337:class:`Logger` instance and a dict-like object which contains your contextual
1338information. When you call one of the logging methods on an instance of
1339:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1340:class:`Logger` passed to its constructor, and arranges to pass the contextual
1341information in the delegated call. Here's a snippet from the code of
1342:class:`LoggerAdapter`::
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001343
Vinay Sajipc7403352008-01-18 15:54:14 +00001344 def debug(self, msg, *args, **kwargs):
1345 """
1346 Delegate a debug call to the underlying logger, after adding
1347 contextual information from this adapter instance.
1348 """
1349 msg, kwargs = self.process(msg, kwargs)
1350 self.logger.debug(msg, *args, **kwargs)
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001351
Vinay Sajipc7403352008-01-18 15:54:14 +00001352The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1353information is added to the logging output. It's passed the message and
1354keyword arguments of the logging call, and it passes back (potentially)
1355modified versions of these to use in the call to the underlying logger. The
1356default implementation of this method leaves the message alone, but inserts
1357an "extra" key in the keyword argument whose value is the dict-like object
1358passed to the constructor. Of course, if you had passed an "extra" keyword
1359argument in the call to the adapter, it will be silently overwritten.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001360
Vinay Sajipc7403352008-01-18 15:54:14 +00001361The advantage of using "extra" is that the values in the dict-like object are
1362merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1363customized strings with your :class:`Formatter` instances which know about
1364the keys of the dict-like object. If you need a different method, e.g. if you
1365want to prepend or append the contextual information to the message string,
1366you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1367to do what you need. Here's an example script which uses this class, which
1368also illustrates what dict-like behaviour is needed from an arbitrary
1369"dict-like" object for use in the constructor::
1370
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001371 import logging
Vinay Sajip733024a2008-01-21 17:39:22 +00001372
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001373 class ConnInfo:
1374 """
1375 An example class which shows how an arbitrary class can be used as
1376 the 'extra' context information repository passed to a LoggerAdapter.
1377 """
Vinay Sajip733024a2008-01-21 17:39:22 +00001378
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001379 def __getitem__(self, name):
1380 """
1381 To allow this instance to look like a dict.
1382 """
1383 from random import choice
1384 if name == "ip":
1385 result = choice(["127.0.0.1", "192.168.0.1"])
1386 elif name == "user":
1387 result = choice(["jim", "fred", "sheila"])
1388 else:
1389 result = self.__dict__.get(name, "?")
1390 return result
Vinay Sajip733024a2008-01-21 17:39:22 +00001391
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001392 def __iter__(self):
1393 """
1394 To allow iteration over keys, which will be merged into
1395 the LogRecord dict before formatting and output.
1396 """
1397 keys = ["ip", "user"]
1398 keys.extend(self.__dict__.keys())
1399 return keys.__iter__()
Vinay Sajip733024a2008-01-21 17:39:22 +00001400
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001401 if __name__ == "__main__":
1402 from random import choice
1403 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1404 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1405 { "ip" : "123.231.231.123", "user" : "sheila" })
1406 logging.basicConfig(level=logging.DEBUG,
1407 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1408 a1.debug("A debug message")
1409 a1.info("An info message with %s", "some parameters")
1410 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1411 for x in range(10):
1412 lvl = choice(levels)
1413 lvlname = logging.getLevelName(lvl)
1414 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Vinay Sajipc7403352008-01-18 15:54:14 +00001415
1416When this script is run, the output should look something like this::
1417
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001418 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1419 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1420 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
1421 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
1422 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
1423 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
1424 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
1425 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1426 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: jim A message at WARNING level with 2 parameters
1427 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
1428 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1429 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Vinay Sajipc7403352008-01-18 15:54:14 +00001430
1431.. versionadded:: 2.6
1432
1433The :class:`LoggerAdapter` class was not present in previous versions.
1434
Vinay Sajip3a0dc302009-08-15 23:23:12 +00001435.. _multiple-processes:
1436
1437Logging to a single file from multiple processes
1438------------------------------------------------
1439
1440Although logging is thread-safe, and logging to a single file from multiple
1441threads in a single process *is* supported, logging to a single file from
1442*multiple processes* is *not* supported, because there is no standard way to
1443serialize access to a single file across multiple processes in Python. If you
1444need to log to a single file from multiple processes, the best way of doing
1445this is to have all the processes log to a :class:`SocketHandler`, and have a
1446separate process which implements a socket server which reads from the socket
1447and logs to file. (If you prefer, you can dedicate one thread in one of the
1448existing processes to perform this function.) The following section documents
1449this approach in more detail and includes a working socket receiver which can
1450be used as a starting point for you to adapt in your own applications.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001451
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001452If you are using a recent version of Python which includes the
1453:mod:`multiprocessing` module, you can write your own handler which uses the
1454:class:`Lock` class from this module to serialize access to the file from
1455your processes. The existing :class:`FileHandler` and subclasses do not make
1456use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip5e7f6452009-08-17 13:14:37 +00001457Note that at present, the :mod:`multiprocessing` module does not provide
1458working lock functionality on all platforms (see
1459http://bugs.python.org/issue3770).
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001460
Georg Brandl8ec7f652007-08-15 14:28:01 +00001461.. _network-logging:
1462
1463Sending and receiving logging events across a network
1464-----------------------------------------------------
1465
1466Let's say you want to send logging events across a network, and handle them at
1467the receiving end. A simple way of doing this is attaching a
1468:class:`SocketHandler` instance to the root logger at the sending end::
1469
Benjamin Petersona7b55a32009-02-20 03:31:23 +00001470 import logging, logging.handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +00001471
1472 rootLogger = logging.getLogger('')
1473 rootLogger.setLevel(logging.DEBUG)
1474 socketHandler = logging.handlers.SocketHandler('localhost',
1475 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1476 # don't bother with a formatter, since a socket handler sends the event as
1477 # an unformatted pickle
1478 rootLogger.addHandler(socketHandler)
1479
1480 # Now, we can log to the root logger, or any other logger. First the root...
1481 logging.info('Jackdaws love my big sphinx of quartz.')
1482
1483 # Now, define a couple of other loggers which might represent areas in your
1484 # application:
1485
1486 logger1 = logging.getLogger('myapp.area1')
1487 logger2 = logging.getLogger('myapp.area2')
1488
1489 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1490 logger1.info('How quickly daft jumping zebras vex.')
1491 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1492 logger2.error('The five boxing wizards jump quickly.')
1493
Georg Brandle152a772008-05-24 18:31:28 +00001494At the receiving end, you can set up a receiver using the :mod:`SocketServer`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001495module. Here is a basic working example::
1496
1497 import cPickle
1498 import logging
1499 import logging.handlers
Georg Brandle152a772008-05-24 18:31:28 +00001500 import SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001501 import struct
1502
1503
Georg Brandle152a772008-05-24 18:31:28 +00001504 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001505 """Handler for a streaming logging request.
1506
1507 This basically logs the record using whatever logging policy is
1508 configured locally.
1509 """
1510
1511 def handle(self):
1512 """
1513 Handle multiple requests - each expected to be a 4-byte length,
1514 followed by the LogRecord in pickle format. Logs the record
1515 according to whatever policy is configured locally.
1516 """
1517 while 1:
1518 chunk = self.connection.recv(4)
1519 if len(chunk) < 4:
1520 break
1521 slen = struct.unpack(">L", chunk)[0]
1522 chunk = self.connection.recv(slen)
1523 while len(chunk) < slen:
1524 chunk = chunk + self.connection.recv(slen - len(chunk))
1525 obj = self.unPickle(chunk)
1526 record = logging.makeLogRecord(obj)
1527 self.handleLogRecord(record)
1528
1529 def unPickle(self, data):
1530 return cPickle.loads(data)
1531
1532 def handleLogRecord(self, record):
1533 # if a name is specified, we use the named logger rather than the one
1534 # implied by the record.
1535 if self.server.logname is not None:
1536 name = self.server.logname
1537 else:
1538 name = record.name
1539 logger = logging.getLogger(name)
1540 # N.B. EVERY record gets logged. This is because Logger.handle
1541 # is normally called AFTER logger-level filtering. If you want
1542 # to do filtering, do it at the client end to save wasting
1543 # cycles and network bandwidth!
1544 logger.handle(record)
1545
Georg Brandle152a772008-05-24 18:31:28 +00001546 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001547 """simple TCP socket-based logging receiver suitable for testing.
1548 """
1549
1550 allow_reuse_address = 1
1551
1552 def __init__(self, host='localhost',
1553 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1554 handler=LogRecordStreamHandler):
Georg Brandle152a772008-05-24 18:31:28 +00001555 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001556 self.abort = 0
1557 self.timeout = 1
1558 self.logname = None
1559
1560 def serve_until_stopped(self):
1561 import select
1562 abort = 0
1563 while not abort:
1564 rd, wr, ex = select.select([self.socket.fileno()],
1565 [], [],
1566 self.timeout)
1567 if rd:
1568 self.handle_request()
1569 abort = self.abort
1570
1571 def main():
1572 logging.basicConfig(
1573 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1574 tcpserver = LogRecordSocketReceiver()
1575 print "About to start TCP server..."
1576 tcpserver.serve_until_stopped()
1577
1578 if __name__ == "__main__":
1579 main()
1580
1581First run the server, and then the client. On the client side, nothing is
1582printed on the console; on the server side, you should see something like::
1583
1584 About to start TCP server...
1585 59 root INFO Jackdaws love my big sphinx of quartz.
1586 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1587 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1588 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1589 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1590
Vinay Sajipf778bec2009-09-22 17:23:41 +00001591Using arbitrary objects as messages
1592-----------------------------------
1593
1594In the preceding sections and examples, it has been assumed that the message
1595passed when logging the event is a string. However, this is not the only
1596possibility. You can pass an arbitrary object as a message, and its
1597:meth:`__str__` method will be called when the logging system needs to convert
1598it to a string representation. In fact, if you want to, you can avoid
1599computing a string representation altogether - for example, the
1600:class:`SocketHandler` emits an event by pickling it and sending it over the
1601wire.
1602
1603Optimization
1604------------
1605
1606Formatting of message arguments is deferred until it cannot be avoided.
1607However, computing the arguments passed to the logging method can also be
1608expensive, and you may want to avoid doing it if the logger will just throw
1609away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1610method which takes a level argument and returns true if the event would be
1611created by the Logger for that level of call. You can write code like this::
1612
1613 if logger.isEnabledFor(logging.DEBUG):
1614 logger.debug("Message with %s, %s", expensive_func1(),
1615 expensive_func2())
1616
1617so that if the logger's threshold is set above ``DEBUG``, the calls to
1618:func:`expensive_func1` and :func:`expensive_func2` are never made.
1619
1620There are other optimizations which can be made for specific applications which
1621need more precise control over what logging information is collected. Here's a
1622list of things you can do to avoid processing during logging which you don't
1623need:
1624
1625+-----------------------------------------------+----------------------------------------+
1626| What you don't want to collect | How to avoid collecting it |
1627+===============================================+========================================+
1628| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1629+-----------------------------------------------+----------------------------------------+
1630| Threading information. | Set ``logging.logThreads`` to ``0``. |
1631+-----------------------------------------------+----------------------------------------+
1632| Process information. | Set ``logging.logProcesses`` to ``0``. |
1633+-----------------------------------------------+----------------------------------------+
1634
1635Also note that the core logging module only includes the basic handlers. If
1636you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1637take up any memory.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001638
Vinay Sajip4b782332009-01-19 06:49:19 +00001639.. _handler:
1640
Georg Brandl8ec7f652007-08-15 14:28:01 +00001641Handler Objects
1642---------------
1643
1644Handlers have the following attributes and methods. Note that :class:`Handler`
1645is never instantiated directly; this class acts as a base for more useful
1646subclasses. However, the :meth:`__init__` method in subclasses needs to call
1647:meth:`Handler.__init__`.
1648
1649
1650.. method:: Handler.__init__(level=NOTSET)
1651
1652 Initializes the :class:`Handler` instance by setting its level, setting the list
1653 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1654 serializing access to an I/O mechanism.
1655
1656
1657.. method:: Handler.createLock()
1658
1659 Initializes a thread lock which can be used to serialize access to underlying
1660 I/O functionality which may not be threadsafe.
1661
1662
1663.. method:: Handler.acquire()
1664
1665 Acquires the thread lock created with :meth:`createLock`.
1666
1667
1668.. method:: Handler.release()
1669
1670 Releases the thread lock acquired with :meth:`acquire`.
1671
1672
1673.. method:: Handler.setLevel(lvl)
1674
1675 Sets the threshold for this handler to *lvl*. Logging messages which are less
1676 severe than *lvl* will be ignored. When a handler is created, the level is set
1677 to :const:`NOTSET` (which causes all messages to be processed).
1678
1679
1680.. method:: Handler.setFormatter(form)
1681
1682 Sets the :class:`Formatter` for this handler to *form*.
1683
1684
1685.. method:: Handler.addFilter(filt)
1686
1687 Adds the specified filter *filt* to this handler.
1688
1689
1690.. method:: Handler.removeFilter(filt)
1691
1692 Removes the specified filter *filt* from this handler.
1693
1694
1695.. method:: Handler.filter(record)
1696
1697 Applies this handler's filters to the record and returns a true value if the
1698 record is to be processed.
1699
1700
1701.. method:: Handler.flush()
1702
1703 Ensure all logging output has been flushed. This version does nothing and is
1704 intended to be implemented by subclasses.
1705
1706
1707.. method:: Handler.close()
1708
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001709 Tidy up any resources used by the handler. This version does no output but
1710 removes the handler from an internal list of handlers which is closed when
1711 :func:`shutdown` is called. Subclasses should ensure that this gets called
1712 from overridden :meth:`close` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001713
1714
1715.. method:: Handler.handle(record)
1716
1717 Conditionally emits the specified logging record, depending on filters which may
1718 have been added to the handler. Wraps the actual emission of the record with
1719 acquisition/release of the I/O thread lock.
1720
1721
1722.. method:: Handler.handleError(record)
1723
1724 This method should be called from handlers when an exception is encountered
1725 during an :meth:`emit` call. By default it does nothing, which means that
1726 exceptions get silently ignored. This is what is mostly wanted for a logging
1727 system - most users will not care about errors in the logging system, they are
1728 more interested in application errors. You could, however, replace this with a
1729 custom handler if you wish. The specified record is the one which was being
1730 processed when the exception occurred.
1731
1732
1733.. method:: Handler.format(record)
1734
1735 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1736 default formatter for the module.
1737
1738
1739.. method:: Handler.emit(record)
1740
1741 Do whatever it takes to actually log the specified logging record. This version
1742 is intended to be implemented by subclasses and so raises a
1743 :exc:`NotImplementedError`.
1744
1745
Vinay Sajip4b782332009-01-19 06:49:19 +00001746.. _stream-handler:
1747
Georg Brandl8ec7f652007-08-15 14:28:01 +00001748StreamHandler
1749^^^^^^^^^^^^^
1750
1751The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1752sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1753file-like object (or, more precisely, any object which supports :meth:`write`
1754and :meth:`flush` methods).
1755
1756
Vinay Sajip0c6a0e32009-12-17 14:52:00 +00001757.. currentmodule:: logging
1758
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001759.. class:: StreamHandler([stream])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001760
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001761 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001762 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1763 will be used.
1764
1765
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001766 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001767
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001768 If a formatter is specified, it is used to format the record. The record
1769 is then written to the stream with a trailing newline. If exception
1770 information is present, it is formatted using
1771 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001772
1773
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001774 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001775
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001776 Flushes the stream by calling its :meth:`flush` method. Note that the
1777 :meth:`close` method is inherited from :class:`Handler` and so does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001778 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001779
1780
Vinay Sajip4b782332009-01-19 06:49:19 +00001781.. _file-handler:
1782
Georg Brandl8ec7f652007-08-15 14:28:01 +00001783FileHandler
1784^^^^^^^^^^^
1785
1786The :class:`FileHandler` class, located in the core :mod:`logging` package,
1787sends logging output to a disk file. It inherits the output functionality from
1788:class:`StreamHandler`.
1789
1790
Vinay Sajipf38ba782008-01-24 12:38:30 +00001791.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001792
1793 Returns a new instance of the :class:`FileHandler` class. The specified file is
1794 opened and used as the stream for logging. If *mode* is not specified,
1795 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001796 with that encoding. If *delay* is true, then file opening is deferred until the
1797 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001798
Vinay Sajip59584c42009-08-14 11:33:54 +00001799 .. versionchanged:: 2.6
1800 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001801
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001802 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001803
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001804 Closes the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001805
1806
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001807 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001808
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001809 Outputs the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001810
Vinay Sajip4b782332009-01-19 06:49:19 +00001811.. _null-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001812
Vinay Sajip51104862009-01-02 18:53:04 +00001813NullHandler
1814^^^^^^^^^^^
1815
1816.. versionadded:: 2.7
1817
1818The :class:`NullHandler` class, located in the core :mod:`logging` package,
1819does not do any formatting or output. It is essentially a "no-op" handler
1820for use by library developers.
1821
1822
1823.. class:: NullHandler()
1824
1825 Returns a new instance of the :class:`NullHandler` class.
1826
1827
1828 .. method:: emit(record)
1829
1830 This method does nothing.
1831
Vinay Sajip99505c82009-01-10 13:38:04 +00001832See :ref:`library-config` for more information on how to use
1833:class:`NullHandler`.
1834
Vinay Sajip4b782332009-01-19 06:49:19 +00001835.. _watched-file-handler:
1836
Georg Brandl8ec7f652007-08-15 14:28:01 +00001837WatchedFileHandler
1838^^^^^^^^^^^^^^^^^^
1839
1840.. versionadded:: 2.6
1841
Vinay Sajipb1a15e42009-01-15 23:04:47 +00001842.. currentmodule:: logging.handlers
Vinay Sajip51104862009-01-02 18:53:04 +00001843
Georg Brandl8ec7f652007-08-15 14:28:01 +00001844The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1845module, is a :class:`FileHandler` which watches the file it is logging to. If
1846the file changes, it is closed and reopened using the file name.
1847
1848A file change can happen because of usage of programs such as *newsyslog* and
1849*logrotate* which perform log file rotation. This handler, intended for use
1850under Unix/Linux, watches the file to see if it has changed since the last emit.
1851(A file is deemed to have changed if its device or inode have changed.) If the
1852file has changed, the old file stream is closed, and the file opened to get a
1853new stream.
1854
1855This handler is not appropriate for use under Windows, because under Windows
1856open log files cannot be moved or renamed - logging opens the files with
1857exclusive locks - and so there is no need for such a handler. Furthermore,
1858*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1859this value.
1860
1861
Vinay Sajipf38ba782008-01-24 12:38:30 +00001862.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001863
1864 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1865 file is opened and used as the stream for logging. If *mode* is not specified,
1866 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001867 with that encoding. If *delay* is true, then file opening is deferred until the
1868 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001869
Vinay Sajip59584c42009-08-14 11:33:54 +00001870 .. versionchanged:: 2.6
1871 *delay* was added.
1872
Georg Brandl8ec7f652007-08-15 14:28:01 +00001873
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001874 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001875
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001876 Outputs the record to the file, but first checks to see if the file has
1877 changed. If it has, the existing stream is flushed and closed and the
1878 file opened again, before outputting the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001879
Vinay Sajip4b782332009-01-19 06:49:19 +00001880.. _rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001881
1882RotatingFileHandler
1883^^^^^^^^^^^^^^^^^^^
1884
1885The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1886module, supports rotation of disk log files.
1887
1888
Vinay Sajipf38ba782008-01-24 12:38:30 +00001889.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001890
1891 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1892 file is opened and used as the stream for logging. If *mode* is not specified,
Vinay Sajipf38ba782008-01-24 12:38:30 +00001893 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
1894 with that encoding. If *delay* is true, then file opening is deferred until the
1895 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001896
1897 You can use the *maxBytes* and *backupCount* values to allow the file to
1898 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1899 the file is closed and a new file is silently opened for output. Rollover occurs
1900 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1901 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1902 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1903 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1904 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1905 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1906 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1907 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1908 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1909
Vinay Sajip59584c42009-08-14 11:33:54 +00001910 .. versionchanged:: 2.6
1911 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001912
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001913 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001914
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001915 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001916
1917
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001918 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001919
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001920 Outputs the record to the file, catering for rollover as described
1921 previously.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001922
Vinay Sajip4b782332009-01-19 06:49:19 +00001923.. _timed-rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001924
1925TimedRotatingFileHandler
1926^^^^^^^^^^^^^^^^^^^^^^^^
1927
1928The :class:`TimedRotatingFileHandler` class, located in the
1929:mod:`logging.handlers` module, supports rotation of disk log files at certain
1930timed intervals.
1931
1932
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001933.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001934
1935 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1936 specified file is opened and used as the stream for logging. On rotating it also
1937 sets the filename suffix. Rotating happens based on the product of *when* and
1938 *interval*.
1939
1940 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandld77554f2008-06-06 07:34:50 +00001941 values is below. Note that they are not case sensitive.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001942
Georg Brandl72780a42008-03-02 13:41:39 +00001943 +----------------+-----------------------+
1944 | Value | Type of interval |
1945 +================+=======================+
1946 | ``'S'`` | Seconds |
1947 +----------------+-----------------------+
1948 | ``'M'`` | Minutes |
1949 +----------------+-----------------------+
1950 | ``'H'`` | Hours |
1951 +----------------+-----------------------+
1952 | ``'D'`` | Days |
1953 +----------------+-----------------------+
1954 | ``'W'`` | Week day (0=Monday) |
1955 +----------------+-----------------------+
1956 | ``'midnight'`` | Roll over at midnight |
1957 +----------------+-----------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001958
Georg Brandle6dab2a2008-03-02 14:15:04 +00001959 The system will save old log files by appending extensions to the filename.
1960 The extensions are date-and-time based, using the strftime format
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001961 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Vinay Sajip2a649f92008-07-18 09:00:35 +00001962 rollover interval.
Vinay Sajipecfa08f2010-03-12 09:16:10 +00001963
1964 When computing the next rollover time for the first time (when the handler
1965 is created), the last modification time of an existing log file, or else
1966 the current time, is used to compute when the next rotation will occur.
1967
Georg Brandld77554f2008-06-06 07:34:50 +00001968 If the *utc* argument is true, times in UTC will be used; otherwise
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001969 local time is used.
1970
1971 If *backupCount* is nonzero, at most *backupCount* files
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001972 will be kept, and if more would be created when rollover occurs, the oldest
1973 one is deleted. The deletion logic uses the interval to determine which
1974 files to delete, so changing the interval may leave old files lying around.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001975
Vinay Sajip59584c42009-08-14 11:33:54 +00001976 If *delay* is true, then file opening is deferred until the first call to
1977 :meth:`emit`.
1978
1979 .. versionchanged:: 2.6
1980 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001981
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001982 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001983
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001984 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001985
1986
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001987 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001988
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001989 Outputs the record to the file, catering for rollover as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001990
1991
Vinay Sajip4b782332009-01-19 06:49:19 +00001992.. _socket-handler:
1993
Georg Brandl8ec7f652007-08-15 14:28:01 +00001994SocketHandler
1995^^^^^^^^^^^^^
1996
1997The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
1998sends logging output to a network socket. The base class uses a TCP socket.
1999
2000
2001.. class:: SocketHandler(host, port)
2002
2003 Returns a new instance of the :class:`SocketHandler` class intended to
2004 communicate with a remote machine whose address is given by *host* and *port*.
2005
2006
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002007 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002008
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002009 Closes the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002010
2011
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002012 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002013
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002014 Pickles the record's attribute dictionary and writes it to the socket in
2015 binary format. If there is an error with the socket, silently drops the
2016 packet. If the connection was previously lost, re-establishes the
2017 connection. To unpickle the record at the receiving end into a
2018 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002019
2020
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002021 .. method:: handleError()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002022
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002023 Handles an error which has occurred during :meth:`emit`. The most likely
2024 cause is a lost connection. Closes the socket so that we can retry on the
2025 next event.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002026
2027
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002028 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002029
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002030 This is a factory method which allows subclasses to define the precise
2031 type of socket they want. The default implementation creates a TCP socket
2032 (:const:`socket.SOCK_STREAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002033
2034
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002035 .. method:: makePickle(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002037 Pickles the record's attribute dictionary in binary format with a length
2038 prefix, and returns it ready for transmission across the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002039
2040
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002041 .. method:: send(packet)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002042
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002043 Send a pickled string *packet* to the socket. This function allows for
2044 partial sends which can happen when the network is busy.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002045
2046
Vinay Sajip4b782332009-01-19 06:49:19 +00002047.. _datagram-handler:
2048
Georg Brandl8ec7f652007-08-15 14:28:01 +00002049DatagramHandler
2050^^^^^^^^^^^^^^^
2051
2052The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2053module, inherits from :class:`SocketHandler` to support sending logging messages
2054over UDP sockets.
2055
2056
2057.. class:: DatagramHandler(host, port)
2058
2059 Returns a new instance of the :class:`DatagramHandler` class intended to
2060 communicate with a remote machine whose address is given by *host* and *port*.
2061
2062
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002063 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002064
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002065 Pickles the record's attribute dictionary and writes it to the socket in
2066 binary format. If there is an error with the socket, silently drops the
2067 packet. To unpickle the record at the receiving end into a
2068 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002069
2070
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002071 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002072
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002073 The factory method of :class:`SocketHandler` is here overridden to create
2074 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002075
2076
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002077 .. method:: send(s)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002078
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002079 Send a pickled string to a socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002080
2081
Vinay Sajip4b782332009-01-19 06:49:19 +00002082.. _syslog-handler:
2083
Georg Brandl8ec7f652007-08-15 14:28:01 +00002084SysLogHandler
2085^^^^^^^^^^^^^
2086
2087The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2088supports sending logging messages to a remote or local Unix syslog.
2089
2090
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002091.. class:: SysLogHandler([address[, facility[, socktype]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002092
2093 Returns a new instance of the :class:`SysLogHandler` class intended to
2094 communicate with a remote Unix machine whose address is given by *address* in
2095 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002096 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl8ec7f652007-08-15 14:28:01 +00002097 alternative to providing a ``(host, port)`` tuple is providing an address as a
2098 string, for example "/dev/log". In this case, a Unix domain socket is used to
2099 send the message to the syslog. If *facility* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002100 :const:`LOG_USER` is used. The type of socket opened depends on the
2101 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2102 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2103 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2104
2105 .. versionchanged:: 2.7
2106 *socktype* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002107
2108
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002109 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002110
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002111 Closes the socket to the remote host.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002112
2113
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002114 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002115
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002116 The record is formatted, and then sent to the syslog server. If exception
2117 information is present, it is *not* sent to the server.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002118
2119
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002120 .. method:: encodePriority(facility, priority)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002121
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002122 Encodes the facility and priority into an integer. You can pass in strings
2123 or integers - if strings are passed, internal mapping dictionaries are
2124 used to convert them to integers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002125
Vinay Sajipa3c39c02010-03-24 15:10:40 +00002126 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2127 mirror the values defined in the ``sys/syslog.h`` header file.
Vinay Sajipb0623d62010-03-24 14:31:21 +00002128
Georg Brandld3bab6a2010-04-02 09:03:18 +00002129 **Priorities**
2130
Vinay Sajipb0623d62010-03-24 14:31:21 +00002131 +--------------------------+---------------+
2132 | Name (string) | Symbolic value|
2133 +==========================+===============+
2134 | ``alert`` | LOG_ALERT |
2135 +--------------------------+---------------+
2136 | ``crit`` or ``critical`` | LOG_CRIT |
2137 +--------------------------+---------------+
2138 | ``debug`` | LOG_DEBUG |
2139 +--------------------------+---------------+
2140 | ``emerg`` or ``panic`` | LOG_EMERG |
2141 +--------------------------+---------------+
2142 | ``err`` or ``error`` | LOG_ERR |
2143 +--------------------------+---------------+
2144 | ``info`` | LOG_INFO |
2145 +--------------------------+---------------+
2146 | ``notice`` | LOG_NOTICE |
2147 +--------------------------+---------------+
2148 | ``warn`` or ``warning`` | LOG_WARNING |
2149 +--------------------------+---------------+
2150
Georg Brandld3bab6a2010-04-02 09:03:18 +00002151 **Facilities**
2152
Vinay Sajipb0623d62010-03-24 14:31:21 +00002153 +---------------+---------------+
2154 | Name (string) | Symbolic value|
2155 +===============+===============+
2156 | ``auth`` | LOG_AUTH |
2157 +---------------+---------------+
2158 | ``authpriv`` | LOG_AUTHPRIV |
2159 +---------------+---------------+
2160 | ``cron`` | LOG_CRON |
2161 +---------------+---------------+
2162 | ``daemon`` | LOG_DAEMON |
2163 +---------------+---------------+
2164 | ``ftp`` | LOG_FTP |
2165 +---------------+---------------+
2166 | ``kern`` | LOG_KERN |
2167 +---------------+---------------+
2168 | ``lpr`` | LOG_LPR |
2169 +---------------+---------------+
2170 | ``mail`` | LOG_MAIL |
2171 +---------------+---------------+
2172 | ``news`` | LOG_NEWS |
2173 +---------------+---------------+
2174 | ``syslog`` | LOG_SYSLOG |
2175 +---------------+---------------+
2176 | ``user`` | LOG_USER |
2177 +---------------+---------------+
2178 | ``uucp`` | LOG_UUCP |
2179 +---------------+---------------+
2180 | ``local0`` | LOG_LOCAL0 |
2181 +---------------+---------------+
2182 | ``local1`` | LOG_LOCAL1 |
2183 +---------------+---------------+
2184 | ``local2`` | LOG_LOCAL2 |
2185 +---------------+---------------+
2186 | ``local3`` | LOG_LOCAL3 |
2187 +---------------+---------------+
2188 | ``local4`` | LOG_LOCAL4 |
2189 +---------------+---------------+
2190 | ``local5`` | LOG_LOCAL5 |
2191 +---------------+---------------+
2192 | ``local6`` | LOG_LOCAL6 |
2193 +---------------+---------------+
2194 | ``local7`` | LOG_LOCAL7 |
2195 +---------------+---------------+
2196
Vinay Sajip66d19e22010-03-24 17:36:35 +00002197 .. method:: mapPriority(levelname)
2198
2199 Maps a logging level name to a syslog priority name.
2200 You may need to override this if you are using custom levels, or
2201 if the default algorithm is not suitable for your needs. The
2202 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2203 ``CRITICAL`` to the equivalent syslog names, and all other level
2204 names to "warning".
Georg Brandl8ec7f652007-08-15 14:28:01 +00002205
Vinay Sajip4b782332009-01-19 06:49:19 +00002206.. _nt-eventlog-handler:
2207
Georg Brandl8ec7f652007-08-15 14:28:01 +00002208NTEventLogHandler
2209^^^^^^^^^^^^^^^^^
2210
2211The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2212module, supports sending logging messages to a local Windows NT, Windows 2000 or
2213Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2214extensions for Python installed.
2215
2216
2217.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
2218
2219 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2220 used to define the application name as it appears in the event log. An
2221 appropriate registry entry is created using this name. The *dllname* should give
2222 the fully qualified pathname of a .dll or .exe which contains message
2223 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2224 - this is installed with the Win32 extensions and contains some basic
2225 placeholder message definitions. Note that use of these placeholders will make
2226 your event logs big, as the entire message source is held in the log. If you
2227 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2228 contains the message definitions you want to use in the event log). The
2229 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2230 defaults to ``'Application'``.
2231
2232
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002233 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002234
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002235 At this point, you can remove the application name from the registry as a
2236 source of event log entries. However, if you do this, you will not be able
2237 to see the events as you intended in the Event Log Viewer - it needs to be
2238 able to access the registry to get the .dll name. The current version does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00002239 not do this.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002240
2241
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002242 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002243
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002244 Determines the message ID, event category and event type, and then logs
2245 the message in the NT event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002246
2247
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002248 .. method:: getEventCategory(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002249
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002250 Returns the event category for the record. Override this if you want to
2251 specify your own categories. This version returns 0.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002252
2253
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002254 .. method:: getEventType(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002255
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002256 Returns the event type for the record. Override this if you want to
2257 specify your own types. This version does a mapping using the handler's
2258 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2259 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2260 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2261 your own levels, you will either need to override this method or place a
2262 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002263
2264
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002265 .. method:: getMessageID(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002266
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002267 Returns the message ID for the record. If you are using your own messages,
2268 you could do this by having the *msg* passed to the logger being an ID
2269 rather than a format string. Then, in here, you could use a dictionary
2270 lookup to get the message ID. This version returns 1, which is the base
2271 message ID in :file:`win32service.pyd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002272
Vinay Sajip4b782332009-01-19 06:49:19 +00002273.. _smtp-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002274
2275SMTPHandler
2276^^^^^^^^^^^
2277
2278The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2279supports sending logging messages to an email address via SMTP.
2280
2281
2282.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
2283
2284 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2285 initialized with the from and to addresses and subject line of the email. The
2286 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2287 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2288 the standard SMTP port is used. If your SMTP server requires authentication, you
2289 can specify a (username, password) tuple for the *credentials* argument.
2290
2291 .. versionchanged:: 2.6
2292 *credentials* was added.
2293
2294
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002295 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002296
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002297 Formats the record and sends it to the specified addressees.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002298
2299
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002300 .. method:: getSubject(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002301
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002302 If you want to specify a subject line which is record-dependent, override
2303 this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002304
Vinay Sajip4b782332009-01-19 06:49:19 +00002305.. _memory-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002306
2307MemoryHandler
2308^^^^^^^^^^^^^
2309
2310The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2311supports buffering of logging records in memory, periodically flushing them to a
2312:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2313event of a certain severity or greater is seen.
2314
2315:class:`MemoryHandler` is a subclass of the more general
2316:class:`BufferingHandler`, which is an abstract class. This buffers logging
2317records in memory. Whenever each record is added to the buffer, a check is made
2318by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2319should, then :meth:`flush` is expected to do the needful.
2320
2321
2322.. class:: BufferingHandler(capacity)
2323
2324 Initializes the handler with a buffer of the specified capacity.
2325
2326
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002327 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002328
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002329 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2330 calls :meth:`flush` to process the buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002331
2332
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002333 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002334
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002335 You can override this to implement custom flushing behavior. This version
2336 just zaps the buffer to empty.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002337
2338
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002339 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002340
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002341 Returns true if the buffer is up to capacity. This method can be
2342 overridden to implement custom flushing strategies.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002343
2344
2345.. class:: MemoryHandler(capacity[, flushLevel [, target]])
2346
2347 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2348 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2349 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2350 set using :meth:`setTarget` before this handler does anything useful.
2351
2352
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002353 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002354
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002355 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2356 buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002357
2358
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002359 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002360
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002361 For a :class:`MemoryHandler`, flushing means just sending the buffered
2362 records to the target, if there is one. Override if you want different
2363 behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002364
2365
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002366 .. method:: setTarget(target)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002367
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002368 Sets the target handler for this handler.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002369
2370
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002371 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002372
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002373 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002374
2375
Vinay Sajip4b782332009-01-19 06:49:19 +00002376.. _http-handler:
2377
Georg Brandl8ec7f652007-08-15 14:28:01 +00002378HTTPHandler
2379^^^^^^^^^^^
2380
2381The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2382supports sending logging messages to a Web server, using either ``GET`` or
2383``POST`` semantics.
2384
2385
2386.. class:: HTTPHandler(host, url[, method])
2387
2388 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2389 initialized with a host address, url and HTTP method. The *host* can be of the
2390 form ``host:port``, should you need to use a specific port number. If no
2391 *method* is specified, ``GET`` is used.
2392
2393
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002394 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002395
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002396 Sends the record to the Web server as an URL-encoded dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002397
2398
Vinay Sajip4b782332009-01-19 06:49:19 +00002399.. _formatter:
Georg Brandlc37f2882007-12-04 17:46:27 +00002400
Georg Brandl8ec7f652007-08-15 14:28:01 +00002401Formatter Objects
2402-----------------
2403
Georg Brandl430effb2009-01-01 13:05:13 +00002404.. currentmodule:: logging
2405
Georg Brandl8ec7f652007-08-15 14:28:01 +00002406:class:`Formatter`\ s have the following attributes and methods. They are
2407responsible for converting a :class:`LogRecord` to (usually) a string which can
2408be interpreted by either a human or an external system. The base
2409:class:`Formatter` allows a formatting string to be specified. If none is
2410supplied, the default value of ``'%(message)s'`` is used.
2411
2412A Formatter can be initialized with a format string which makes use of knowledge
2413of the :class:`LogRecord` attributes - such as the default value mentioned above
2414making use of the fact that the user's message and arguments are pre-formatted
2415into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti062d2b52009-12-19 22:41:49 +00002416standard Python %-style mapping keys. See section :ref:`string-formatting`
Georg Brandl8ec7f652007-08-15 14:28:01 +00002417for more information on string formatting.
2418
2419Currently, the useful mapping keys in a :class:`LogRecord` are:
2420
2421+-------------------------+-----------------------------------------------+
2422| Format | Description |
2423+=========================+===============================================+
2424| ``%(name)s`` | Name of the logger (logging channel). |
2425+-------------------------+-----------------------------------------------+
2426| ``%(levelno)s`` | Numeric logging level for the message |
2427| | (:const:`DEBUG`, :const:`INFO`, |
2428| | :const:`WARNING`, :const:`ERROR`, |
2429| | :const:`CRITICAL`). |
2430+-------------------------+-----------------------------------------------+
2431| ``%(levelname)s`` | Text logging level for the message |
2432| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2433| | ``'ERROR'``, ``'CRITICAL'``). |
2434+-------------------------+-----------------------------------------------+
2435| ``%(pathname)s`` | Full pathname of the source file where the |
2436| | logging call was issued (if available). |
2437+-------------------------+-----------------------------------------------+
2438| ``%(filename)s`` | Filename portion of pathname. |
2439+-------------------------+-----------------------------------------------+
2440| ``%(module)s`` | Module (name portion of filename). |
2441+-------------------------+-----------------------------------------------+
2442| ``%(funcName)s`` | Name of function containing the logging call. |
2443+-------------------------+-----------------------------------------------+
2444| ``%(lineno)d`` | Source line number where the logging call was |
2445| | issued (if available). |
2446+-------------------------+-----------------------------------------------+
2447| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2448| | (as returned by :func:`time.time`). |
2449+-------------------------+-----------------------------------------------+
2450| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2451| | created, relative to the time the logging |
2452| | module was loaded. |
2453+-------------------------+-----------------------------------------------+
2454| ``%(asctime)s`` | Human-readable time when the |
2455| | :class:`LogRecord` was created. By default |
2456| | this is of the form "2003-07-08 16:49:45,896" |
2457| | (the numbers after the comma are millisecond |
2458| | portion of the time). |
2459+-------------------------+-----------------------------------------------+
2460| ``%(msecs)d`` | Millisecond portion of the time when the |
2461| | :class:`LogRecord` was created. |
2462+-------------------------+-----------------------------------------------+
2463| ``%(thread)d`` | Thread ID (if available). |
2464+-------------------------+-----------------------------------------------+
2465| ``%(threadName)s`` | Thread name (if available). |
2466+-------------------------+-----------------------------------------------+
2467| ``%(process)d`` | Process ID (if available). |
2468+-------------------------+-----------------------------------------------+
2469| ``%(message)s`` | The logged message, computed as ``msg % |
2470| | args``. |
2471+-------------------------+-----------------------------------------------+
2472
2473.. versionchanged:: 2.5
2474 *funcName* was added.
2475
2476
2477.. class:: Formatter([fmt[, datefmt]])
2478
2479 Returns a new instance of the :class:`Formatter` class. The instance is
2480 initialized with a format string for the message as a whole, as well as a format
2481 string for the date/time portion of a message. If no *fmt* is specified,
2482 ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
2483 is used.
2484
2485
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002486 .. method:: format(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002487
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002488 The record's attribute dictionary is used as the operand to a string
2489 formatting operation. Returns the resulting string. Before formatting the
2490 dictionary, a couple of preparatory steps are carried out. The *message*
2491 attribute of the record is computed using *msg* % *args*. If the
2492 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2493 to format the event time. If there is exception information, it is
2494 formatted using :meth:`formatException` and appended to the message. Note
2495 that the formatted exception information is cached in attribute
2496 *exc_text*. This is useful because the exception information can be
2497 pickled and sent across the wire, but you should be careful if you have
2498 more than one :class:`Formatter` subclass which customizes the formatting
2499 of exception information. In this case, you will have to clear the cached
2500 value after a formatter has done its formatting, so that the next
2501 formatter to handle the event doesn't use the cached value but
2502 recalculates it afresh.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002503
2504
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002505 .. method:: formatTime(record[, datefmt])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002506
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002507 This method should be called from :meth:`format` by a formatter which
2508 wants to make use of a formatted time. This method can be overridden in
2509 formatters to provide for any specific requirement, but the basic behavior
2510 is as follows: if *datefmt* (a string) is specified, it is used with
2511 :func:`time.strftime` to format the creation time of the
2512 record. Otherwise, the ISO8601 format is used. The resulting string is
2513 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002514
2515
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002516 .. method:: formatException(exc_info)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002517
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002518 Formats the specified exception information (a standard exception tuple as
2519 returned by :func:`sys.exc_info`) as a string. This default implementation
2520 just uses :func:`traceback.print_exception`. The resulting string is
2521 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002522
Vinay Sajip4b782332009-01-19 06:49:19 +00002523.. _filter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002524
2525Filter Objects
2526--------------
2527
Vinay Sajip4b782332009-01-19 06:49:19 +00002528Filters can be used by :class:`Handler`\ s and :class:`Logger`\ s for
Georg Brandl8ec7f652007-08-15 14:28:01 +00002529more sophisticated filtering than is provided by levels. The base filter class
2530only allows events which are below a certain point in the logger hierarchy. For
2531example, a filter initialized with "A.B" will allow events logged by loggers
2532"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2533initialized with the empty string, all events are passed.
2534
2535
2536.. class:: Filter([name])
2537
2538 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2539 names a logger which, together with its children, will have its events allowed
2540 through the filter. If no name is specified, allows every event.
2541
2542
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002543 .. method:: filter(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002544
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002545 Is the specified record to be logged? Returns zero for no, nonzero for
2546 yes. If deemed appropriate, the record may be modified in-place by this
2547 method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002548
Vinay Sajip4b782332009-01-19 06:49:19 +00002549.. _log-record:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002550
2551LogRecord Objects
2552-----------------
2553
2554:class:`LogRecord` instances are created every time something is logged. They
2555contain all the information pertinent to the event being logged. The main
2556information passed in is in msg and args, which are combined using msg % args to
2557create the message field of the record. The record also includes information
2558such as when the record was created, the source line where the logging call was
2559made, and any exception information to be logged.
2560
2561
2562.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
2563
2564 Returns an instance of :class:`LogRecord` initialized with interesting
2565 information. The *name* is the logger name; *lvl* is the numeric level;
2566 *pathname* is the absolute pathname of the source file in which the logging
2567 call was made; *lineno* is the line number in that file where the logging
2568 call is found; *msg* is the user-supplied message (a format string); *args*
2569 is the tuple which, together with *msg*, makes up the user message; and
2570 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2571 (or :const:`None`, if no exception information is available). The *func* is
2572 the name of the function from which the logging call was made. If not
2573 specified, it defaults to ``None``.
2574
2575 .. versionchanged:: 2.5
2576 *func* was added.
2577
2578
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002579 .. method:: getMessage()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002580
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002581 Returns the message for this :class:`LogRecord` instance after merging any
2582 user-supplied arguments with the message.
2583
Vinay Sajip4b782332009-01-19 06:49:19 +00002584.. _logger-adapter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002585
Vinay Sajipc7403352008-01-18 15:54:14 +00002586LoggerAdapter Objects
2587---------------------
2588
2589.. versionadded:: 2.6
2590
2591:class:`LoggerAdapter` instances are used to conveniently pass contextual
Vinay Sajip733024a2008-01-21 17:39:22 +00002592information into logging calls. For a usage example , see the section on
2593`adding contextual information to your logging output`__.
2594
2595__ context-info_
Vinay Sajipc7403352008-01-18 15:54:14 +00002596
2597.. class:: LoggerAdapter(logger, extra)
2598
2599 Returns an instance of :class:`LoggerAdapter` initialized with an
2600 underlying :class:`Logger` instance and a dict-like object.
2601
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002602 .. method:: process(msg, kwargs)
Vinay Sajipc7403352008-01-18 15:54:14 +00002603
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002604 Modifies the message and/or keyword arguments passed to a logging call in
2605 order to insert contextual information. This implementation takes the object
2606 passed as *extra* to the constructor and adds it to *kwargs* using key
2607 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2608 (possibly modified) versions of the arguments passed in.
Vinay Sajipc7403352008-01-18 15:54:14 +00002609
2610In addition to the above, :class:`LoggerAdapter` supports all the logging
2611methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2612:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2613methods have the same signatures as their counterparts in :class:`Logger`, so
2614you can use the two types of instances interchangeably.
2615
Vinay Sajip804899b2010-03-22 15:29:01 +00002616.. versionchanged:: 2.7
2617
2618The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method
2619delegates to the underlying logger.
2620
Georg Brandl8ec7f652007-08-15 14:28:01 +00002621
2622Thread Safety
2623-------------
2624
2625The logging module is intended to be thread-safe without any special work
2626needing to be done by its clients. It achieves this though using threading
2627locks; there is one lock to serialize access to the module's shared data, and
2628each handler also creates a lock to serialize access to its underlying I/O.
2629
Vinay Sajip353a85f2009-04-03 21:58:16 +00002630If you are implementing asynchronous signal handlers using the :mod:`signal`
2631module, you may not be able to use logging from within such handlers. This is
2632because lock implementations in the :mod:`threading` module are not always
2633re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002634
Vinay Sajip61afd262010-02-19 23:53:17 +00002635
2636Integration with the warnings module
2637------------------------------------
2638
2639The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2640with the :mod:`warnings` module.
2641
2642.. function:: captureWarnings(capture)
2643
2644 This function is used to turn the capture of warnings by logging on and
2645 off.
2646
Georg Brandlf6d367452010-03-12 10:02:03 +00002647 If *capture* is ``True``, warnings issued by the :mod:`warnings` module
Vinay Sajip61afd262010-02-19 23:53:17 +00002648 will be redirected to the logging system. Specifically, a warning will be
2649 formatted using :func:`warnings.formatwarning` and the resulting string
Georg Brandlf6d367452010-03-12 10:02:03 +00002650 logged to a logger named "py.warnings" with a severity of ``WARNING``.
Vinay Sajip61afd262010-02-19 23:53:17 +00002651
Georg Brandlf6d367452010-03-12 10:02:03 +00002652 If *capture* is ``False``, the redirection of warnings to the logging system
Vinay Sajip61afd262010-02-19 23:53:17 +00002653 will stop, and warnings will be redirected to their original destinations
Georg Brandlf6d367452010-03-12 10:02:03 +00002654 (i.e. those in effect before ``captureWarnings(True)`` was called).
Vinay Sajip61afd262010-02-19 23:53:17 +00002655
2656
Georg Brandl8ec7f652007-08-15 14:28:01 +00002657Configuration
2658-------------
2659
2660
2661.. _logging-config-api:
2662
2663Configuration functions
2664^^^^^^^^^^^^^^^^^^^^^^^
2665
Georg Brandl8ec7f652007-08-15 14:28:01 +00002666The following functions configure the logging module. They are located in the
2667:mod:`logging.config` module. Their use is optional --- you can configure the
2668logging module using these functions or by making calls to the main API (defined
2669in :mod:`logging` itself) and defining handlers which are declared either in
2670:mod:`logging` or :mod:`logging.handlers`.
2671
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002672.. function:: dictConfig(config)
2673
2674 Takes the logging configuration from a dictionary. The contents of
2675 this dictionary are described in :ref:`logging-config-dictschema`
2676 below.
2677
2678 If an error is encountered during configuration, this function will
2679 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2680 or :exc:`ImportError` with a suitably descriptive message. The
2681 following is a (possibly incomplete) list of conditions which will
2682 raise an error:
2683
2684 * A ``level`` which is not a string or which is a string not
2685 corresponding to an actual logging level.
2686 * A ``propagate`` value which is not a boolean.
2687 * An id which does not have a corresponding destination.
2688 * A non-existent handler id found during an incremental call.
2689 * An invalid logger name.
2690 * Inability to resolve to an internal or external object.
2691
2692 Parsing is performed by the :class:`DictConfigurator` class, whose
2693 constructor is passed the dictionary used for configuration, and
2694 has a :meth:`configure` method. The :mod:`logging.config` module
2695 has a callable attribute :attr:`dictConfigClass`
2696 which is initially set to :class:`DictConfigurator`.
2697 You can replace the value of :attr:`dictConfigClass` with a
2698 suitable implementation of your own.
2699
2700 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2701 the specified dictionary, and then calls the :meth:`configure` method on
2702 the returned object to put the configuration into effect::
2703
2704 def dictConfig(config):
2705 dictConfigClass(config).configure()
2706
2707 For example, a subclass of :class:`DictConfigurator` could call
2708 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2709 set up custom prefixes which would be usable in the subsequent
2710 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2711 this new subclass, and then :func:`dictConfig` could be called exactly as
2712 in the default, uncustomized state.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002713
2714.. function:: fileConfig(fname[, defaults])
2715
Vinay Sajip51104862009-01-02 18:53:04 +00002716 Reads the logging configuration from a :mod:`ConfigParser`\-format file named
2717 *fname*. This function can be called several times from an application,
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002718 allowing an end user to select from various pre-canned
Vinay Sajip51104862009-01-02 18:53:04 +00002719 configurations (if the developer provides a mechanism to present the choices
2720 and load the chosen configuration). Defaults to be passed to the ConfigParser
2721 can be specified in the *defaults* argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002722
Georg Brandl8ec7f652007-08-15 14:28:01 +00002723.. function:: listen([port])
2724
2725 Starts up a socket server on the specified port, and listens for new
2726 configurations. If no port is specified, the module's default
2727 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2728 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2729 :class:`Thread` instance on which you can call :meth:`start` to start the
2730 server, and which you can :meth:`join` when appropriate. To stop the server,
Georg Brandlc37f2882007-12-04 17:46:27 +00002731 call :func:`stopListening`.
2732
2733 To send a configuration to the socket, read in the configuration file and
2734 send it to the socket as a string of bytes preceded by a four-byte length
2735 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002736
2737
2738.. function:: stopListening()
2739
Georg Brandlc37f2882007-12-04 17:46:27 +00002740 Stops the listening server which was created with a call to :func:`listen`.
2741 This is typically called before calling :meth:`join` on the return value from
Georg Brandl8ec7f652007-08-15 14:28:01 +00002742 :func:`listen`.
2743
2744
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002745.. _logging-config-dictschema:
2746
2747Configuration dictionary schema
2748^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2749
2750Describing a logging configuration requires listing the various
2751objects to create and the connections between them; for example, you
2752may create a handler named "console" and then say that the logger
2753named "startup" will send its messages to the "console" handler.
2754These objects aren't limited to those provided by the :mod:`logging`
2755module because you might write your own formatter or handler class.
2756The parameters to these classes may also need to include external
2757objects such as ``sys.stderr``. The syntax for describing these
2758objects and connections is defined in :ref:`logging-config-dict-connections`
2759below.
2760
2761Dictionary Schema Details
2762"""""""""""""""""""""""""
2763
2764The dictionary passed to :func:`dictConfig` must contain the following
2765keys:
2766
2767* `version` - to be set to an integer value representing the schema
2768 version. The only valid value at present is 1, but having this key
2769 allows the schema to evolve while still preserving backwards
2770 compatibility.
2771
2772All other keys are optional, but if present they will be interpreted
2773as described below. In all cases below where a 'configuring dict' is
2774mentioned, it will be checked for the special ``'()'`` key to see if a
Andrew M. Kuchling1b553472010-05-16 23:31:16 +00002775custom instantiation is required. If so, the mechanism described in
2776:ref:`logging-config-dict-userdef` below is used to create an instance;
2777otherwise, the context is used to determine what to instantiate.
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002778
2779* `formatters` - the corresponding value will be a dict in which each
2780 key is a formatter id and each value is a dict describing how to
2781 configure the corresponding Formatter instance.
2782
2783 The configuring dict is searched for keys ``format`` and ``datefmt``
2784 (with defaults of ``None``) and these are used to construct a
2785 :class:`logging.Formatter` instance.
2786
2787* `filters` - the corresponding value will be a dict in which each key
2788 is a filter id and each value is a dict describing how to configure
2789 the corresponding Filter instance.
2790
2791 The configuring dict is searched for the key ``name`` (defaulting to the
2792 empty string) and this is used to construct a :class:`logging.Filter`
2793 instance.
2794
2795* `handlers` - the corresponding value will be a dict in which each
2796 key is a handler id and each value is a dict describing how to
2797 configure the corresponding Handler instance.
2798
2799 The configuring dict is searched for the following keys:
2800
2801 * ``class`` (mandatory). This is the fully qualified name of the
2802 handler class.
2803
2804 * ``level`` (optional). The level of the handler.
2805
2806 * ``formatter`` (optional). The id of the formatter for this
2807 handler.
2808
2809 * ``filters`` (optional). A list of ids of the filters for this
2810 handler.
2811
2812 All *other* keys are passed through as keyword arguments to the
2813 handler's constructor. For example, given the snippet::
2814
2815 handlers:
2816 console:
2817 class : logging.StreamHandler
2818 formatter: brief
2819 level : INFO
2820 filters: [allow_foo]
2821 stream : ext://sys.stdout
2822 file:
2823 class : logging.handlers.RotatingFileHandler
2824 formatter: precise
2825 filename: logconfig.log
2826 maxBytes: 1024
2827 backupCount: 3
2828
2829 the handler with id ``console`` is instantiated as a
2830 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
2831 stream. The handler with id ``file`` is instantiated as a
2832 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
2833 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
2834
2835* `loggers` - the corresponding value will be a dict in which each key
2836 is a logger name and each value is a dict describing how to
2837 configure the corresponding Logger instance.
2838
2839 The configuring dict is searched for the following keys:
2840
2841 * ``level`` (optional). The level of the logger.
2842
2843 * ``propagate`` (optional). The propagation setting of the logger.
2844
2845 * ``filters`` (optional). A list of ids of the filters for this
2846 logger.
2847
2848 * ``handlers`` (optional). A list of ids of the handlers for this
2849 logger.
2850
2851 The specified loggers will be configured according to the level,
2852 propagation, filters and handlers specified.
2853
2854* `root` - this will be the configuration for the root logger.
2855 Processing of the configuration will be as for any logger, except
2856 that the ``propagate`` setting will not be applicable.
2857
2858* `incremental` - whether the configuration is to be interpreted as
2859 incremental to the existing configuration. This value defaults to
2860 ``False``, which means that the specified configuration replaces the
2861 existing configuration with the same semantics as used by the
2862 existing :func:`fileConfig` API.
2863
2864 If the specified value is ``True``, the configuration is processed
2865 as described in the section on :ref:`logging-config-dict-incremental`.
2866
2867* `disable_existing_loggers` - whether any existing loggers are to be
2868 disabled. This setting mirrors the parameter of the same name in
2869 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
2870 This value is ignored if `incremental` is ``True``.
2871
2872.. _logging-config-dict-incremental:
2873
2874Incremental Configuration
2875"""""""""""""""""""""""""
2876
2877It is difficult to provide complete flexibility for incremental
2878configuration. For example, because objects such as filters
2879and formatters are anonymous, once a configuration is set up, it is
2880not possible to refer to such anonymous objects when augmenting a
2881configuration.
2882
2883Furthermore, there is not a compelling case for arbitrarily altering
2884the object graph of loggers, handlers, filters, formatters at
2885run-time, once a configuration is set up; the verbosity of loggers and
2886handlers can be controlled just by setting levels (and, in the case of
2887loggers, propagation flags). Changing the object graph arbitrarily in
2888a safe way is problematic in a multi-threaded environment; while not
2889impossible, the benefits are not worth the complexity it adds to the
2890implementation.
2891
2892Thus, when the ``incremental`` key of a configuration dict is present
2893and is ``True``, the system will completely ignore any ``formatters`` and
2894``filters`` entries, and process only the ``level``
2895settings in the ``handlers`` entries, and the ``level`` and
2896``propagate`` settings in the ``loggers`` and ``root`` entries.
2897
2898Using a value in the configuration dict lets configurations to be sent
2899over the wire as pickled dicts to a socket listener. Thus, the logging
2900verbosity of a long-running application can be altered over time with
2901no need to stop and restart the application.
2902
2903.. _logging-config-dict-connections:
2904
2905Object connections
2906""""""""""""""""""
2907
2908The schema describes a set of logging objects - loggers,
2909handlers, formatters, filters - which are connected to each other in
2910an object graph. Thus, the schema needs to represent connections
2911between the objects. For example, say that, once configured, a
2912particular logger has attached to it a particular handler. For the
2913purposes of this discussion, we can say that the logger represents the
2914source, and the handler the destination, of a connection between the
2915two. Of course in the configured objects this is represented by the
2916logger holding a reference to the handler. In the configuration dict,
2917this is done by giving each destination object an id which identifies
2918it unambiguously, and then using the id in the source object's
2919configuration to indicate that a connection exists between the source
2920and the destination object with that id.
2921
2922So, for example, consider the following YAML snippet::
2923
2924 formatters:
2925 brief:
2926 # configuration for formatter with id 'brief' goes here
2927 precise:
2928 # configuration for formatter with id 'precise' goes here
2929 handlers:
2930 h1: #This is an id
2931 # configuration of handler with id 'h1' goes here
2932 formatter: brief
2933 h2: #This is another id
2934 # configuration of handler with id 'h2' goes here
2935 formatter: precise
2936 loggers:
2937 foo.bar.baz:
2938 # other configuration for logger 'foo.bar.baz'
2939 handlers: [h1, h2]
2940
2941(Note: YAML used here because it's a little more readable than the
2942equivalent Python source form for the dictionary.)
2943
2944The ids for loggers are the logger names which would be used
2945programmatically to obtain a reference to those loggers, e.g.
2946``foo.bar.baz``. The ids for Formatters and Filters can be any string
2947value (such as ``brief``, ``precise`` above) and they are transient,
2948in that they are only meaningful for processing the configuration
2949dictionary and used to determine connections between objects, and are
2950not persisted anywhere when the configuration call is complete.
2951
2952The above snippet indicates that logger named ``foo.bar.baz`` should
2953have two handlers attached to it, which are described by the handler
2954ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
2955``brief``, and the formatter for ``h2`` is that described by id
2956``precise``.
2957
2958
2959.. _logging-config-dict-userdef:
2960
2961User-defined objects
2962""""""""""""""""""""
2963
2964The schema supports user-defined objects for handlers, filters and
2965formatters. (Loggers do not need to have different types for
2966different instances, so there is no support in this configuration
2967schema for user-defined logger classes.)
2968
2969Objects to be configured are described by dictionaries
2970which detail their configuration. In some places, the logging system
2971will be able to infer from the context how an object is to be
2972instantiated, but when a user-defined object is to be instantiated,
2973the system will not know how to do this. In order to provide complete
2974flexibility for user-defined object instantiation, the user needs
2975to provide a 'factory' - a callable which is called with a
2976configuration dictionary and which returns the instantiated object.
2977This is signalled by an absolute import path to the factory being
2978made available under the special key ``'()'``. Here's a concrete
2979example::
2980
2981 formatters:
2982 brief:
2983 format: '%(message)s'
2984 default:
2985 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
2986 datefmt: '%Y-%m-%d %H:%M:%S'
2987 custom:
2988 (): my.package.customFormatterFactory
2989 bar: baz
2990 spam: 99.9
2991 answer: 42
2992
2993The above YAML snippet defines three formatters. The first, with id
2994``brief``, is a standard :class:`logging.Formatter` instance with the
2995specified format string. The second, with id ``default``, has a
2996longer format and also defines the time format explicitly, and will
2997result in a :class:`logging.Formatter` initialized with those two format
2998strings. Shown in Python source form, the ``brief`` and ``default``
2999formatters have configuration sub-dictionaries::
3000
3001 {
3002 'format' : '%(message)s'
3003 }
3004
3005and::
3006
3007 {
3008 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3009 'datefmt' : '%Y-%m-%d %H:%M:%S'
3010 }
3011
3012respectively, and as these dictionaries do not contain the special key
3013``'()'``, the instantiation is inferred from the context: as a result,
3014standard :class:`logging.Formatter` instances are created. The
3015configuration sub-dictionary for the third formatter, with id
3016``custom``, is::
3017
3018 {
3019 '()' : 'my.package.customFormatterFactory',
3020 'bar' : 'baz',
3021 'spam' : 99.9,
3022 'answer' : 42
3023 }
3024
3025and this contains the special key ``'()'``, which means that
3026user-defined instantiation is wanted. In this case, the specified
3027factory callable will be used. If it is an actual callable it will be
3028used directly - otherwise, if you specify a string (as in the example)
3029the actual callable will be located using normal import mechanisms.
3030The callable will be called with the **remaining** items in the
3031configuration sub-dictionary as keyword arguments. In the above
3032example, the formatter with id ``custom`` will be assumed to be
3033returned by the call::
3034
3035 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3036
3037The key ``'()'`` has been used as the special key because it is not a
3038valid keyword parameter name, and so will not clash with the names of
3039the keyword arguments used in the call. The ``'()'`` also serves as a
3040mnemonic that the corresponding value is a callable.
3041
3042
3043.. _logging-config-dict-externalobj:
3044
3045Access to external objects
3046""""""""""""""""""""""""""
3047
3048There are times where a configuration needs to refer to objects
3049external to the configuration, for example ``sys.stderr``. If the
3050configuration dict is constructed using Python code, this is
3051straightforward, but a problem arises when the configuration is
3052provided via a text file (e.g. JSON, YAML). In a text file, there is
3053no standard way to distinguish ``sys.stderr`` from the literal string
3054``'sys.stderr'``. To facilitate this distinction, the configuration
3055system looks for certain special prefixes in string values and
3056treat them specially. For example, if the literal string
3057``'ext://sys.stderr'`` is provided as a value in the configuration,
3058then the ``ext://`` will be stripped off and the remainder of the
3059value processed using normal import mechanisms.
3060
3061The handling of such prefixes is done in a way analogous to protocol
3062handling: there is a generic mechanism to look for prefixes which
3063match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3064whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3065in a prefix-dependent manner and the result of the processing replaces
3066the string value. If the prefix is not recognised, then the string
3067value will be left as-is.
3068
3069
3070.. _logging-config-dict-internalobj:
3071
3072Access to internal objects
3073""""""""""""""""""""""""""
3074
3075As well as external objects, there is sometimes also a need to refer
3076to objects in the configuration. This will be done implicitly by the
3077configuration system for things that it knows about. For example, the
3078string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3079automatically be converted to the value ``logging.DEBUG``, and the
3080``handlers``, ``filters`` and ``formatter`` entries will take an
3081object id and resolve to the appropriate destination object.
3082
3083However, a more generic mechanism is needed for user-defined
3084objects which are not known to the :mod:`logging` module. For
3085example, consider :class:`logging.handlers.MemoryHandler`, which takes
3086a ``target`` argument which is another handler to delegate to. Since
3087the system already knows about this class, then in the configuration,
3088the given ``target`` just needs to be the object id of the relevant
3089target handler, and the system will resolve to the handler from the
3090id. If, however, a user defines a ``my.package.MyHandler`` which has
3091an ``alternate`` handler, the configuration system would not know that
3092the ``alternate`` referred to a handler. To cater for this, a generic
3093resolution system allows the user to specify::
3094
3095 handlers:
3096 file:
3097 # configuration of file handler goes here
3098
3099 custom:
3100 (): my.package.MyHandler
3101 alternate: cfg://handlers.file
3102
3103The literal string ``'cfg://handlers.file'`` will be resolved in an
3104analogous way to strings with the ``ext://`` prefix, but looking
3105in the configuration itself rather than the import namespace. The
3106mechanism allows access by dot or by index, in a similar way to
3107that provided by ``str.format``. Thus, given the following snippet::
3108
3109 handlers:
3110 email:
3111 class: logging.handlers.SMTPHandler
3112 mailhost: localhost
3113 fromaddr: my_app@domain.tld
3114 toaddrs:
3115 - support_team@domain.tld
3116 - dev_team@domain.tld
3117 subject: Houston, we have a problem.
3118
3119in the configuration, the string ``'cfg://handlers'`` would resolve to
3120the dict with key ``handlers``, the string ``'cfg://handlers.email``
3121would resolve to the dict with key ``email`` in the ``handlers`` dict,
3122and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3123resolve to ``'dev_team.domain.tld'`` and the string
3124``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3125``'support_team@domain.tld'``. The ``subject`` value could be accessed
3126using either ``'cfg://handlers.email.subject'`` or, equivalently,
3127``'cfg://handlers.email[subject]'``. The latter form only needs to be
3128used if the key contains spaces or non-alphanumeric characters. If an
3129index value consists only of decimal digits, access will be attempted
3130using the corresponding integer value, falling back to the string
3131value if needed.
3132
3133Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3134resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3135If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3136the system will attempt to retrieve the value from
3137``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3138to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3139fails.
3140
Georg Brandl8ec7f652007-08-15 14:28:01 +00003141.. _logging-config-fileformat:
3142
3143Configuration file format
3144^^^^^^^^^^^^^^^^^^^^^^^^^
3145
Georg Brandl392c6fc2008-05-25 07:25:25 +00003146The configuration file format understood by :func:`fileConfig` is based on
Vinay Sajip51104862009-01-02 18:53:04 +00003147:mod:`ConfigParser` functionality. The file must contain sections called
3148``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3149entities of each type which are defined in the file. For each such entity,
3150there is a separate section which identifies how that entity is configured.
3151Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant
3152configuration details are held in a section ``[logger_log01]``. Similarly, a
3153handler called ``hand01`` in the ``[handlers]`` section will have its
3154configuration held in a section called ``[handler_hand01]``, while a formatter
3155called ``form01`` in the ``[formatters]`` section will have its configuration
3156specified in a section called ``[formatter_form01]``. The root logger
3157configuration must be specified in a section called ``[logger_root]``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003158
3159Examples of these sections in the file are given below. ::
3160
3161 [loggers]
3162 keys=root,log02,log03,log04,log05,log06,log07
3163
3164 [handlers]
3165 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3166
3167 [formatters]
3168 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3169
3170The root logger must specify a level and a list of handlers. An example of a
3171root logger section is given below. ::
3172
3173 [logger_root]
3174 level=NOTSET
3175 handlers=hand01
3176
3177The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3178``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3179logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3180package's namespace.
3181
3182The ``handlers`` entry is a comma-separated list of handler names, which must
3183appear in the ``[handlers]`` section. These names must appear in the
3184``[handlers]`` section and have corresponding sections in the configuration
3185file.
3186
3187For loggers other than the root logger, some additional information is required.
3188This is illustrated by the following example. ::
3189
3190 [logger_parser]
3191 level=DEBUG
3192 handlers=hand01
3193 propagate=1
3194 qualname=compiler.parser
3195
3196The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3197except that if a non-root logger's level is specified as ``NOTSET``, the system
3198consults loggers higher up the hierarchy to determine the effective level of the
3199logger. The ``propagate`` entry is set to 1 to indicate that messages must
3200propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3201indicate that messages are **not** propagated to handlers up the hierarchy. The
3202``qualname`` entry is the hierarchical channel name of the logger, that is to
3203say the name used by the application to get the logger.
3204
3205Sections which specify handler configuration are exemplified by the following.
3206::
3207
3208 [handler_hand01]
3209 class=StreamHandler
3210 level=NOTSET
3211 formatter=form01
3212 args=(sys.stdout,)
3213
3214The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3215in the ``logging`` package's namespace). The ``level`` is interpreted as for
3216loggers, and ``NOTSET`` is taken to mean "log everything".
3217
Vinay Sajip2a649f92008-07-18 09:00:35 +00003218.. versionchanged:: 2.6
3219 Added support for resolving the handler's class as a dotted module and class
3220 name.
3221
Georg Brandl8ec7f652007-08-15 14:28:01 +00003222The ``formatter`` entry indicates the key name of the formatter for this
3223handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3224If a name is specified, it must appear in the ``[formatters]`` section and have
3225a corresponding section in the configuration file.
3226
3227The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3228package's namespace, is the list of arguments to the constructor for the handler
3229class. Refer to the constructors for the relevant handlers, or to the examples
3230below, to see how typical entries are constructed. ::
3231
3232 [handler_hand02]
3233 class=FileHandler
3234 level=DEBUG
3235 formatter=form02
3236 args=('python.log', 'w')
3237
3238 [handler_hand03]
3239 class=handlers.SocketHandler
3240 level=INFO
3241 formatter=form03
3242 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3243
3244 [handler_hand04]
3245 class=handlers.DatagramHandler
3246 level=WARN
3247 formatter=form04
3248 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3249
3250 [handler_hand05]
3251 class=handlers.SysLogHandler
3252 level=ERROR
3253 formatter=form05
3254 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3255
3256 [handler_hand06]
3257 class=handlers.NTEventLogHandler
3258 level=CRITICAL
3259 formatter=form06
3260 args=('Python Application', '', 'Application')
3261
3262 [handler_hand07]
3263 class=handlers.SMTPHandler
3264 level=WARN
3265 formatter=form07
3266 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3267
3268 [handler_hand08]
3269 class=handlers.MemoryHandler
3270 level=NOTSET
3271 formatter=form08
3272 target=
3273 args=(10, ERROR)
3274
3275 [handler_hand09]
3276 class=handlers.HTTPHandler
3277 level=NOTSET
3278 formatter=form09
3279 args=('localhost:9022', '/log', 'GET')
3280
3281Sections which specify formatter configuration are typified by the following. ::
3282
3283 [formatter_form01]
3284 format=F1 %(asctime)s %(levelname)s %(message)s
3285 datefmt=
3286 class=logging.Formatter
3287
3288The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Georg Brandlb19be572007-12-29 10:57:00 +00003289the :func:`strftime`\ -compatible date/time format string. If empty, the
3290package substitutes ISO8601 format date/times, which is almost equivalent to
3291specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3292also specifies milliseconds, which are appended to the result of using the above
3293format string, with a comma separator. An example time in ISO8601 format is
3294``2003-01-23 00:29:50,411``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003295
3296The ``class`` entry is optional. It indicates the name of the formatter's class
3297(as a dotted module and class name.) This option is useful for instantiating a
3298:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3299exception tracebacks in an expanded or condensed format.
3300
Georg Brandlc37f2882007-12-04 17:46:27 +00003301
3302Configuration server example
3303^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3304
3305Here is an example of a module using the logging configuration server::
3306
3307 import logging
3308 import logging.config
3309 import time
3310 import os
3311
3312 # read initial config file
3313 logging.config.fileConfig("logging.conf")
3314
3315 # create and start listener on port 9999
3316 t = logging.config.listen(9999)
3317 t.start()
3318
3319 logger = logging.getLogger("simpleExample")
3320
3321 try:
3322 # loop through logging calls to see the difference
3323 # new configurations make, until Ctrl+C is pressed
3324 while True:
3325 logger.debug("debug message")
3326 logger.info("info message")
3327 logger.warn("warn message")
3328 logger.error("error message")
3329 logger.critical("critical message")
3330 time.sleep(5)
3331 except KeyboardInterrupt:
3332 # cleanup
3333 logging.config.stopListening()
3334 t.join()
3335
3336And here is a script that takes a filename and sends that file to the server,
3337properly preceded with the binary-encoded length, as the new logging
3338configuration::
3339
3340 #!/usr/bin/env python
Benjamin Petersona7b55a32009-02-20 03:31:23 +00003341 import socket, sys, struct
Georg Brandlc37f2882007-12-04 17:46:27 +00003342
3343 data_to_send = open(sys.argv[1], "r").read()
3344
3345 HOST = 'localhost'
3346 PORT = 9999
3347 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3348 print "connecting..."
3349 s.connect((HOST, PORT))
3350 print "sending config..."
3351 s.send(struct.pack(">L", len(data_to_send)))
3352 s.send(data_to_send)
3353 s.close()
3354 print "complete"
3355
3356
3357More examples
3358-------------
3359
3360Multiple handlers and formatters
3361^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3362
3363Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3364or maximum quota for the number of handlers you may add. Sometimes it will be
3365beneficial for an application to log all messages of all severities to a text
3366file while simultaneously logging errors or above to the console. To set this
3367up, simply configure the appropriate handlers. The logging calls in the
3368application code will remain unchanged. Here is a slight modification to the
3369previous simple module-based configuration example::
3370
3371 import logging
3372
3373 logger = logging.getLogger("simple_example")
3374 logger.setLevel(logging.DEBUG)
3375 # create file handler which logs even debug messages
3376 fh = logging.FileHandler("spam.log")
3377 fh.setLevel(logging.DEBUG)
3378 # create console handler with a higher log level
3379 ch = logging.StreamHandler()
3380 ch.setLevel(logging.ERROR)
3381 # create formatter and add it to the handlers
3382 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3383 ch.setFormatter(formatter)
3384 fh.setFormatter(formatter)
3385 # add the handlers to logger
3386 logger.addHandler(ch)
3387 logger.addHandler(fh)
3388
3389 # "application" code
3390 logger.debug("debug message")
3391 logger.info("info message")
3392 logger.warn("warn message")
3393 logger.error("error message")
3394 logger.critical("critical message")
3395
3396Notice that the "application" code does not care about multiple handlers. All
3397that changed was the addition and configuration of a new handler named *fh*.
3398
3399The ability to create new handlers with higher- or lower-severity filters can be
3400very helpful when writing and testing an application. Instead of using many
3401``print`` statements for debugging, use ``logger.debug``: Unlike the print
3402statements, which you will have to delete or comment out later, the logger.debug
3403statements can remain intact in the source code and remain dormant until you
3404need them again. At that time, the only change that needs to happen is to
3405modify the severity level of the logger and/or handler to debug.
3406
3407
3408Using logging in multiple modules
3409^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3410
3411It was mentioned above that multiple calls to
3412``logging.getLogger('someLogger')`` return a reference to the same logger
3413object. This is true not only within the same module, but also across modules
3414as long as it is in the same Python interpreter process. It is true for
3415references to the same object; additionally, application code can define and
3416configure a parent logger in one module and create (but not configure) a child
3417logger in a separate module, and all logger calls to the child will pass up to
3418the parent. Here is a main module::
3419
3420 import logging
3421 import auxiliary_module
3422
3423 # create logger with "spam_application"
3424 logger = logging.getLogger("spam_application")
3425 logger.setLevel(logging.DEBUG)
3426 # create file handler which logs even debug messages
3427 fh = logging.FileHandler("spam.log")
3428 fh.setLevel(logging.DEBUG)
3429 # create console handler with a higher log level
3430 ch = logging.StreamHandler()
3431 ch.setLevel(logging.ERROR)
3432 # create formatter and add it to the handlers
3433 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3434 fh.setFormatter(formatter)
3435 ch.setFormatter(formatter)
3436 # add the handlers to the logger
3437 logger.addHandler(fh)
3438 logger.addHandler(ch)
3439
3440 logger.info("creating an instance of auxiliary_module.Auxiliary")
3441 a = auxiliary_module.Auxiliary()
3442 logger.info("created an instance of auxiliary_module.Auxiliary")
3443 logger.info("calling auxiliary_module.Auxiliary.do_something")
3444 a.do_something()
3445 logger.info("finished auxiliary_module.Auxiliary.do_something")
3446 logger.info("calling auxiliary_module.some_function()")
3447 auxiliary_module.some_function()
3448 logger.info("done with auxiliary_module.some_function()")
3449
3450Here is the auxiliary module::
3451
3452 import logging
3453
3454 # create logger
3455 module_logger = logging.getLogger("spam_application.auxiliary")
3456
3457 class Auxiliary:
3458 def __init__(self):
3459 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3460 self.logger.info("creating an instance of Auxiliary")
3461 def do_something(self):
3462 self.logger.info("doing something")
3463 a = 1 + 1
3464 self.logger.info("done doing something")
3465
3466 def some_function():
3467 module_logger.info("received a call to \"some_function\"")
3468
3469The output looks like this::
3470
Vinay Sajipe28fa292008-01-07 15:30:36 +00003471 2005-03-23 23:47:11,663 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003472 creating an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003473 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003474 creating an instance of Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003475 2005-03-23 23:47:11,665 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003476 created an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003477 2005-03-23 23:47:11,668 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003478 calling auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003479 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003480 doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003481 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003482 done doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003483 2005-03-23 23:47:11,670 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003484 finished auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003485 2005-03-23 23:47:11,671 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003486 calling auxiliary_module.some_function()
Vinay Sajipe28fa292008-01-07 15:30:36 +00003487 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003488 received a call to "some_function"
Vinay Sajipe28fa292008-01-07 15:30:36 +00003489 2005-03-23 23:47:11,673 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003490 done with auxiliary_module.some_function()
3491