blob: e82be99f9bbbefef96d55b1b9577ed8b4e13bd9b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl8ec7f652007-08-15 14:28:01 +000012.. index:: pair: Errors; logging
13
14.. versionadded:: 2.3
15
16This module defines functions and classes which implement a flexible error
17logging system for applications.
18
19Logging is performed by calling methods on instances of the :class:`Logger`
20class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandla7395032007-10-21 12:15:05 +000021conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl8ec7f652007-08-15 14:28:01 +000022separators. For example, a logger named "scan" is the parent of loggers
23"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
24and indicate the area of an application in which a logged message originates.
25
26Logged messages also have levels of importance associated with them. The default
27levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
28:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
29importance of a logged message by calling an appropriate method of
30:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
31:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
32constrained to use these levels: you can specify your own and use a more general
33:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
34
Georg Brandlc37f2882007-12-04 17:46:27 +000035
36Logging tutorial
37----------------
38
39The key benefit of having the logging API provided by a standard library module
40is that all Python modules can participate in logging, so your application log
41can include messages from third-party modules.
42
43It is, of course, possible to log messages with different verbosity levels or to
44different destinations. Support for writing log messages to files, HTTP
45GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Georg Brandl907a7202008-02-22 12:31:45 +000046mechanisms are all supported by the standard module. You can also create your
Georg Brandlc37f2882007-12-04 17:46:27 +000047own log destination class if you have special requirements not met by any of the
48built-in classes.
49
50Simple examples
51^^^^^^^^^^^^^^^
52
53.. sectionauthor:: Doug Hellmann
54.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
55
56Most applications are probably going to want to log to a file, so let's start
57with that case. Using the :func:`basicConfig` function, we can set up the
Vinay Sajip9a26aab2010-06-03 22:34:42 +000058default handler so that debug messages are written to a file (in the example,
59we assume that you have the appropriate permissions to create a file called
Vinay Sajip998cc242010-06-04 13:41:02 +000060*example.log* in the current directory)::
Georg Brandlc37f2882007-12-04 17:46:27 +000061
62 import logging
Vinay Sajip9a26aab2010-06-03 22:34:42 +000063 LOG_FILENAME = 'example.log'
Vinay Sajipf778bec2009-09-22 17:23:41 +000064 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Georg Brandlc37f2882007-12-04 17:46:27 +000065
66 logging.debug('This message should go to the log file')
67
68And now if we open the file and look at what we have, we should find the log
69message::
70
71 DEBUG:root:This message should go to the log file
72
73If you run the script repeatedly, the additional log messages are appended to
Eric Smithe7dbebb2009-06-04 17:58:15 +000074the file. To create a new file each time, you can pass a *filemode* argument to
Georg Brandlc37f2882007-12-04 17:46:27 +000075:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
76yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
77
78 import glob
79 import logging
80 import logging.handlers
81
Vinay Sajip998cc242010-06-04 13:41:02 +000082 LOG_FILENAME = 'logging_rotatingfile_example.out'
Georg Brandlc37f2882007-12-04 17:46:27 +000083
84 # Set up a specific logger with our desired output level
85 my_logger = logging.getLogger('MyLogger')
86 my_logger.setLevel(logging.DEBUG)
87
88 # Add the log message handler to the logger
89 handler = logging.handlers.RotatingFileHandler(
90 LOG_FILENAME, maxBytes=20, backupCount=5)
91
92 my_logger.addHandler(handler)
93
94 # Log some messages
95 for i in range(20):
96 my_logger.debug('i = %d' % i)
97
98 # See what files are created
99 logfiles = glob.glob('%s*' % LOG_FILENAME)
100
101 for filename in logfiles:
102 print filename
103
104The result should be 6 separate files, each with part of the log history for the
105application::
106
Vinay Sajip998cc242010-06-04 13:41:02 +0000107 logging_rotatingfile_example.out
108 logging_rotatingfile_example.out.1
109 logging_rotatingfile_example.out.2
110 logging_rotatingfile_example.out.3
111 logging_rotatingfile_example.out.4
112 logging_rotatingfile_example.out.5
Georg Brandlc37f2882007-12-04 17:46:27 +0000113
Vinay Sajip998cc242010-06-04 13:41:02 +0000114The most current file is always :file:`logging_rotatingfile_example.out`,
Georg Brandlc37f2882007-12-04 17:46:27 +0000115and each time it reaches the size limit it is renamed with the suffix
116``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smithe7dbebb2009-06-04 17:58:15 +0000117(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Georg Brandlc37f2882007-12-04 17:46:27 +0000118
119Obviously this example sets the log length much much too small as an extreme
120example. You would want to set *maxBytes* to an appropriate value.
121
122Another useful feature of the logging API is the ability to produce different
123messages at different log levels. This allows you to instrument your code with
124debug messages, for example, but turning the log level down so that those debug
125messages are not written for your production system. The default levels are
Vinay Sajipa7d44002009-10-28 23:28:16 +0000126``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Georg Brandlc37f2882007-12-04 17:46:27 +0000127
128The logger, handler, and log message call each specify a level. The log message
129is only emitted if the handler and logger are configured to emit messages of
130that level or lower. For example, if a message is ``CRITICAL``, and the logger
131is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
132the logger is set to produce only ``ERROR``\s, the message is not emitted::
133
134 import logging
135 import sys
136
137 LEVELS = {'debug': logging.DEBUG,
138 'info': logging.INFO,
139 'warning': logging.WARNING,
140 'error': logging.ERROR,
141 'critical': logging.CRITICAL}
142
143 if len(sys.argv) > 1:
144 level_name = sys.argv[1]
145 level = LEVELS.get(level_name, logging.NOTSET)
146 logging.basicConfig(level=level)
147
148 logging.debug('This is a debug message')
149 logging.info('This is an info message')
150 logging.warning('This is a warning message')
151 logging.error('This is an error message')
152 logging.critical('This is a critical error message')
153
154Run the script with an argument like 'debug' or 'warning' to see which messages
155show up at different levels::
156
157 $ python logging_level_example.py debug
158 DEBUG:root:This is a debug message
159 INFO:root:This is an info message
160 WARNING:root:This is a warning message
161 ERROR:root:This is an error message
162 CRITICAL:root:This is a critical error message
163
164 $ python logging_level_example.py info
165 INFO:root:This is an info message
166 WARNING:root:This is a warning message
167 ERROR:root:This is an error message
168 CRITICAL:root:This is a critical error message
169
170You will notice that these log messages all have ``root`` embedded in them. The
171logging module supports a hierarchy of loggers with different names. An easy
172way to tell where a specific log message comes from is to use a separate logger
173object for each of your modules. Each new logger "inherits" the configuration
174of its parent, and log messages sent to a logger include the name of that
175logger. Optionally, each logger can be configured differently, so that messages
176from different modules are handled in different ways. Let's look at a simple
177example of how to log from different modules so it is easy to trace the source
178of the message::
179
180 import logging
181
182 logging.basicConfig(level=logging.WARNING)
183
184 logger1 = logging.getLogger('package1.module1')
185 logger2 = logging.getLogger('package2.module2')
186
187 logger1.warning('This message comes from one module')
188 logger2.warning('And this message comes from another module')
189
190And the output::
191
192 $ python logging_modules_example.py
193 WARNING:package1.module1:This message comes from one module
194 WARNING:package2.module2:And this message comes from another module
195
196There are many more options for configuring logging, including different log
197message formatting options, having messages delivered to multiple destinations,
198and changing the configuration of a long-running application on the fly using a
199socket interface. All of these options are covered in depth in the library
200module documentation.
201
202Loggers
203^^^^^^^
204
205The logging library takes a modular approach and offers the several categories
206of components: loggers, handlers, filters, and formatters. Loggers expose the
207interface that application code directly uses. Handlers send the log records to
208the appropriate destination. Filters provide a finer grained facility for
209determining which log records to send on to a handler. Formatters specify the
210layout of the resultant log record.
211
212:class:`Logger` objects have a threefold job. First, they expose several
213methods to application code so that applications can log messages at runtime.
214Second, logger objects determine which log messages to act upon based upon
215severity (the default filtering facility) or filter objects. Third, logger
216objects pass along relevant log messages to all interested log handlers.
217
218The most widely used methods on logger objects fall into two categories:
219configuration and message sending.
220
221* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
222 will handle, where debug is the lowest built-in severity level and critical is
223 the highest built-in severity. For example, if the severity level is info,
224 the logger will handle only info, warning, error, and critical messages and
225 will ignore debug messages.
226
227* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
228 objects from the logger object. This tutorial does not address filters.
229
230With the logger object configured, the following methods create log messages:
231
232* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
233 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
234 a message and a level that corresponds to their respective method names. The
235 message is actually a format string, which may contain the standard string
236 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
237 rest of their arguments is a list of objects that correspond with the
238 substitution fields in the message. With regard to :const:`**kwargs`, the
239 logging methods care only about a keyword of :const:`exc_info` and use it to
240 determine whether to log exception information.
241
242* :meth:`Logger.exception` creates a log message similar to
243 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
244 stack trace along with it. Call this method only from an exception handler.
245
246* :meth:`Logger.log` takes a log level as an explicit argument. This is a
247 little more verbose for logging messages than using the log level convenience
248 methods listed above, but this is how to log at custom log levels.
249
Brett Cannon499969a2008-02-25 05:33:07 +0000250:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajip80eed3e2010-07-06 15:08:55 +0000251name if it is provided, or ``root`` if not. The names are period-separated
Georg Brandlc37f2882007-12-04 17:46:27 +0000252hierarchical structures. Multiple calls to :func:`getLogger` with the same name
253will return a reference to the same logger object. Loggers that are further
254down in the hierarchical list are children of loggers higher up in the list.
255For example, given a logger with a name of ``foo``, loggers with names of
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000256``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
257Child loggers propagate messages up to the handlers associated with their
258ancestor loggers. Because of this, it is unnecessary to define and configure
259handlers for all the loggers an application uses. It is sufficient to
260configure handlers for a top-level logger and create child loggers as needed.
Georg Brandlc37f2882007-12-04 17:46:27 +0000261
262
263Handlers
264^^^^^^^^
265
266:class:`Handler` objects are responsible for dispatching the appropriate log
267messages (based on the log messages' severity) to the handler's specified
268destination. Logger objects can add zero or more handler objects to themselves
269with an :func:`addHandler` method. As an example scenario, an application may
270want to send all log messages to a log file, all log messages of error or higher
271to stdout, and all messages of critical to an email address. This scenario
Georg Brandl907a7202008-02-22 12:31:45 +0000272requires three individual handlers where each handler is responsible for sending
Georg Brandlc37f2882007-12-04 17:46:27 +0000273messages of a specific severity to a specific location.
274
275The standard library includes quite a few handler types; this tutorial uses only
276:class:`StreamHandler` and :class:`FileHandler` in its examples.
277
278There are very few methods in a handler for application developers to concern
279themselves with. The only handler methods that seem relevant for application
280developers who are using the built-in handler objects (that is, not creating
281custom handlers) are the following configuration methods:
282
283* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
284 lowest severity that will be dispatched to the appropriate destination. Why
285 are there two :func:`setLevel` methods? The level set in the logger
286 determines which severity of messages it will pass to its handlers. The level
287 set in each handler determines which messages that handler will send on.
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000288
289* :func:`setFormatter` selects a Formatter object for this handler to use.
Georg Brandlc37f2882007-12-04 17:46:27 +0000290
291* :func:`addFilter` and :func:`removeFilter` respectively configure and
292 deconfigure filter objects on handlers.
293
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000294Application code should not directly instantiate and use instances of
295:class:`Handler`. Instead, the :class:`Handler` class is a base class that
Vinay Sajip497256b2010-04-07 09:40:52 +0000296defines the interface that all handlers should have and establishes some
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000297default behavior that child classes can use (or override).
Georg Brandlc37f2882007-12-04 17:46:27 +0000298
299
300Formatters
301^^^^^^^^^^
302
303Formatter objects configure the final order, structure, and contents of the log
Brett Cannon499969a2008-02-25 05:33:07 +0000304message. Unlike the base :class:`logging.Handler` class, application code may
Georg Brandlc37f2882007-12-04 17:46:27 +0000305instantiate formatter classes, although you could likely subclass the formatter
306if your application needs special behavior. The constructor takes two optional
307arguments: a message format string and a date format string. If there is no
308message format string, the default is to use the raw message. If there is no
309date format string, the default date format is::
310
311 %Y-%m-%d %H:%M:%S
312
313with the milliseconds tacked on at the end.
314
315The message format string uses ``%(<dictionary key>)s`` styled string
Vinay Sajip4b782332009-01-19 06:49:19 +0000316substitution; the possible keys are documented in :ref:`formatter`.
Georg Brandlc37f2882007-12-04 17:46:27 +0000317
318The following message format string will log the time in a human-readable
319format, the severity of the message, and the contents of the message, in that
320order::
321
322 "%(asctime)s - %(levelname)s - %(message)s"
323
Vinay Sajip8d8e6152010-08-30 18:10:03 +0000324Formatters use a user-configurable function to convert the creation time of a
325record to a tuple. By default, :func:`time.localtime` is used; to change this
326for a particular formatter instance, set the ``converter`` attribute of the
327instance to a function with the same signature as :func:`time.localtime` or
328:func:`time.gmtime`. To change it for all formatters, for example if you want
329all logging times to be shown in GMT, set the ``converter`` attribute in the
330Formatter class (to ``time.gmtime`` for GMT display).
331
Georg Brandlc37f2882007-12-04 17:46:27 +0000332
333Configuring Logging
334^^^^^^^^^^^^^^^^^^^
335
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000336Programmers can configure logging in three ways:
337
3381. Creating loggers, handlers, and formatters explicitly using Python
339 code that calls the configuration methods listed above.
3402. Creating a logging config file and reading it using the :func:`fileConfig`
341 function.
3423. Creating a dictionary of configuration information and passing it
343 to the :func:`dictConfig` function.
344
345The following example configures a very simple logger, a console
Vinay Sajipa38cd522010-05-18 08:16:27 +0000346handler, and a simple formatter using Python code::
Georg Brandlc37f2882007-12-04 17:46:27 +0000347
348 import logging
349
350 # create logger
351 logger = logging.getLogger("simple_example")
352 logger.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000353
Georg Brandlc37f2882007-12-04 17:46:27 +0000354 # create console handler and set level to debug
355 ch = logging.StreamHandler()
356 ch.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000357
Georg Brandlc37f2882007-12-04 17:46:27 +0000358 # create formatter
359 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000360
Georg Brandlc37f2882007-12-04 17:46:27 +0000361 # add formatter to ch
362 ch.setFormatter(formatter)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000363
Georg Brandlc37f2882007-12-04 17:46:27 +0000364 # add ch to logger
365 logger.addHandler(ch)
366
367 # "application" code
368 logger.debug("debug message")
369 logger.info("info message")
370 logger.warn("warn message")
371 logger.error("error message")
372 logger.critical("critical message")
373
374Running this module from the command line produces the following output::
375
376 $ python simple_logging_module.py
377 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
378 2005-03-19 15:10:26,620 - simple_example - INFO - info message
379 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
380 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
381 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
382
383The following Python module creates a logger, handler, and formatter nearly
384identical to those in the example listed above, with the only difference being
385the names of the objects::
386
387 import logging
388 import logging.config
389
390 logging.config.fileConfig("logging.conf")
391
392 # create logger
393 logger = logging.getLogger("simpleExample")
394
395 # "application" code
396 logger.debug("debug message")
397 logger.info("info message")
398 logger.warn("warn message")
399 logger.error("error message")
400 logger.critical("critical message")
401
402Here is the logging.conf file::
403
404 [loggers]
405 keys=root,simpleExample
406
407 [handlers]
408 keys=consoleHandler
409
410 [formatters]
411 keys=simpleFormatter
412
413 [logger_root]
414 level=DEBUG
415 handlers=consoleHandler
416
417 [logger_simpleExample]
418 level=DEBUG
419 handlers=consoleHandler
420 qualname=simpleExample
421 propagate=0
422
423 [handler_consoleHandler]
424 class=StreamHandler
425 level=DEBUG
426 formatter=simpleFormatter
427 args=(sys.stdout,)
428
429 [formatter_simpleFormatter]
430 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
431 datefmt=
432
433The output is nearly identical to that of the non-config-file-based example::
434
435 $ python simple_logging_config.py
436 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
437 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
438 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
439 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
440 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
441
442You can see that the config file approach has a few advantages over the Python
443code approach, mainly separation of configuration and code and the ability of
444noncoders to easily modify the logging properties.
445
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000446Note that the class names referenced in config files need to be either relative
447to the logging module, or absolute values which can be resolved using normal
Georg Brandlf6d367452010-03-12 10:02:03 +0000448import mechanisms. Thus, you could use either :class:`handlers.WatchedFileHandler`
449(relative to the logging module) or :class:`mypackage.mymodule.MyHandler` (for a
450class defined in package :mod:`mypackage` and module :mod:`mymodule`, where
451:mod:`mypackage` is available on the Python import path).
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000452
Vinay Sajipc76defc2010-05-21 17:41:34 +0000453.. versionchanged:: 2.7
454
455In Python 2.7, a new means of configuring logging has been introduced, using
456dictionaries to hold configuration information. This provides a superset of the
457functionality of the config-file-based approach outlined above, and is the
458recommended configuration method for new applications and deployments. Because
459a Python dictionary is used to hold configuration information, and since you
460can populate that dictionary using different means, you have more options for
461configuration. For example, you can use a configuration file in JSON format,
462or, if you have access to YAML processing functionality, a file in YAML
463format, to populate the configuration dictionary. Or, of course, you can
464construct the dictionary in Python code, receive it in pickled form over a
465socket, or use whatever approach makes sense for your application.
466
467Here's an example of the same configuration as above, in YAML format for
468the new dictionary-based approach::
469
470 version: 1
471 formatters:
472 simple:
473 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
474 handlers:
475 console:
476 class: logging.StreamHandler
477 level: DEBUG
478 formatter: simple
479 stream: ext://sys.stdout
480 loggers:
481 simpleExample:
482 level: DEBUG
483 handlers: [console]
484 propagate: no
485 root:
486 level: DEBUG
487 handlers: [console]
488
489For more information about logging using a dictionary, see
490:ref:`logging-config-api`.
491
Vinay Sajip99505c82009-01-10 13:38:04 +0000492.. _library-config:
493
Vinay Sajip34bfda52008-09-01 15:08:07 +0000494Configuring Logging for a Library
495^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
496
497When developing a library which uses logging, some consideration needs to be
498given to its configuration. If the using application does not use logging, and
499library code makes logging calls, then a one-off message "No handlers could be
500found for logger X.Y.Z" is printed to the console. This message is intended
501to catch mistakes in logging configuration, but will confuse an application
502developer who is not aware of logging by the library.
503
504In addition to documenting how a library uses logging, a good way to configure
505library logging so that it does not cause a spurious message is to add a
506handler which does nothing. This avoids the message being printed, since a
507handler will be found: it just doesn't produce any output. If the library user
508configures logging for application use, presumably that configuration will add
509some handlers, and if levels are suitably configured then logging calls made
510in library code will send output to those handlers, as normal.
511
512A do-nothing handler can be simply defined as follows::
513
514 import logging
515
516 class NullHandler(logging.Handler):
517 def emit(self, record):
518 pass
519
520An instance of this handler should be added to the top-level logger of the
521logging namespace used by the library. If all logging by a library *foo* is
522done using loggers with names matching "foo.x.y", then the code::
523
524 import logging
525
526 h = NullHandler()
527 logging.getLogger("foo").addHandler(h)
528
529should have the desired effect. If an organisation produces a number of
530libraries, then the logger name specified can be "orgname.foo" rather than
531just "foo".
532
Vinay Sajip213faca2008-12-03 23:22:58 +0000533.. versionadded:: 2.7
534
535The :class:`NullHandler` class was not present in previous versions, but is now
536included, so that it need not be defined in library code.
537
538
Georg Brandlc37f2882007-12-04 17:46:27 +0000539
540Logging Levels
541--------------
542
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543The numeric values of logging levels are given in the following table. These are
544primarily of interest if you want to define your own levels, and need them to
545have specific values relative to the predefined levels. If you define a level
546with the same numeric value, it overwrites the predefined value; the predefined
547name is lost.
548
549+--------------+---------------+
550| Level | Numeric value |
551+==============+===============+
552| ``CRITICAL`` | 50 |
553+--------------+---------------+
554| ``ERROR`` | 40 |
555+--------------+---------------+
556| ``WARNING`` | 30 |
557+--------------+---------------+
558| ``INFO`` | 20 |
559+--------------+---------------+
560| ``DEBUG`` | 10 |
561+--------------+---------------+
562| ``NOTSET`` | 0 |
563+--------------+---------------+
564
565Levels can also be associated with loggers, being set either by the developer or
566through loading a saved logging configuration. When a logging method is called
567on a logger, the logger compares its own level with the level associated with
568the method call. If the logger's level is higher than the method call's, no
569logging message is actually generated. This is the basic mechanism controlling
570the verbosity of logging output.
571
572Logging messages are encoded as instances of the :class:`LogRecord` class. When
573a logger decides to actually log an event, a :class:`LogRecord` instance is
574created from the logging message.
575
576Logging messages are subjected to a dispatch mechanism through the use of
577:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
578class. Handlers are responsible for ensuring that a logged message (in the form
579of a :class:`LogRecord`) ends up in a particular location (or set of locations)
580which is useful for the target audience for that message (such as end users,
581support desk staff, system administrators, developers). Handlers are passed
582:class:`LogRecord` instances intended for particular destinations. Each logger
583can have zero, one or more handlers associated with it (via the
584:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
585directly associated with a logger, *all handlers associated with all ancestors
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000586of the logger* are called to dispatch the message (unless the *propagate* flag
587for a logger is set to a false value, at which point the passing to ancestor
588handlers stops).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589
590Just as for loggers, handlers can have levels associated with them. A handler's
591level acts as a filter in the same way as a logger's level does. If a handler
592decides to actually dispatch an event, the :meth:`emit` method is used to send
593the message to its destination. Most user-defined subclasses of :class:`Handler`
594will need to override this :meth:`emit`.
595
Vinay Sajipb5902e62009-01-15 22:48:13 +0000596Useful Handlers
597---------------
598
Georg Brandl8ec7f652007-08-15 14:28:01 +0000599In addition to the base :class:`Handler` class, many useful subclasses are
600provided:
601
Vinay Sajip4b782332009-01-19 06:49:19 +0000602#. :ref:`stream-handler` instances send error messages to streams (file-like
Georg Brandl8ec7f652007-08-15 14:28:01 +0000603 objects).
604
Vinay Sajip4b782332009-01-19 06:49:19 +0000605#. :ref:`file-handler` instances send error messages to disk files.
Vinay Sajipb1a15e42009-01-15 23:04:47 +0000606
Vinay Sajipb5902e62009-01-15 22:48:13 +0000607#. :class:`BaseRotatingHandler` is the base class for handlers that
Vinay Sajip99234c52009-01-12 20:36:18 +0000608 rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajip4b782332009-01-19 06:49:19 +0000609 directly. Instead, use :ref:`rotating-file-handler` or
610 :ref:`timed-rotating-file-handler`.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000611
Vinay Sajip4b782332009-01-19 06:49:19 +0000612#. :ref:`rotating-file-handler` instances send error messages to disk
Vinay Sajipb5902e62009-01-15 22:48:13 +0000613 files, with support for maximum log file sizes and log file rotation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000614
Vinay Sajip4b782332009-01-19 06:49:19 +0000615#. :ref:`timed-rotating-file-handler` instances send error messages to
Vinay Sajipb5902e62009-01-15 22:48:13 +0000616 disk files, rotating the log file at certain timed intervals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
Vinay Sajip4b782332009-01-19 06:49:19 +0000618#. :ref:`socket-handler` instances send error messages to TCP/IP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000619 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000620
Vinay Sajip4b782332009-01-19 06:49:19 +0000621#. :ref:`datagram-handler` instances send error messages to UDP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000622 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623
Vinay Sajip4b782332009-01-19 06:49:19 +0000624#. :ref:`smtp-handler` instances send error messages to a designated
Vinay Sajipb5902e62009-01-15 22:48:13 +0000625 email address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000626
Vinay Sajip4b782332009-01-19 06:49:19 +0000627#. :ref:`syslog-handler` instances send error messages to a Unix
Vinay Sajipb5902e62009-01-15 22:48:13 +0000628 syslog daemon, possibly on a remote machine.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000629
Vinay Sajip4b782332009-01-19 06:49:19 +0000630#. :ref:`nt-eventlog-handler` instances send error messages to a
Vinay Sajipb5902e62009-01-15 22:48:13 +0000631 Windows NT/2000/XP event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632
Vinay Sajip4b782332009-01-19 06:49:19 +0000633#. :ref:`memory-handler` instances send error messages to a buffer
Vinay Sajipb5902e62009-01-15 22:48:13 +0000634 in memory, which is flushed whenever specific criteria are met.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Vinay Sajip4b782332009-01-19 06:49:19 +0000636#. :ref:`http-handler` instances send error messages to an HTTP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000637 server using either ``GET`` or ``POST`` semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000638
Vinay Sajip4b782332009-01-19 06:49:19 +0000639#. :ref:`watched-file-handler` instances watch the file they are
Vinay Sajipb5902e62009-01-15 22:48:13 +0000640 logging to. If the file changes, it is closed and reopened using the file
641 name. This handler is only useful on Unix-like systems; Windows does not
642 support the underlying mechanism used.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000643
Vinay Sajip4b782332009-01-19 06:49:19 +0000644#. :ref:`null-handler` instances do nothing with error messages. They are used
Vinay Sajip213faca2008-12-03 23:22:58 +0000645 by library developers who want to use logging, but want to avoid the "No
646 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip99505c82009-01-10 13:38:04 +0000647 the library user has not configured logging. See :ref:`library-config` for
648 more information.
Vinay Sajip213faca2008-12-03 23:22:58 +0000649
650.. versionadded:: 2.7
651
652The :class:`NullHandler` class was not present in previous versions.
653
Vinay Sajip7cc97552008-12-30 07:01:25 +0000654The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
655classes are defined in the core logging package. The other handlers are
656defined in a sub- module, :mod:`logging.handlers`. (There is also another
657sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000658
659Logged messages are formatted for presentation through instances of the
660:class:`Formatter` class. They are initialized with a format string suitable for
661use with the % operator and a dictionary.
662
663For formatting multiple messages in a batch, instances of
664:class:`BufferingFormatter` can be used. In addition to the format string (which
665is applied to each message in the batch), there is provision for header and
666trailer format strings.
667
668When filtering based on logger level and/or handler level is not enough,
669instances of :class:`Filter` can be added to both :class:`Logger` and
670:class:`Handler` instances (through their :meth:`addFilter` method). Before
671deciding to process a message further, both loggers and handlers consult all
672their filters for permission. If any filter returns a false value, the message
673is not processed further.
674
675The basic :class:`Filter` functionality allows filtering by specific logger
676name. If this feature is used, messages sent to the named logger and its
677children are allowed through the filter, and all others dropped.
678
Vinay Sajipb5902e62009-01-15 22:48:13 +0000679Module-Level Functions
680----------------------
681
Georg Brandl8ec7f652007-08-15 14:28:01 +0000682In addition to the classes described above, there are a number of module- level
683functions.
684
685
686.. function:: getLogger([name])
687
688 Return a logger with the specified name or, if no name is specified, return a
689 logger which is the root logger of the hierarchy. If specified, the name is
690 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
691 Choice of these names is entirely up to the developer who is using logging.
692
693 All calls to this function with a given name return the same logger instance.
694 This means that logger instances never need to be passed between different parts
695 of an application.
696
697
698.. function:: getLoggerClass()
699
700 Return either the standard :class:`Logger` class, or the last class passed to
701 :func:`setLoggerClass`. This function may be called from within a new class
702 definition, to ensure that installing a customised :class:`Logger` class will
703 not undo customisations already applied by other code. For example::
704
705 class MyLogger(logging.getLoggerClass()):
706 # ... override behaviour here
707
708
709.. function:: debug(msg[, *args[, **kwargs]])
710
711 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
712 message format string, and the *args* are the arguments which are merged into
713 *msg* using the string formatting operator. (Note that this means that you can
714 use keywords in the format string, together with a single dictionary argument.)
715
716 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
717 which, if it does not evaluate as false, causes exception information to be
718 added to the logging message. If an exception tuple (in the format returned by
719 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
720 is called to get the exception information.
721
722 The other optional keyword argument is *extra* which can be used to pass a
723 dictionary which is used to populate the __dict__ of the LogRecord created for
724 the logging event with user-defined attributes. These custom attributes can then
725 be used as you like. For example, they could be incorporated into logged
726 messages. For example::
727
728 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
729 logging.basicConfig(format=FORMAT)
730 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
731 logging.warning("Protocol problem: %s", "connection reset", extra=d)
732
733 would print something like ::
734
735 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
736
737 The keys in the dictionary passed in *extra* should not clash with the keys used
738 by the logging system. (See the :class:`Formatter` documentation for more
739 information on which keys are used by the logging system.)
740
741 If you choose to use these attributes in logged messages, you need to exercise
742 some care. In the above example, for instance, the :class:`Formatter` has been
743 set up with a format string which expects 'clientip' and 'user' in the attribute
744 dictionary of the LogRecord. If these are missing, the message will not be
745 logged because a string formatting exception will occur. So in this case, you
746 always need to pass the *extra* dictionary with these keys.
747
748 While this might be annoying, this feature is intended for use in specialized
749 circumstances, such as multi-threaded servers where the same code executes in
750 many contexts, and interesting conditions which arise are dependent on this
751 context (such as remote client IP address and authenticated user name, in the
752 above example). In such circumstances, it is likely that specialized
753 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
754
755 .. versionchanged:: 2.5
756 *extra* was added.
757
758
759.. function:: info(msg[, *args[, **kwargs]])
760
761 Logs a message with level :const:`INFO` on the root logger. The arguments are
762 interpreted as for :func:`debug`.
763
764
765.. function:: warning(msg[, *args[, **kwargs]])
766
767 Logs a message with level :const:`WARNING` on the root logger. The arguments are
768 interpreted as for :func:`debug`.
769
770
771.. function:: error(msg[, *args[, **kwargs]])
772
773 Logs a message with level :const:`ERROR` on the root logger. The arguments are
774 interpreted as for :func:`debug`.
775
776
777.. function:: critical(msg[, *args[, **kwargs]])
778
779 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
780 are interpreted as for :func:`debug`.
781
782
783.. function:: exception(msg[, *args])
784
785 Logs a message with level :const:`ERROR` on the root logger. The arguments are
786 interpreted as for :func:`debug`. Exception info is added to the logging
787 message. This function should only be called from an exception handler.
788
789
790.. function:: log(level, msg[, *args[, **kwargs]])
791
792 Logs a message with level *level* on the root logger. The other arguments are
793 interpreted as for :func:`debug`.
794
795
796.. function:: disable(lvl)
797
798 Provides an overriding level *lvl* for all loggers which takes precedence over
799 the logger's own level. When the need arises to temporarily throttle logging
Vinay Sajip2060e422010-03-17 15:05:57 +0000800 output down across the whole application, this function can be useful. Its
801 effect is to disable all logging calls of severity *lvl* and below, so that
802 if you call it with a value of INFO, then all INFO and DEBUG events would be
803 discarded, whereas those of severity WARNING and above would be processed
804 according to the logger's effective level.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805
806
807.. function:: addLevelName(lvl, levelName)
808
809 Associates level *lvl* with text *levelName* in an internal dictionary, which is
810 used to map numeric levels to a textual representation, for example when a
811 :class:`Formatter` formats a message. This function can also be used to define
812 your own levels. The only constraints are that all levels used must be
813 registered using this function, levels should be positive integers and they
814 should increase in increasing order of severity.
815
816
817.. function:: getLevelName(lvl)
818
819 Returns the textual representation of logging level *lvl*. If the level is one
820 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
821 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
822 have associated levels with names using :func:`addLevelName` then the name you
823 have associated with *lvl* is returned. If a numeric value corresponding to one
824 of the defined levels is passed in, the corresponding string representation is
825 returned. Otherwise, the string "Level %s" % lvl is returned.
826
827
828.. function:: makeLogRecord(attrdict)
829
830 Creates and returns a new :class:`LogRecord` instance whose attributes are
831 defined by *attrdict*. This function is useful for taking a pickled
832 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
833 it as a :class:`LogRecord` instance at the receiving end.
834
835
836.. function:: basicConfig([**kwargs])
837
838 Does basic configuration for the logging system by creating a
839 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000840 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000841 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
842 if no handlers are defined for the root logger.
843
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000844 This function does nothing if the root logger already has handlers
845 configured for it.
Georg Brandldfb5bbd2008-05-09 06:18:27 +0000846
Georg Brandl8ec7f652007-08-15 14:28:01 +0000847 .. versionchanged:: 2.4
848 Formerly, :func:`basicConfig` did not take any keyword arguments.
849
850 The following keyword arguments are supported.
851
852 +--------------+---------------------------------------------+
853 | Format | Description |
854 +==============+=============================================+
855 | ``filename`` | Specifies that a FileHandler be created, |
856 | | using the specified filename, rather than a |
857 | | StreamHandler. |
858 +--------------+---------------------------------------------+
859 | ``filemode`` | Specifies the mode to open the file, if |
860 | | filename is specified (if filemode is |
861 | | unspecified, it defaults to 'a'). |
862 +--------------+---------------------------------------------+
863 | ``format`` | Use the specified format string for the |
864 | | handler. |
865 +--------------+---------------------------------------------+
866 | ``datefmt`` | Use the specified date/time format. |
867 +--------------+---------------------------------------------+
868 | ``level`` | Set the root logger level to the specified |
869 | | level. |
870 +--------------+---------------------------------------------+
871 | ``stream`` | Use the specified stream to initialize the |
872 | | StreamHandler. Note that this argument is |
873 | | incompatible with 'filename' - if both are |
874 | | present, 'stream' is ignored. |
875 +--------------+---------------------------------------------+
876
877
878.. function:: shutdown()
879
880 Informs the logging system to perform an orderly shutdown by flushing and
Vinay Sajip91f0ee42008-03-16 21:35:58 +0000881 closing all handlers. This should be called at application exit and no
882 further use of the logging system should be made after this call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883
884
885.. function:: setLoggerClass(klass)
886
887 Tells the logging system to use the class *klass* when instantiating a logger.
888 The class should define :meth:`__init__` such that only a name argument is
889 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
890 function is typically called before any loggers are instantiated by applications
891 which need to use custom logger behavior.
892
893
894.. seealso::
895
896 :pep:`282` - A Logging System
897 The proposal which described this feature for inclusion in the Python standard
898 library.
899
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000900 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901 This is the original source for the :mod:`logging` package. The version of the
902 package available from this site is suitable for use with Python 1.5.2, 2.1.x
903 and 2.2.x, which do not include the :mod:`logging` package in the standard
904 library.
905
Vinay Sajip4b782332009-01-19 06:49:19 +0000906.. _logger:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000907
908Logger Objects
909--------------
910
911Loggers have the following attributes and methods. Note that Loggers are never
912instantiated directly, but always through the module-level function
913``logging.getLogger(name)``.
914
915
916.. attribute:: Logger.propagate
917
918 If this evaluates to false, logging messages are not passed by this logger or by
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000919 its child loggers to the handlers of higher level (ancestor) loggers. The
920 constructor sets this attribute to 1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000921
922
923.. method:: Logger.setLevel(lvl)
924
925 Sets the threshold for this logger to *lvl*. Logging messages which are less
926 severe than *lvl* will be ignored. When a logger is created, the level is set to
927 :const:`NOTSET` (which causes all messages to be processed when the logger is
928 the root logger, or delegation to the parent when the logger is a non-root
929 logger). Note that the root logger is created with level :const:`WARNING`.
930
931 The term "delegation to the parent" means that if a logger has a level of
932 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
933 a level other than NOTSET is found, or the root is reached.
934
935 If an ancestor is found with a level other than NOTSET, then that ancestor's
936 level is treated as the effective level of the logger where the ancestor search
937 began, and is used to determine how a logging event is handled.
938
939 If the root is reached, and it has a level of NOTSET, then all messages will be
940 processed. Otherwise, the root's level will be used as the effective level.
941
942
943.. method:: Logger.isEnabledFor(lvl)
944
945 Indicates if a message of severity *lvl* would be processed by this logger.
946 This method checks first the module-level level set by
947 ``logging.disable(lvl)`` and then the logger's effective level as determined
948 by :meth:`getEffectiveLevel`.
949
950
951.. method:: Logger.getEffectiveLevel()
952
953 Indicates the effective level for this logger. If a value other than
954 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
955 the hierarchy is traversed towards the root until a value other than
956 :const:`NOTSET` is found, and that value is returned.
957
958
Vinay Sajip804899b2010-03-22 15:29:01 +0000959.. method:: Logger.getChild(suffix)
960
961 Returns a logger which is a descendant to this logger, as determined by the suffix.
962 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
963 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
964 convenience method, useful when the parent logger is named using e.g. ``__name__``
965 rather than a literal string.
966
967 .. versionadded:: 2.7
968
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969.. method:: Logger.debug(msg[, *args[, **kwargs]])
970
971 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
972 message format string, and the *args* are the arguments which are merged into
973 *msg* using the string formatting operator. (Note that this means that you can
974 use keywords in the format string, together with a single dictionary argument.)
975
976 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
977 which, if it does not evaluate as false, causes exception information to be
978 added to the logging message. If an exception tuple (in the format returned by
979 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
980 is called to get the exception information.
981
982 The other optional keyword argument is *extra* which can be used to pass a
983 dictionary which is used to populate the __dict__ of the LogRecord created for
984 the logging event with user-defined attributes. These custom attributes can then
985 be used as you like. For example, they could be incorporated into logged
986 messages. For example::
987
988 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
989 logging.basicConfig(format=FORMAT)
Neal Norwitz53004282007-10-23 05:44:27 +0000990 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl8ec7f652007-08-15 14:28:01 +0000991 logger = logging.getLogger("tcpserver")
992 logger.warning("Protocol problem: %s", "connection reset", extra=d)
993
994 would print something like ::
995
996 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
997
998 The keys in the dictionary passed in *extra* should not clash with the keys used
999 by the logging system. (See the :class:`Formatter` documentation for more
1000 information on which keys are used by the logging system.)
1001
1002 If you choose to use these attributes in logged messages, you need to exercise
1003 some care. In the above example, for instance, the :class:`Formatter` has been
1004 set up with a format string which expects 'clientip' and 'user' in the attribute
1005 dictionary of the LogRecord. If these are missing, the message will not be
1006 logged because a string formatting exception will occur. So in this case, you
1007 always need to pass the *extra* dictionary with these keys.
1008
1009 While this might be annoying, this feature is intended for use in specialized
1010 circumstances, such as multi-threaded servers where the same code executes in
1011 many contexts, and interesting conditions which arise are dependent on this
1012 context (such as remote client IP address and authenticated user name, in the
1013 above example). In such circumstances, it is likely that specialized
1014 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1015
1016 .. versionchanged:: 2.5
1017 *extra* was added.
1018
1019
1020.. method:: Logger.info(msg[, *args[, **kwargs]])
1021
1022 Logs a message with level :const:`INFO` on this logger. The arguments are
1023 interpreted as for :meth:`debug`.
1024
1025
1026.. method:: Logger.warning(msg[, *args[, **kwargs]])
1027
1028 Logs a message with level :const:`WARNING` on this logger. The arguments are
1029 interpreted as for :meth:`debug`.
1030
1031
1032.. method:: Logger.error(msg[, *args[, **kwargs]])
1033
1034 Logs a message with level :const:`ERROR` on this logger. The arguments are
1035 interpreted as for :meth:`debug`.
1036
1037
1038.. method:: Logger.critical(msg[, *args[, **kwargs]])
1039
1040 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1041 interpreted as for :meth:`debug`.
1042
1043
1044.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
1045
1046 Logs a message with integer level *lvl* on this logger. The other arguments are
1047 interpreted as for :meth:`debug`.
1048
1049
1050.. method:: Logger.exception(msg[, *args])
1051
1052 Logs a message with level :const:`ERROR` on this logger. The arguments are
1053 interpreted as for :meth:`debug`. Exception info is added to the logging
1054 message. This method should only be called from an exception handler.
1055
1056
1057.. method:: Logger.addFilter(filt)
1058
1059 Adds the specified filter *filt* to this logger.
1060
1061
1062.. method:: Logger.removeFilter(filt)
1063
1064 Removes the specified filter *filt* from this logger.
1065
1066
1067.. method:: Logger.filter(record)
1068
1069 Applies this logger's filters to the record and returns a true value if the
1070 record is to be processed.
1071
1072
1073.. method:: Logger.addHandler(hdlr)
1074
1075 Adds the specified handler *hdlr* to this logger.
1076
1077
1078.. method:: Logger.removeHandler(hdlr)
1079
1080 Removes the specified handler *hdlr* from this logger.
1081
1082
1083.. method:: Logger.findCaller()
1084
1085 Finds the caller's source filename and line number. Returns the filename, line
1086 number and function name as a 3-element tuple.
1087
Matthias Klosef0e29182007-08-16 12:03:44 +00001088 .. versionchanged:: 2.4
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089 The function name was added. In earlier versions, the filename and line number
1090 were returned as a 2-element tuple..
1091
1092
1093.. method:: Logger.handle(record)
1094
1095 Handles a record by passing it to all handlers associated with this logger and
1096 its ancestors (until a false value of *propagate* is found). This method is used
1097 for unpickled records received from a socket, as well as those created locally.
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001098 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001099
1100
1101.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
1102
1103 This is a factory method which can be overridden in subclasses to create
1104 specialized :class:`LogRecord` instances.
1105
1106 .. versionchanged:: 2.5
1107 *func* and *extra* were added.
1108
1109
1110.. _minimal-example:
1111
1112Basic example
1113-------------
1114
1115.. versionchanged:: 2.4
1116 formerly :func:`basicConfig` did not take any keyword arguments.
1117
1118The :mod:`logging` package provides a lot of flexibility, and its configuration
1119can appear daunting. This section demonstrates that simple use of the logging
1120package is possible.
1121
1122The simplest example shows logging to the console::
1123
1124 import logging
1125
1126 logging.debug('A debug message')
1127 logging.info('Some information')
1128 logging.warning('A shot across the bows')
1129
1130If you run the above script, you'll see this::
1131
1132 WARNING:root:A shot across the bows
1133
1134Because no particular logger was specified, the system used the root logger. The
1135debug and info messages didn't appear because by default, the root logger is
1136configured to only handle messages with a severity of WARNING or above. The
1137message format is also a configuration default, as is the output destination of
1138the messages - ``sys.stderr``. The severity level, the message format and
1139destination can be easily changed, as shown in the example below::
1140
1141 import logging
1142
1143 logging.basicConfig(level=logging.DEBUG,
1144 format='%(asctime)s %(levelname)s %(message)s',
Vinay Sajip998cc242010-06-04 13:41:02 +00001145 filename='myapp.log',
Georg Brandl8ec7f652007-08-15 14:28:01 +00001146 filemode='w')
1147 logging.debug('A debug message')
1148 logging.info('Some information')
1149 logging.warning('A shot across the bows')
1150
1151The :meth:`basicConfig` method is used to change the configuration defaults,
Vinay Sajip998cc242010-06-04 13:41:02 +00001152which results in output (written to ``myapp.log``) which should look
Georg Brandl8ec7f652007-08-15 14:28:01 +00001153something like the following::
1154
1155 2004-07-02 13:00:08,743 DEBUG A debug message
1156 2004-07-02 13:00:08,743 INFO Some information
1157 2004-07-02 13:00:08,743 WARNING A shot across the bows
1158
1159This time, all messages with a severity of DEBUG or above were handled, and the
1160format of the messages was also changed, and output went to the specified file
1161rather than the console.
1162
1163Formatting uses standard Python string formatting - see section
1164:ref:`string-formatting`. The format string takes the following common
1165specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1166documentation.
1167
1168+-------------------+-----------------------------------------------+
1169| Format | Description |
1170+===================+===============================================+
1171| ``%(name)s`` | Name of the logger (logging channel). |
1172+-------------------+-----------------------------------------------+
1173| ``%(levelname)s`` | Text logging level for the message |
1174| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1175| | ``'ERROR'``, ``'CRITICAL'``). |
1176+-------------------+-----------------------------------------------+
1177| ``%(asctime)s`` | Human-readable time when the |
1178| | :class:`LogRecord` was created. By default |
1179| | this is of the form "2003-07-08 16:49:45,896" |
1180| | (the numbers after the comma are millisecond |
1181| | portion of the time). |
1182+-------------------+-----------------------------------------------+
1183| ``%(message)s`` | The logged message. |
1184+-------------------+-----------------------------------------------+
1185
1186To change the date/time format, you can pass an additional keyword parameter,
1187*datefmt*, as in the following::
1188
1189 import logging
1190
1191 logging.basicConfig(level=logging.DEBUG,
1192 format='%(asctime)s %(levelname)-8s %(message)s',
1193 datefmt='%a, %d %b %Y %H:%M:%S',
1194 filename='/temp/myapp.log',
1195 filemode='w')
1196 logging.debug('A debug message')
1197 logging.info('Some information')
1198 logging.warning('A shot across the bows')
1199
1200which would result in output like ::
1201
1202 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1203 Fri, 02 Jul 2004 13:06:18 INFO Some information
1204 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1205
1206The date format string follows the requirements of :func:`strftime` - see the
1207documentation for the :mod:`time` module.
1208
1209If, instead of sending logging output to the console or a file, you'd rather use
1210a file-like object which you have created separately, you can pass it to
1211:func:`basicConfig` using the *stream* keyword argument. Note that if both
1212*stream* and *filename* keyword arguments are passed, the *stream* argument is
1213ignored.
1214
1215Of course, you can put variable information in your output. To do this, simply
1216have the message be a format string and pass in additional arguments containing
1217the variable information, as in the following example::
1218
1219 import logging
1220
1221 logging.basicConfig(level=logging.DEBUG,
1222 format='%(asctime)s %(levelname)-8s %(message)s',
1223 datefmt='%a, %d %b %Y %H:%M:%S',
1224 filename='/temp/myapp.log',
1225 filemode='w')
1226 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1227
1228which would result in ::
1229
1230 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1231
1232
1233.. _multiple-destinations:
1234
1235Logging to multiple destinations
1236--------------------------------
1237
1238Let's say you want to log to console and file with different message formats and
1239in differing circumstances. Say you want to log messages with levels of DEBUG
1240and higher to file, and those messages at level INFO and higher to the console.
1241Let's also assume that the file should contain timestamps, but the console
1242messages should not. Here's how you can achieve this::
1243
1244 import logging
1245
1246 # set up logging to file - see previous section for more details
1247 logging.basicConfig(level=logging.DEBUG,
1248 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1249 datefmt='%m-%d %H:%M',
1250 filename='/temp/myapp.log',
1251 filemode='w')
1252 # define a Handler which writes INFO messages or higher to the sys.stderr
1253 console = logging.StreamHandler()
1254 console.setLevel(logging.INFO)
1255 # set a format which is simpler for console use
1256 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1257 # tell the handler to use this format
1258 console.setFormatter(formatter)
1259 # add the handler to the root logger
1260 logging.getLogger('').addHandler(console)
1261
1262 # Now, we can log to the root logger, or any other logger. First the root...
1263 logging.info('Jackdaws love my big sphinx of quartz.')
1264
1265 # Now, define a couple of other loggers which might represent areas in your
1266 # application:
1267
1268 logger1 = logging.getLogger('myapp.area1')
1269 logger2 = logging.getLogger('myapp.area2')
1270
1271 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1272 logger1.info('How quickly daft jumping zebras vex.')
1273 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1274 logger2.error('The five boxing wizards jump quickly.')
1275
1276When you run this, on the console you will see ::
1277
1278 root : INFO Jackdaws love my big sphinx of quartz.
1279 myapp.area1 : INFO How quickly daft jumping zebras vex.
1280 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1281 myapp.area2 : ERROR The five boxing wizards jump quickly.
1282
1283and in the file you will see something like ::
1284
1285 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1286 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1287 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1288 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1289 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1290
1291As you can see, the DEBUG message only shows up in the file. The other messages
1292are sent to both destinations.
1293
1294This example uses console and file handlers, but you can use any number and
1295combination of handlers you choose.
1296
Vinay Sajip333c6e72009-08-20 22:04:32 +00001297.. _logging-exceptions:
1298
1299Exceptions raised during logging
1300--------------------------------
1301
1302The logging package is designed to swallow exceptions which occur while logging
1303in production. This is so that errors which occur while handling logging events
1304- such as logging misconfiguration, network or other similar errors - do not
1305cause the application using logging to terminate prematurely.
1306
1307:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1308swallowed. Other exceptions which occur during the :meth:`emit` method of a
1309:class:`Handler` subclass are passed to its :meth:`handleError` method.
1310
1311The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlf6d367452010-03-12 10:02:03 +00001312to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1313traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip333c6e72009-08-20 22:04:32 +00001314
Georg Brandlf6d367452010-03-12 10:02:03 +00001315**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip333c6e72009-08-20 22:04:32 +00001316during development, you typically want to be notified of any exceptions that
Georg Brandlf6d367452010-03-12 10:02:03 +00001317occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip333c6e72009-08-20 22:04:32 +00001318usage.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001319
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001320.. _context-info:
1321
1322Adding contextual information to your logging output
1323----------------------------------------------------
1324
1325Sometimes you want logging output to contain contextual information in
1326addition to the parameters passed to the logging call. For example, in a
1327networked application, it may be desirable to log client-specific information
1328in the log (e.g. remote client's username, or IP address). Although you could
1329use the *extra* parameter to achieve this, it's not always convenient to pass
1330the information in this way. While it might be tempting to create
1331:class:`Logger` instances on a per-connection basis, this is not a good idea
1332because these instances are not garbage collected. While this is not a problem
1333in practice, when the number of :class:`Logger` instances is dependent on the
1334level of granularity you want to use in logging an application, it could
1335be hard to manage if the number of :class:`Logger` instances becomes
1336effectively unbounded.
1337
Vinay Sajipc7403352008-01-18 15:54:14 +00001338An easy way in which you can pass contextual information to be output along
1339with logging event information is to use the :class:`LoggerAdapter` class.
1340This class is designed to look like a :class:`Logger`, so that you can call
1341:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1342:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1343same signatures as their counterparts in :class:`Logger`, so you can use the
1344two types of instances interchangeably.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001345
Vinay Sajipc7403352008-01-18 15:54:14 +00001346When you create an instance of :class:`LoggerAdapter`, you pass it a
1347:class:`Logger` instance and a dict-like object which contains your contextual
1348information. When you call one of the logging methods on an instance of
1349:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1350:class:`Logger` passed to its constructor, and arranges to pass the contextual
1351information in the delegated call. Here's a snippet from the code of
1352:class:`LoggerAdapter`::
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001353
Vinay Sajipc7403352008-01-18 15:54:14 +00001354 def debug(self, msg, *args, **kwargs):
1355 """
1356 Delegate a debug call to the underlying logger, after adding
1357 contextual information from this adapter instance.
1358 """
1359 msg, kwargs = self.process(msg, kwargs)
1360 self.logger.debug(msg, *args, **kwargs)
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001361
Vinay Sajipc7403352008-01-18 15:54:14 +00001362The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1363information is added to the logging output. It's passed the message and
1364keyword arguments of the logging call, and it passes back (potentially)
1365modified versions of these to use in the call to the underlying logger. The
1366default implementation of this method leaves the message alone, but inserts
1367an "extra" key in the keyword argument whose value is the dict-like object
1368passed to the constructor. Of course, if you had passed an "extra" keyword
1369argument in the call to the adapter, it will be silently overwritten.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001370
Vinay Sajipc7403352008-01-18 15:54:14 +00001371The advantage of using "extra" is that the values in the dict-like object are
1372merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1373customized strings with your :class:`Formatter` instances which know about
1374the keys of the dict-like object. If you need a different method, e.g. if you
1375want to prepend or append the contextual information to the message string,
1376you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1377to do what you need. Here's an example script which uses this class, which
1378also illustrates what dict-like behaviour is needed from an arbitrary
1379"dict-like" object for use in the constructor::
1380
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001381 import logging
Vinay Sajip733024a2008-01-21 17:39:22 +00001382
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001383 class ConnInfo:
1384 """
1385 An example class which shows how an arbitrary class can be used as
1386 the 'extra' context information repository passed to a LoggerAdapter.
1387 """
Vinay Sajip733024a2008-01-21 17:39:22 +00001388
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001389 def __getitem__(self, name):
1390 """
1391 To allow this instance to look like a dict.
1392 """
1393 from random import choice
1394 if name == "ip":
1395 result = choice(["127.0.0.1", "192.168.0.1"])
1396 elif name == "user":
1397 result = choice(["jim", "fred", "sheila"])
1398 else:
1399 result = self.__dict__.get(name, "?")
1400 return result
Vinay Sajip733024a2008-01-21 17:39:22 +00001401
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001402 def __iter__(self):
1403 """
1404 To allow iteration over keys, which will be merged into
1405 the LogRecord dict before formatting and output.
1406 """
1407 keys = ["ip", "user"]
1408 keys.extend(self.__dict__.keys())
1409 return keys.__iter__()
Vinay Sajip733024a2008-01-21 17:39:22 +00001410
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001411 if __name__ == "__main__":
1412 from random import choice
1413 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1414 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1415 { "ip" : "123.231.231.123", "user" : "sheila" })
1416 logging.basicConfig(level=logging.DEBUG,
1417 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1418 a1.debug("A debug message")
1419 a1.info("An info message with %s", "some parameters")
1420 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1421 for x in range(10):
1422 lvl = choice(levels)
1423 lvlname = logging.getLevelName(lvl)
1424 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Vinay Sajipc7403352008-01-18 15:54:14 +00001425
1426When this script is run, the output should look something like this::
1427
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001428 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1429 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1430 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
1431 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
1432 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
1433 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
1434 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
1435 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
1436 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
1437 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
1438 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
1439 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 +00001440
1441.. versionadded:: 2.6
1442
1443The :class:`LoggerAdapter` class was not present in previous versions.
1444
Vinay Sajip3a0dc302009-08-15 23:23:12 +00001445.. _multiple-processes:
1446
1447Logging to a single file from multiple processes
1448------------------------------------------------
1449
1450Although logging is thread-safe, and logging to a single file from multiple
1451threads in a single process *is* supported, logging to a single file from
1452*multiple processes* is *not* supported, because there is no standard way to
1453serialize access to a single file across multiple processes in Python. If you
1454need to log to a single file from multiple processes, the best way of doing
1455this is to have all the processes log to a :class:`SocketHandler`, and have a
1456separate process which implements a socket server which reads from the socket
1457and logs to file. (If you prefer, you can dedicate one thread in one of the
1458existing processes to perform this function.) The following section documents
1459this approach in more detail and includes a working socket receiver which can
1460be used as a starting point for you to adapt in your own applications.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001461
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001462If you are using a recent version of Python which includes the
1463:mod:`multiprocessing` module, you can write your own handler which uses the
1464:class:`Lock` class from this module to serialize access to the file from
1465your processes. The existing :class:`FileHandler` and subclasses do not make
1466use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip5e7f6452009-08-17 13:14:37 +00001467Note that at present, the :mod:`multiprocessing` module does not provide
1468working lock functionality on all platforms (see
1469http://bugs.python.org/issue3770).
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001470
Georg Brandl8ec7f652007-08-15 14:28:01 +00001471.. _network-logging:
1472
1473Sending and receiving logging events across a network
1474-----------------------------------------------------
1475
1476Let's say you want to send logging events across a network, and handle them at
1477the receiving end. A simple way of doing this is attaching a
1478:class:`SocketHandler` instance to the root logger at the sending end::
1479
Benjamin Petersona7b55a32009-02-20 03:31:23 +00001480 import logging, logging.handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +00001481
1482 rootLogger = logging.getLogger('')
1483 rootLogger.setLevel(logging.DEBUG)
1484 socketHandler = logging.handlers.SocketHandler('localhost',
1485 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1486 # don't bother with a formatter, since a socket handler sends the event as
1487 # an unformatted pickle
1488 rootLogger.addHandler(socketHandler)
1489
1490 # Now, we can log to the root logger, or any other logger. First the root...
1491 logging.info('Jackdaws love my big sphinx of quartz.')
1492
1493 # Now, define a couple of other loggers which might represent areas in your
1494 # application:
1495
1496 logger1 = logging.getLogger('myapp.area1')
1497 logger2 = logging.getLogger('myapp.area2')
1498
1499 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1500 logger1.info('How quickly daft jumping zebras vex.')
1501 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1502 logger2.error('The five boxing wizards jump quickly.')
1503
Georg Brandle152a772008-05-24 18:31:28 +00001504At the receiving end, you can set up a receiver using the :mod:`SocketServer`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001505module. Here is a basic working example::
1506
1507 import cPickle
1508 import logging
1509 import logging.handlers
Georg Brandle152a772008-05-24 18:31:28 +00001510 import SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001511 import struct
1512
1513
Georg Brandle152a772008-05-24 18:31:28 +00001514 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001515 """Handler for a streaming logging request.
1516
1517 This basically logs the record using whatever logging policy is
1518 configured locally.
1519 """
1520
1521 def handle(self):
1522 """
1523 Handle multiple requests - each expected to be a 4-byte length,
1524 followed by the LogRecord in pickle format. Logs the record
1525 according to whatever policy is configured locally.
1526 """
1527 while 1:
1528 chunk = self.connection.recv(4)
1529 if len(chunk) < 4:
1530 break
1531 slen = struct.unpack(">L", chunk)[0]
1532 chunk = self.connection.recv(slen)
1533 while len(chunk) < slen:
1534 chunk = chunk + self.connection.recv(slen - len(chunk))
1535 obj = self.unPickle(chunk)
1536 record = logging.makeLogRecord(obj)
1537 self.handleLogRecord(record)
1538
1539 def unPickle(self, data):
1540 return cPickle.loads(data)
1541
1542 def handleLogRecord(self, record):
1543 # if a name is specified, we use the named logger rather than the one
1544 # implied by the record.
1545 if self.server.logname is not None:
1546 name = self.server.logname
1547 else:
1548 name = record.name
1549 logger = logging.getLogger(name)
1550 # N.B. EVERY record gets logged. This is because Logger.handle
1551 # is normally called AFTER logger-level filtering. If you want
1552 # to do filtering, do it at the client end to save wasting
1553 # cycles and network bandwidth!
1554 logger.handle(record)
1555
Georg Brandle152a772008-05-24 18:31:28 +00001556 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001557 """simple TCP socket-based logging receiver suitable for testing.
1558 """
1559
1560 allow_reuse_address = 1
1561
1562 def __init__(self, host='localhost',
1563 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1564 handler=LogRecordStreamHandler):
Georg Brandle152a772008-05-24 18:31:28 +00001565 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001566 self.abort = 0
1567 self.timeout = 1
1568 self.logname = None
1569
1570 def serve_until_stopped(self):
1571 import select
1572 abort = 0
1573 while not abort:
1574 rd, wr, ex = select.select([self.socket.fileno()],
1575 [], [],
1576 self.timeout)
1577 if rd:
1578 self.handle_request()
1579 abort = self.abort
1580
1581 def main():
1582 logging.basicConfig(
1583 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1584 tcpserver = LogRecordSocketReceiver()
1585 print "About to start TCP server..."
1586 tcpserver.serve_until_stopped()
1587
1588 if __name__ == "__main__":
1589 main()
1590
1591First run the server, and then the client. On the client side, nothing is
1592printed on the console; on the server side, you should see something like::
1593
1594 About to start TCP server...
1595 59 root INFO Jackdaws love my big sphinx of quartz.
1596 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1597 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1598 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1599 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1600
Vinay Sajip80eed3e2010-07-06 15:08:55 +00001601Note that there are some security issues with pickle in some scenarios. If
1602these affect you, you can use an alternative serialization scheme by overriding
1603the :meth:`makePickle` method and implementing your alternative there, as
1604well as adapting the above script to use your alternative serialization.
1605
Vinay Sajipf778bec2009-09-22 17:23:41 +00001606Using arbitrary objects as messages
1607-----------------------------------
1608
1609In the preceding sections and examples, it has been assumed that the message
1610passed when logging the event is a string. However, this is not the only
1611possibility. You can pass an arbitrary object as a message, and its
1612:meth:`__str__` method will be called when the logging system needs to convert
1613it to a string representation. In fact, if you want to, you can avoid
1614computing a string representation altogether - for example, the
1615:class:`SocketHandler` emits an event by pickling it and sending it over the
1616wire.
1617
1618Optimization
1619------------
1620
1621Formatting of message arguments is deferred until it cannot be avoided.
1622However, computing the arguments passed to the logging method can also be
1623expensive, and you may want to avoid doing it if the logger will just throw
1624away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1625method which takes a level argument and returns true if the event would be
1626created by the Logger for that level of call. You can write code like this::
1627
1628 if logger.isEnabledFor(logging.DEBUG):
1629 logger.debug("Message with %s, %s", expensive_func1(),
1630 expensive_func2())
1631
1632so that if the logger's threshold is set above ``DEBUG``, the calls to
1633:func:`expensive_func1` and :func:`expensive_func2` are never made.
1634
1635There are other optimizations which can be made for specific applications which
1636need more precise control over what logging information is collected. Here's a
1637list of things you can do to avoid processing during logging which you don't
1638need:
1639
1640+-----------------------------------------------+----------------------------------------+
1641| What you don't want to collect | How to avoid collecting it |
1642+===============================================+========================================+
1643| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1644+-----------------------------------------------+----------------------------------------+
1645| Threading information. | Set ``logging.logThreads`` to ``0``. |
1646+-----------------------------------------------+----------------------------------------+
1647| Process information. | Set ``logging.logProcesses`` to ``0``. |
1648+-----------------------------------------------+----------------------------------------+
1649
1650Also note that the core logging module only includes the basic handlers. If
1651you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1652take up any memory.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001653
Vinay Sajip4b782332009-01-19 06:49:19 +00001654.. _handler:
1655
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656Handler Objects
1657---------------
1658
1659Handlers have the following attributes and methods. Note that :class:`Handler`
1660is never instantiated directly; this class acts as a base for more useful
1661subclasses. However, the :meth:`__init__` method in subclasses needs to call
1662:meth:`Handler.__init__`.
1663
1664
1665.. method:: Handler.__init__(level=NOTSET)
1666
1667 Initializes the :class:`Handler` instance by setting its level, setting the list
1668 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1669 serializing access to an I/O mechanism.
1670
1671
1672.. method:: Handler.createLock()
1673
1674 Initializes a thread lock which can be used to serialize access to underlying
1675 I/O functionality which may not be threadsafe.
1676
1677
1678.. method:: Handler.acquire()
1679
1680 Acquires the thread lock created with :meth:`createLock`.
1681
1682
1683.. method:: Handler.release()
1684
1685 Releases the thread lock acquired with :meth:`acquire`.
1686
1687
1688.. method:: Handler.setLevel(lvl)
1689
1690 Sets the threshold for this handler to *lvl*. Logging messages which are less
1691 severe than *lvl* will be ignored. When a handler is created, the level is set
1692 to :const:`NOTSET` (which causes all messages to be processed).
1693
1694
1695.. method:: Handler.setFormatter(form)
1696
1697 Sets the :class:`Formatter` for this handler to *form*.
1698
1699
1700.. method:: Handler.addFilter(filt)
1701
1702 Adds the specified filter *filt* to this handler.
1703
1704
1705.. method:: Handler.removeFilter(filt)
1706
1707 Removes the specified filter *filt* from this handler.
1708
1709
1710.. method:: Handler.filter(record)
1711
1712 Applies this handler's filters to the record and returns a true value if the
1713 record is to be processed.
1714
1715
1716.. method:: Handler.flush()
1717
1718 Ensure all logging output has been flushed. This version does nothing and is
1719 intended to be implemented by subclasses.
1720
1721
1722.. method:: Handler.close()
1723
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001724 Tidy up any resources used by the handler. This version does no output but
1725 removes the handler from an internal list of handlers which is closed when
1726 :func:`shutdown` is called. Subclasses should ensure that this gets called
1727 from overridden :meth:`close` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001728
1729
1730.. method:: Handler.handle(record)
1731
1732 Conditionally emits the specified logging record, depending on filters which may
1733 have been added to the handler. Wraps the actual emission of the record with
1734 acquisition/release of the I/O thread lock.
1735
1736
1737.. method:: Handler.handleError(record)
1738
1739 This method should be called from handlers when an exception is encountered
1740 during an :meth:`emit` call. By default it does nothing, which means that
1741 exceptions get silently ignored. This is what is mostly wanted for a logging
1742 system - most users will not care about errors in the logging system, they are
1743 more interested in application errors. You could, however, replace this with a
1744 custom handler if you wish. The specified record is the one which was being
1745 processed when the exception occurred.
1746
1747
1748.. method:: Handler.format(record)
1749
1750 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1751 default formatter for the module.
1752
1753
1754.. method:: Handler.emit(record)
1755
1756 Do whatever it takes to actually log the specified logging record. This version
1757 is intended to be implemented by subclasses and so raises a
1758 :exc:`NotImplementedError`.
1759
1760
Vinay Sajip4b782332009-01-19 06:49:19 +00001761.. _stream-handler:
1762
Georg Brandl8ec7f652007-08-15 14:28:01 +00001763StreamHandler
1764^^^^^^^^^^^^^
1765
1766The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1767sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1768file-like object (or, more precisely, any object which supports :meth:`write`
1769and :meth:`flush` methods).
1770
1771
Vinay Sajip0c6a0e32009-12-17 14:52:00 +00001772.. currentmodule:: logging
1773
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001774.. class:: StreamHandler([stream])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001775
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001776 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001777 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1778 will be used.
1779
1780
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001781 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001782
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001783 If a formatter is specified, it is used to format the record. The record
1784 is then written to the stream with a trailing newline. If exception
1785 information is present, it is formatted using
1786 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001787
1788
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001789 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001790
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001791 Flushes the stream by calling its :meth:`flush` method. Note that the
1792 :meth:`close` method is inherited from :class:`Handler` and so does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001793 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001794
1795
Vinay Sajip4b782332009-01-19 06:49:19 +00001796.. _file-handler:
1797
Georg Brandl8ec7f652007-08-15 14:28:01 +00001798FileHandler
1799^^^^^^^^^^^
1800
1801The :class:`FileHandler` class, located in the core :mod:`logging` package,
1802sends logging output to a disk file. It inherits the output functionality from
1803:class:`StreamHandler`.
1804
1805
Vinay Sajipf38ba782008-01-24 12:38:30 +00001806.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001807
1808 Returns a new instance of the :class:`FileHandler` class. The specified file is
1809 opened and used as the stream for logging. If *mode* is not specified,
1810 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001811 with that encoding. If *delay* is true, then file opening is deferred until the
1812 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001813
Vinay Sajip59584c42009-08-14 11:33:54 +00001814 .. versionchanged:: 2.6
1815 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001816
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001817 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001818
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001819 Closes the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001820
1821
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001822 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001823
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001824 Outputs the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001825
Vinay Sajip4b782332009-01-19 06:49:19 +00001826.. _null-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001827
Vinay Sajip51104862009-01-02 18:53:04 +00001828NullHandler
1829^^^^^^^^^^^
1830
1831.. versionadded:: 2.7
1832
1833The :class:`NullHandler` class, located in the core :mod:`logging` package,
1834does not do any formatting or output. It is essentially a "no-op" handler
1835for use by library developers.
1836
1837
1838.. class:: NullHandler()
1839
1840 Returns a new instance of the :class:`NullHandler` class.
1841
1842
1843 .. method:: emit(record)
1844
1845 This method does nothing.
1846
Vinay Sajip99505c82009-01-10 13:38:04 +00001847See :ref:`library-config` for more information on how to use
1848:class:`NullHandler`.
1849
Vinay Sajip4b782332009-01-19 06:49:19 +00001850.. _watched-file-handler:
1851
Georg Brandl8ec7f652007-08-15 14:28:01 +00001852WatchedFileHandler
1853^^^^^^^^^^^^^^^^^^
1854
1855.. versionadded:: 2.6
1856
Vinay Sajipb1a15e42009-01-15 23:04:47 +00001857.. currentmodule:: logging.handlers
Vinay Sajip51104862009-01-02 18:53:04 +00001858
Georg Brandl8ec7f652007-08-15 14:28:01 +00001859The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1860module, is a :class:`FileHandler` which watches the file it is logging to. If
1861the file changes, it is closed and reopened using the file name.
1862
1863A file change can happen because of usage of programs such as *newsyslog* and
1864*logrotate* which perform log file rotation. This handler, intended for use
1865under Unix/Linux, watches the file to see if it has changed since the last emit.
1866(A file is deemed to have changed if its device or inode have changed.) If the
1867file has changed, the old file stream is closed, and the file opened to get a
1868new stream.
1869
1870This handler is not appropriate for use under Windows, because under Windows
1871open log files cannot be moved or renamed - logging opens the files with
1872exclusive locks - and so there is no need for such a handler. Furthermore,
1873*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1874this value.
1875
1876
Vinay Sajipf38ba782008-01-24 12:38:30 +00001877.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001878
1879 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1880 file is opened and used as the stream for logging. If *mode* is not specified,
1881 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001882 with that encoding. If *delay* is true, then file opening is deferred until the
1883 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001884
Vinay Sajip59584c42009-08-14 11:33:54 +00001885 .. versionchanged:: 2.6
1886 *delay* was added.
1887
Georg Brandl8ec7f652007-08-15 14:28:01 +00001888
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001889 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001890
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001891 Outputs the record to the file, but first checks to see if the file has
1892 changed. If it has, the existing stream is flushed and closed and the
1893 file opened again, before outputting the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001894
Vinay Sajip4b782332009-01-19 06:49:19 +00001895.. _rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001896
1897RotatingFileHandler
1898^^^^^^^^^^^^^^^^^^^
1899
1900The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1901module, supports rotation of disk log files.
1902
1903
Vinay Sajipf38ba782008-01-24 12:38:30 +00001904.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001905
1906 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1907 file is opened and used as the stream for logging. If *mode* is not specified,
Vinay Sajipf38ba782008-01-24 12:38:30 +00001908 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
1909 with that encoding. If *delay* is true, then file opening is deferred until the
1910 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001911
1912 You can use the *maxBytes* and *backupCount* values to allow the file to
1913 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1914 the file is closed and a new file is silently opened for output. Rollover occurs
1915 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1916 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1917 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1918 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1919 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1920 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1921 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1922 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1923 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1924
Vinay Sajip59584c42009-08-14 11:33:54 +00001925 .. versionchanged:: 2.6
1926 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001927
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001928 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001929
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001930 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001931
1932
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001933 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001934
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001935 Outputs the record to the file, catering for rollover as described
1936 previously.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001937
Vinay Sajip4b782332009-01-19 06:49:19 +00001938.. _timed-rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001939
1940TimedRotatingFileHandler
1941^^^^^^^^^^^^^^^^^^^^^^^^
1942
1943The :class:`TimedRotatingFileHandler` class, located in the
1944:mod:`logging.handlers` module, supports rotation of disk log files at certain
1945timed intervals.
1946
1947
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001948.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001949
1950 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1951 specified file is opened and used as the stream for logging. On rotating it also
1952 sets the filename suffix. Rotating happens based on the product of *when* and
1953 *interval*.
1954
1955 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandld77554f2008-06-06 07:34:50 +00001956 values is below. Note that they are not case sensitive.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001957
Georg Brandl72780a42008-03-02 13:41:39 +00001958 +----------------+-----------------------+
1959 | Value | Type of interval |
1960 +================+=======================+
1961 | ``'S'`` | Seconds |
1962 +----------------+-----------------------+
1963 | ``'M'`` | Minutes |
1964 +----------------+-----------------------+
1965 | ``'H'`` | Hours |
1966 +----------------+-----------------------+
1967 | ``'D'`` | Days |
1968 +----------------+-----------------------+
1969 | ``'W'`` | Week day (0=Monday) |
1970 +----------------+-----------------------+
1971 | ``'midnight'`` | Roll over at midnight |
1972 +----------------+-----------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001973
Georg Brandle6dab2a2008-03-02 14:15:04 +00001974 The system will save old log files by appending extensions to the filename.
1975 The extensions are date-and-time based, using the strftime format
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001976 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Vinay Sajip2a649f92008-07-18 09:00:35 +00001977 rollover interval.
Vinay Sajipecfa08f2010-03-12 09:16:10 +00001978
1979 When computing the next rollover time for the first time (when the handler
1980 is created), the last modification time of an existing log file, or else
1981 the current time, is used to compute when the next rotation will occur.
1982
Georg Brandld77554f2008-06-06 07:34:50 +00001983 If the *utc* argument is true, times in UTC will be used; otherwise
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001984 local time is used.
1985
1986 If *backupCount* is nonzero, at most *backupCount* files
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001987 will be kept, and if more would be created when rollover occurs, the oldest
1988 one is deleted. The deletion logic uses the interval to determine which
1989 files to delete, so changing the interval may leave old files lying around.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001990
Vinay Sajip59584c42009-08-14 11:33:54 +00001991 If *delay* is true, then file opening is deferred until the first call to
1992 :meth:`emit`.
1993
1994 .. versionchanged:: 2.6
1995 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001996
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001997 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001998
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001999 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002000
2001
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002002 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002003
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002004 Outputs the record to the file, catering for rollover as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002005
2006
Vinay Sajip4b782332009-01-19 06:49:19 +00002007.. _socket-handler:
2008
Georg Brandl8ec7f652007-08-15 14:28:01 +00002009SocketHandler
2010^^^^^^^^^^^^^
2011
2012The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2013sends logging output to a network socket. The base class uses a TCP socket.
2014
2015
2016.. class:: SocketHandler(host, port)
2017
2018 Returns a new instance of the :class:`SocketHandler` class intended to
2019 communicate with a remote machine whose address is given by *host* and *port*.
2020
2021
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002022 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002023
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002024 Closes the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002025
2026
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002027 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002028
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002029 Pickles the record's attribute dictionary and writes it to the socket in
2030 binary format. If there is an error with the socket, silently drops the
2031 packet. If the connection was previously lost, re-establishes the
2032 connection. To unpickle the record at the receiving end into a
2033 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002034
2035
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002036 .. method:: handleError()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002037
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002038 Handles an error which has occurred during :meth:`emit`. The most likely
2039 cause is a lost connection. Closes the socket so that we can retry on the
2040 next event.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002041
2042
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002043 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002044
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002045 This is a factory method which allows subclasses to define the precise
2046 type of socket they want. The default implementation creates a TCP socket
2047 (:const:`socket.SOCK_STREAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002048
2049
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002050 .. method:: makePickle(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002051
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002052 Pickles the record's attribute dictionary in binary format with a length
2053 prefix, and returns it ready for transmission across the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002054
Vinay Sajip86aa9052010-06-29 15:13:14 +00002055 Note that pickles aren't completely secure. If you are concerned about
2056 security, you may want to override this method to implement a more secure
2057 mechanism. For example, you can sign pickles using HMAC and then verify
2058 them on the receiving end, or alternatively you can disable unpickling of
2059 global objects on the receiving end.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002060
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002061 .. method:: send(packet)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002062
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002063 Send a pickled string *packet* to the socket. This function allows for
2064 partial sends which can happen when the network is busy.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002065
2066
Vinay Sajip4b782332009-01-19 06:49:19 +00002067.. _datagram-handler:
2068
Georg Brandl8ec7f652007-08-15 14:28:01 +00002069DatagramHandler
2070^^^^^^^^^^^^^^^
2071
2072The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2073module, inherits from :class:`SocketHandler` to support sending logging messages
2074over UDP sockets.
2075
2076
2077.. class:: DatagramHandler(host, port)
2078
2079 Returns a new instance of the :class:`DatagramHandler` class intended to
2080 communicate with a remote machine whose address is given by *host* and *port*.
2081
2082
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002083 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002084
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002085 Pickles the record's attribute dictionary and writes it to the socket in
2086 binary format. If there is an error with the socket, silently drops the
2087 packet. To unpickle the record at the receiving end into a
2088 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002089
2090
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002091 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002092
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002093 The factory method of :class:`SocketHandler` is here overridden to create
2094 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002095
2096
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002097 .. method:: send(s)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002098
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002099 Send a pickled string to a socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002100
2101
Vinay Sajip4b782332009-01-19 06:49:19 +00002102.. _syslog-handler:
2103
Georg Brandl8ec7f652007-08-15 14:28:01 +00002104SysLogHandler
2105^^^^^^^^^^^^^
2106
2107The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2108supports sending logging messages to a remote or local Unix syslog.
2109
2110
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002111.. class:: SysLogHandler([address[, facility[, socktype]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002112
2113 Returns a new instance of the :class:`SysLogHandler` class intended to
2114 communicate with a remote Unix machine whose address is given by *address* in
2115 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002116 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl8ec7f652007-08-15 14:28:01 +00002117 alternative to providing a ``(host, port)`` tuple is providing an address as a
2118 string, for example "/dev/log". In this case, a Unix domain socket is used to
2119 send the message to the syslog. If *facility* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002120 :const:`LOG_USER` is used. The type of socket opened depends on the
2121 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2122 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2123 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2124
2125 .. versionchanged:: 2.7
2126 *socktype* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002127
2128
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002129 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002130
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002131 Closes the socket to the remote host.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002132
2133
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002134 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002135
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002136 The record is formatted, and then sent to the syslog server. If exception
2137 information is present, it is *not* sent to the server.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002138
2139
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002140 .. method:: encodePriority(facility, priority)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002141
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002142 Encodes the facility and priority into an integer. You can pass in strings
2143 or integers - if strings are passed, internal mapping dictionaries are
2144 used to convert them to integers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002145
Vinay Sajipa3c39c02010-03-24 15:10:40 +00002146 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2147 mirror the values defined in the ``sys/syslog.h`` header file.
Vinay Sajipb0623d62010-03-24 14:31:21 +00002148
Georg Brandld3bab6a2010-04-02 09:03:18 +00002149 **Priorities**
2150
Vinay Sajipb0623d62010-03-24 14:31:21 +00002151 +--------------------------+---------------+
2152 | Name (string) | Symbolic value|
2153 +==========================+===============+
2154 | ``alert`` | LOG_ALERT |
2155 +--------------------------+---------------+
2156 | ``crit`` or ``critical`` | LOG_CRIT |
2157 +--------------------------+---------------+
2158 | ``debug`` | LOG_DEBUG |
2159 +--------------------------+---------------+
2160 | ``emerg`` or ``panic`` | LOG_EMERG |
2161 +--------------------------+---------------+
2162 | ``err`` or ``error`` | LOG_ERR |
2163 +--------------------------+---------------+
2164 | ``info`` | LOG_INFO |
2165 +--------------------------+---------------+
2166 | ``notice`` | LOG_NOTICE |
2167 +--------------------------+---------------+
2168 | ``warn`` or ``warning`` | LOG_WARNING |
2169 +--------------------------+---------------+
2170
Georg Brandld3bab6a2010-04-02 09:03:18 +00002171 **Facilities**
2172
Vinay Sajipb0623d62010-03-24 14:31:21 +00002173 +---------------+---------------+
2174 | Name (string) | Symbolic value|
2175 +===============+===============+
2176 | ``auth`` | LOG_AUTH |
2177 +---------------+---------------+
2178 | ``authpriv`` | LOG_AUTHPRIV |
2179 +---------------+---------------+
2180 | ``cron`` | LOG_CRON |
2181 +---------------+---------------+
2182 | ``daemon`` | LOG_DAEMON |
2183 +---------------+---------------+
2184 | ``ftp`` | LOG_FTP |
2185 +---------------+---------------+
2186 | ``kern`` | LOG_KERN |
2187 +---------------+---------------+
2188 | ``lpr`` | LOG_LPR |
2189 +---------------+---------------+
2190 | ``mail`` | LOG_MAIL |
2191 +---------------+---------------+
2192 | ``news`` | LOG_NEWS |
2193 +---------------+---------------+
2194 | ``syslog`` | LOG_SYSLOG |
2195 +---------------+---------------+
2196 | ``user`` | LOG_USER |
2197 +---------------+---------------+
2198 | ``uucp`` | LOG_UUCP |
2199 +---------------+---------------+
2200 | ``local0`` | LOG_LOCAL0 |
2201 +---------------+---------------+
2202 | ``local1`` | LOG_LOCAL1 |
2203 +---------------+---------------+
2204 | ``local2`` | LOG_LOCAL2 |
2205 +---------------+---------------+
2206 | ``local3`` | LOG_LOCAL3 |
2207 +---------------+---------------+
2208 | ``local4`` | LOG_LOCAL4 |
2209 +---------------+---------------+
2210 | ``local5`` | LOG_LOCAL5 |
2211 +---------------+---------------+
2212 | ``local6`` | LOG_LOCAL6 |
2213 +---------------+---------------+
2214 | ``local7`` | LOG_LOCAL7 |
2215 +---------------+---------------+
2216
Vinay Sajip66d19e22010-03-24 17:36:35 +00002217 .. method:: mapPriority(levelname)
2218
2219 Maps a logging level name to a syslog priority name.
2220 You may need to override this if you are using custom levels, or
2221 if the default algorithm is not suitable for your needs. The
2222 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2223 ``CRITICAL`` to the equivalent syslog names, and all other level
2224 names to "warning".
Georg Brandl8ec7f652007-08-15 14:28:01 +00002225
Vinay Sajip4b782332009-01-19 06:49:19 +00002226.. _nt-eventlog-handler:
2227
Georg Brandl8ec7f652007-08-15 14:28:01 +00002228NTEventLogHandler
2229^^^^^^^^^^^^^^^^^
2230
2231The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2232module, supports sending logging messages to a local Windows NT, Windows 2000 or
2233Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2234extensions for Python installed.
2235
2236
2237.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
2238
2239 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2240 used to define the application name as it appears in the event log. An
2241 appropriate registry entry is created using this name. The *dllname* should give
2242 the fully qualified pathname of a .dll or .exe which contains message
2243 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2244 - this is installed with the Win32 extensions and contains some basic
2245 placeholder message definitions. Note that use of these placeholders will make
2246 your event logs big, as the entire message source is held in the log. If you
2247 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2248 contains the message definitions you want to use in the event log). The
2249 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2250 defaults to ``'Application'``.
2251
2252
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002253 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002254
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002255 At this point, you can remove the application name from the registry as a
2256 source of event log entries. However, if you do this, you will not be able
2257 to see the events as you intended in the Event Log Viewer - it needs to be
2258 able to access the registry to get the .dll name. The current version does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00002259 not do this.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002260
2261
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002262 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002263
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002264 Determines the message ID, event category and event type, and then logs
2265 the message in the NT event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002266
2267
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002268 .. method:: getEventCategory(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002269
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002270 Returns the event category for the record. Override this if you want to
2271 specify your own categories. This version returns 0.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002272
2273
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002274 .. method:: getEventType(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002275
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002276 Returns the event type for the record. Override this if you want to
2277 specify your own types. This version does a mapping using the handler's
2278 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2279 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2280 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2281 your own levels, you will either need to override this method or place a
2282 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002283
2284
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002285 .. method:: getMessageID(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002286
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002287 Returns the message ID for the record. If you are using your own messages,
2288 you could do this by having the *msg* passed to the logger being an ID
2289 rather than a format string. Then, in here, you could use a dictionary
2290 lookup to get the message ID. This version returns 1, which is the base
2291 message ID in :file:`win32service.pyd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002292
Vinay Sajip4b782332009-01-19 06:49:19 +00002293.. _smtp-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002294
2295SMTPHandler
2296^^^^^^^^^^^
2297
2298The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2299supports sending logging messages to an email address via SMTP.
2300
2301
2302.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
2303
2304 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2305 initialized with the from and to addresses and subject line of the email. The
2306 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2307 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2308 the standard SMTP port is used. If your SMTP server requires authentication, you
2309 can specify a (username, password) tuple for the *credentials* argument.
2310
2311 .. versionchanged:: 2.6
2312 *credentials* was added.
2313
2314
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002315 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002316
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002317 Formats the record and sends it to the specified addressees.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002318
2319
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002320 .. method:: getSubject(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002321
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002322 If you want to specify a subject line which is record-dependent, override
2323 this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002324
Vinay Sajip4b782332009-01-19 06:49:19 +00002325.. _memory-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002326
2327MemoryHandler
2328^^^^^^^^^^^^^
2329
2330The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2331supports buffering of logging records in memory, periodically flushing them to a
2332:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2333event of a certain severity or greater is seen.
2334
2335:class:`MemoryHandler` is a subclass of the more general
2336:class:`BufferingHandler`, which is an abstract class. This buffers logging
2337records in memory. Whenever each record is added to the buffer, a check is made
2338by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2339should, then :meth:`flush` is expected to do the needful.
2340
2341
2342.. class:: BufferingHandler(capacity)
2343
2344 Initializes the handler with a buffer of the specified capacity.
2345
2346
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002347 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002348
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002349 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2350 calls :meth:`flush` to process the buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002351
2352
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002353 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002354
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002355 You can override this to implement custom flushing behavior. This version
2356 just zaps the buffer to empty.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002357
2358
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002359 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002360
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002361 Returns true if the buffer is up to capacity. This method can be
2362 overridden to implement custom flushing strategies.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002363
2364
2365.. class:: MemoryHandler(capacity[, flushLevel [, target]])
2366
2367 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2368 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2369 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2370 set using :meth:`setTarget` before this handler does anything useful.
2371
2372
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002373 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002374
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002375 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2376 buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002377
2378
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002379 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002380
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002381 For a :class:`MemoryHandler`, flushing means just sending the buffered
2382 records to the target, if there is one. Override if you want different
2383 behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002384
2385
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002386 .. method:: setTarget(target)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002387
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002388 Sets the target handler for this handler.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002389
2390
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002391 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002392
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002393 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002394
2395
Vinay Sajip4b782332009-01-19 06:49:19 +00002396.. _http-handler:
2397
Georg Brandl8ec7f652007-08-15 14:28:01 +00002398HTTPHandler
2399^^^^^^^^^^^
2400
2401The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2402supports sending logging messages to a Web server, using either ``GET`` or
2403``POST`` semantics.
2404
2405
2406.. class:: HTTPHandler(host, url[, method])
2407
2408 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2409 initialized with a host address, url and HTTP method. The *host* can be of the
2410 form ``host:port``, should you need to use a specific port number. If no
2411 *method* is specified, ``GET`` is used.
2412
2413
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002414 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002415
Senthil Kumaranbd13f452010-08-09 20:14:11 +00002416 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002417
2418
Vinay Sajip4b782332009-01-19 06:49:19 +00002419.. _formatter:
Georg Brandlc37f2882007-12-04 17:46:27 +00002420
Georg Brandl8ec7f652007-08-15 14:28:01 +00002421Formatter Objects
2422-----------------
2423
Georg Brandl430effb2009-01-01 13:05:13 +00002424.. currentmodule:: logging
2425
Georg Brandl8ec7f652007-08-15 14:28:01 +00002426:class:`Formatter`\ s have the following attributes and methods. They are
2427responsible for converting a :class:`LogRecord` to (usually) a string which can
2428be interpreted by either a human or an external system. The base
2429:class:`Formatter` allows a formatting string to be specified. If none is
2430supplied, the default value of ``'%(message)s'`` is used.
2431
2432A Formatter can be initialized with a format string which makes use of knowledge
2433of the :class:`LogRecord` attributes - such as the default value mentioned above
2434making use of the fact that the user's message and arguments are pre-formatted
2435into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti062d2b52009-12-19 22:41:49 +00002436standard Python %-style mapping keys. See section :ref:`string-formatting`
Georg Brandl8ec7f652007-08-15 14:28:01 +00002437for more information on string formatting.
2438
2439Currently, the useful mapping keys in a :class:`LogRecord` are:
2440
2441+-------------------------+-----------------------------------------------+
2442| Format | Description |
2443+=========================+===============================================+
2444| ``%(name)s`` | Name of the logger (logging channel). |
2445+-------------------------+-----------------------------------------------+
2446| ``%(levelno)s`` | Numeric logging level for the message |
2447| | (:const:`DEBUG`, :const:`INFO`, |
2448| | :const:`WARNING`, :const:`ERROR`, |
2449| | :const:`CRITICAL`). |
2450+-------------------------+-----------------------------------------------+
2451| ``%(levelname)s`` | Text logging level for the message |
2452| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2453| | ``'ERROR'``, ``'CRITICAL'``). |
2454+-------------------------+-----------------------------------------------+
2455| ``%(pathname)s`` | Full pathname of the source file where the |
2456| | logging call was issued (if available). |
2457+-------------------------+-----------------------------------------------+
2458| ``%(filename)s`` | Filename portion of pathname. |
2459+-------------------------+-----------------------------------------------+
2460| ``%(module)s`` | Module (name portion of filename). |
2461+-------------------------+-----------------------------------------------+
2462| ``%(funcName)s`` | Name of function containing the logging call. |
2463+-------------------------+-----------------------------------------------+
2464| ``%(lineno)d`` | Source line number where the logging call was |
2465| | issued (if available). |
2466+-------------------------+-----------------------------------------------+
2467| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2468| | (as returned by :func:`time.time`). |
2469+-------------------------+-----------------------------------------------+
2470| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2471| | created, relative to the time the logging |
2472| | module was loaded. |
2473+-------------------------+-----------------------------------------------+
2474| ``%(asctime)s`` | Human-readable time when the |
2475| | :class:`LogRecord` was created. By default |
2476| | this is of the form "2003-07-08 16:49:45,896" |
2477| | (the numbers after the comma are millisecond |
2478| | portion of the time). |
2479+-------------------------+-----------------------------------------------+
2480| ``%(msecs)d`` | Millisecond portion of the time when the |
2481| | :class:`LogRecord` was created. |
2482+-------------------------+-----------------------------------------------+
2483| ``%(thread)d`` | Thread ID (if available). |
2484+-------------------------+-----------------------------------------------+
2485| ``%(threadName)s`` | Thread name (if available). |
2486+-------------------------+-----------------------------------------------+
2487| ``%(process)d`` | Process ID (if available). |
2488+-------------------------+-----------------------------------------------+
2489| ``%(message)s`` | The logged message, computed as ``msg % |
2490| | args``. |
2491+-------------------------+-----------------------------------------------+
2492
2493.. versionchanged:: 2.5
2494 *funcName* was added.
2495
2496
2497.. class:: Formatter([fmt[, datefmt]])
2498
2499 Returns a new instance of the :class:`Formatter` class. The instance is
2500 initialized with a format string for the message as a whole, as well as a format
2501 string for the date/time portion of a message. If no *fmt* is specified,
2502 ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
2503 is used.
2504
2505
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002506 .. method:: format(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002507
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002508 The record's attribute dictionary is used as the operand to a string
2509 formatting operation. Returns the resulting string. Before formatting the
2510 dictionary, a couple of preparatory steps are carried out. The *message*
2511 attribute of the record is computed using *msg* % *args*. If the
2512 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2513 to format the event time. If there is exception information, it is
2514 formatted using :meth:`formatException` and appended to the message. Note
2515 that the formatted exception information is cached in attribute
2516 *exc_text*. This is useful because the exception information can be
2517 pickled and sent across the wire, but you should be careful if you have
2518 more than one :class:`Formatter` subclass which customizes the formatting
2519 of exception information. In this case, you will have to clear the cached
2520 value after a formatter has done its formatting, so that the next
2521 formatter to handle the event doesn't use the cached value but
2522 recalculates it afresh.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002523
2524
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002525 .. method:: formatTime(record[, datefmt])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002526
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002527 This method should be called from :meth:`format` by a formatter which
2528 wants to make use of a formatted time. This method can be overridden in
2529 formatters to provide for any specific requirement, but the basic behavior
2530 is as follows: if *datefmt* (a string) is specified, it is used with
2531 :func:`time.strftime` to format the creation time of the
2532 record. Otherwise, the ISO8601 format is used. The resulting string is
2533 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002534
2535
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002536 .. method:: formatException(exc_info)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002537
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002538 Formats the specified exception information (a standard exception tuple as
2539 returned by :func:`sys.exc_info`) as a string. This default implementation
2540 just uses :func:`traceback.print_exception`. The resulting string is
2541 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002542
Vinay Sajip4b782332009-01-19 06:49:19 +00002543.. _filter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002544
2545Filter Objects
2546--------------
2547
Vinay Sajip4b782332009-01-19 06:49:19 +00002548Filters can be used by :class:`Handler`\ s and :class:`Logger`\ s for
Georg Brandl8ec7f652007-08-15 14:28:01 +00002549more sophisticated filtering than is provided by levels. The base filter class
2550only allows events which are below a certain point in the logger hierarchy. For
2551example, a filter initialized with "A.B" will allow events logged by loggers
2552"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2553initialized with the empty string, all events are passed.
2554
2555
2556.. class:: Filter([name])
2557
2558 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2559 names a logger which, together with its children, will have its events allowed
2560 through the filter. If no name is specified, allows every event.
2561
2562
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002563 .. method:: filter(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002564
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002565 Is the specified record to be logged? Returns zero for no, nonzero for
2566 yes. If deemed appropriate, the record may be modified in-place by this
2567 method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002568
Vinay Sajip3478ac02010-08-19 19:17:41 +00002569Note that filters attached to handlers are consulted whenever an event is
2570emitted by the handler, whereas filters attached to loggers are consulted
2571whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
2572etc.) This means that events which have been generated by descendant loggers
2573will not be filtered by a logger's filter setting, unless the filter has also
2574been applied to those descendant loggers.
2575
Vinay Sajip4b782332009-01-19 06:49:19 +00002576.. _log-record:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002577
2578LogRecord Objects
2579-----------------
2580
2581:class:`LogRecord` instances are created every time something is logged. They
2582contain all the information pertinent to the event being logged. The main
2583information passed in is in msg and args, which are combined using msg % args to
2584create the message field of the record. The record also includes information
2585such as when the record was created, the source line where the logging call was
2586made, and any exception information to be logged.
2587
2588
2589.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
2590
2591 Returns an instance of :class:`LogRecord` initialized with interesting
2592 information. The *name* is the logger name; *lvl* is the numeric level;
2593 *pathname* is the absolute pathname of the source file in which the logging
2594 call was made; *lineno* is the line number in that file where the logging
2595 call is found; *msg* is the user-supplied message (a format string); *args*
2596 is the tuple which, together with *msg*, makes up the user message; and
2597 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2598 (or :const:`None`, if no exception information is available). The *func* is
2599 the name of the function from which the logging call was made. If not
2600 specified, it defaults to ``None``.
2601
2602 .. versionchanged:: 2.5
2603 *func* was added.
2604
2605
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002606 .. method:: getMessage()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002607
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002608 Returns the message for this :class:`LogRecord` instance after merging any
2609 user-supplied arguments with the message.
2610
Vinay Sajip4b782332009-01-19 06:49:19 +00002611.. _logger-adapter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002612
Vinay Sajipc7403352008-01-18 15:54:14 +00002613LoggerAdapter Objects
2614---------------------
2615
2616.. versionadded:: 2.6
2617
2618:class:`LoggerAdapter` instances are used to conveniently pass contextual
Vinay Sajip733024a2008-01-21 17:39:22 +00002619information into logging calls. For a usage example , see the section on
2620`adding contextual information to your logging output`__.
2621
2622__ context-info_
Vinay Sajipc7403352008-01-18 15:54:14 +00002623
2624.. class:: LoggerAdapter(logger, extra)
2625
2626 Returns an instance of :class:`LoggerAdapter` initialized with an
2627 underlying :class:`Logger` instance and a dict-like object.
2628
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002629 .. method:: process(msg, kwargs)
Vinay Sajipc7403352008-01-18 15:54:14 +00002630
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002631 Modifies the message and/or keyword arguments passed to a logging call in
2632 order to insert contextual information. This implementation takes the object
2633 passed as *extra* to the constructor and adds it to *kwargs* using key
2634 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2635 (possibly modified) versions of the arguments passed in.
Vinay Sajipc7403352008-01-18 15:54:14 +00002636
2637In addition to the above, :class:`LoggerAdapter` supports all the logging
2638methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2639:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2640methods have the same signatures as their counterparts in :class:`Logger`, so
2641you can use the two types of instances interchangeably.
2642
Vinay Sajip804899b2010-03-22 15:29:01 +00002643.. versionchanged:: 2.7
2644
2645The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method
2646delegates to the underlying logger.
2647
Georg Brandl8ec7f652007-08-15 14:28:01 +00002648
2649Thread Safety
2650-------------
2651
2652The logging module is intended to be thread-safe without any special work
2653needing to be done by its clients. It achieves this though using threading
2654locks; there is one lock to serialize access to the module's shared data, and
2655each handler also creates a lock to serialize access to its underlying I/O.
2656
Vinay Sajip353a85f2009-04-03 21:58:16 +00002657If you are implementing asynchronous signal handlers using the :mod:`signal`
2658module, you may not be able to use logging from within such handlers. This is
2659because lock implementations in the :mod:`threading` module are not always
2660re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002661
Vinay Sajip61afd262010-02-19 23:53:17 +00002662
2663Integration with the warnings module
2664------------------------------------
2665
2666The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2667with the :mod:`warnings` module.
2668
2669.. function:: captureWarnings(capture)
2670
2671 This function is used to turn the capture of warnings by logging on and
2672 off.
2673
Georg Brandlf6d367452010-03-12 10:02:03 +00002674 If *capture* is ``True``, warnings issued by the :mod:`warnings` module
Vinay Sajip61afd262010-02-19 23:53:17 +00002675 will be redirected to the logging system. Specifically, a warning will be
2676 formatted using :func:`warnings.formatwarning` and the resulting string
Georg Brandlf6d367452010-03-12 10:02:03 +00002677 logged to a logger named "py.warnings" with a severity of ``WARNING``.
Vinay Sajip61afd262010-02-19 23:53:17 +00002678
Georg Brandlf6d367452010-03-12 10:02:03 +00002679 If *capture* is ``False``, the redirection of warnings to the logging system
Vinay Sajip61afd262010-02-19 23:53:17 +00002680 will stop, and warnings will be redirected to their original destinations
Georg Brandlf6d367452010-03-12 10:02:03 +00002681 (i.e. those in effect before ``captureWarnings(True)`` was called).
Vinay Sajip61afd262010-02-19 23:53:17 +00002682
2683
Georg Brandl8ec7f652007-08-15 14:28:01 +00002684Configuration
2685-------------
2686
2687
2688.. _logging-config-api:
2689
2690Configuration functions
2691^^^^^^^^^^^^^^^^^^^^^^^
2692
Georg Brandl8ec7f652007-08-15 14:28:01 +00002693The following functions configure the logging module. They are located in the
2694:mod:`logging.config` module. Their use is optional --- you can configure the
2695logging module using these functions or by making calls to the main API (defined
2696in :mod:`logging` itself) and defining handlers which are declared either in
2697:mod:`logging` or :mod:`logging.handlers`.
2698
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002699.. function:: dictConfig(config)
2700
2701 Takes the logging configuration from a dictionary. The contents of
2702 this dictionary are described in :ref:`logging-config-dictschema`
2703 below.
2704
2705 If an error is encountered during configuration, this function will
2706 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2707 or :exc:`ImportError` with a suitably descriptive message. The
2708 following is a (possibly incomplete) list of conditions which will
2709 raise an error:
2710
2711 * A ``level`` which is not a string or which is a string not
2712 corresponding to an actual logging level.
2713 * A ``propagate`` value which is not a boolean.
2714 * An id which does not have a corresponding destination.
2715 * A non-existent handler id found during an incremental call.
2716 * An invalid logger name.
2717 * Inability to resolve to an internal or external object.
2718
2719 Parsing is performed by the :class:`DictConfigurator` class, whose
2720 constructor is passed the dictionary used for configuration, and
2721 has a :meth:`configure` method. The :mod:`logging.config` module
2722 has a callable attribute :attr:`dictConfigClass`
2723 which is initially set to :class:`DictConfigurator`.
2724 You can replace the value of :attr:`dictConfigClass` with a
2725 suitable implementation of your own.
2726
2727 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2728 the specified dictionary, and then calls the :meth:`configure` method on
2729 the returned object to put the configuration into effect::
2730
2731 def dictConfig(config):
2732 dictConfigClass(config).configure()
2733
2734 For example, a subclass of :class:`DictConfigurator` could call
2735 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2736 set up custom prefixes which would be usable in the subsequent
2737 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2738 this new subclass, and then :func:`dictConfig` could be called exactly as
2739 in the default, uncustomized state.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002740
2741.. function:: fileConfig(fname[, defaults])
2742
Vinay Sajip51104862009-01-02 18:53:04 +00002743 Reads the logging configuration from a :mod:`ConfigParser`\-format file named
2744 *fname*. This function can be called several times from an application,
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002745 allowing an end user to select from various pre-canned
Vinay Sajip51104862009-01-02 18:53:04 +00002746 configurations (if the developer provides a mechanism to present the choices
2747 and load the chosen configuration). Defaults to be passed to the ConfigParser
2748 can be specified in the *defaults* argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002749
Georg Brandl8ec7f652007-08-15 14:28:01 +00002750.. function:: listen([port])
2751
2752 Starts up a socket server on the specified port, and listens for new
2753 configurations. If no port is specified, the module's default
2754 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2755 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2756 :class:`Thread` instance on which you can call :meth:`start` to start the
2757 server, and which you can :meth:`join` when appropriate. To stop the server,
Georg Brandlc37f2882007-12-04 17:46:27 +00002758 call :func:`stopListening`.
2759
2760 To send a configuration to the socket, read in the configuration file and
2761 send it to the socket as a string of bytes preceded by a four-byte length
2762 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002763
2764
2765.. function:: stopListening()
2766
Georg Brandlc37f2882007-12-04 17:46:27 +00002767 Stops the listening server which was created with a call to :func:`listen`.
2768 This is typically called before calling :meth:`join` on the return value from
Georg Brandl8ec7f652007-08-15 14:28:01 +00002769 :func:`listen`.
2770
2771
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002772.. _logging-config-dictschema:
2773
2774Configuration dictionary schema
2775^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2776
2777Describing a logging configuration requires listing the various
2778objects to create and the connections between them; for example, you
2779may create a handler named "console" and then say that the logger
2780named "startup" will send its messages to the "console" handler.
2781These objects aren't limited to those provided by the :mod:`logging`
2782module because you might write your own formatter or handler class.
2783The parameters to these classes may also need to include external
2784objects such as ``sys.stderr``. The syntax for describing these
2785objects and connections is defined in :ref:`logging-config-dict-connections`
2786below.
2787
2788Dictionary Schema Details
2789"""""""""""""""""""""""""
2790
2791The dictionary passed to :func:`dictConfig` must contain the following
2792keys:
2793
2794* `version` - to be set to an integer value representing the schema
2795 version. The only valid value at present is 1, but having this key
2796 allows the schema to evolve while still preserving backwards
2797 compatibility.
2798
2799All other keys are optional, but if present they will be interpreted
2800as described below. In all cases below where a 'configuring dict' is
2801mentioned, it will be checked for the special ``'()'`` key to see if a
Andrew M. Kuchling1b553472010-05-16 23:31:16 +00002802custom instantiation is required. If so, the mechanism described in
2803:ref:`logging-config-dict-userdef` below is used to create an instance;
2804otherwise, the context is used to determine what to instantiate.
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002805
2806* `formatters` - the corresponding value will be a dict in which each
2807 key is a formatter id and each value is a dict describing how to
2808 configure the corresponding Formatter instance.
2809
2810 The configuring dict is searched for keys ``format`` and ``datefmt``
2811 (with defaults of ``None``) and these are used to construct a
2812 :class:`logging.Formatter` instance.
2813
2814* `filters` - the corresponding value will be a dict in which each key
2815 is a filter id and each value is a dict describing how to configure
2816 the corresponding Filter instance.
2817
2818 The configuring dict is searched for the key ``name`` (defaulting to the
2819 empty string) and this is used to construct a :class:`logging.Filter`
2820 instance.
2821
2822* `handlers` - the corresponding value will be a dict in which each
2823 key is a handler id and each value is a dict describing how to
2824 configure the corresponding Handler instance.
2825
2826 The configuring dict is searched for the following keys:
2827
2828 * ``class`` (mandatory). This is the fully qualified name of the
2829 handler class.
2830
2831 * ``level`` (optional). The level of the handler.
2832
2833 * ``formatter`` (optional). The id of the formatter for this
2834 handler.
2835
2836 * ``filters`` (optional). A list of ids of the filters for this
2837 handler.
2838
2839 All *other* keys are passed through as keyword arguments to the
2840 handler's constructor. For example, given the snippet::
2841
2842 handlers:
2843 console:
2844 class : logging.StreamHandler
2845 formatter: brief
2846 level : INFO
2847 filters: [allow_foo]
2848 stream : ext://sys.stdout
2849 file:
2850 class : logging.handlers.RotatingFileHandler
2851 formatter: precise
2852 filename: logconfig.log
2853 maxBytes: 1024
2854 backupCount: 3
2855
2856 the handler with id ``console`` is instantiated as a
2857 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
2858 stream. The handler with id ``file`` is instantiated as a
2859 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
2860 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
2861
2862* `loggers` - the corresponding value will be a dict in which each key
2863 is a logger name and each value is a dict describing how to
2864 configure the corresponding Logger instance.
2865
2866 The configuring dict is searched for the following keys:
2867
2868 * ``level`` (optional). The level of the logger.
2869
2870 * ``propagate`` (optional). The propagation setting of the logger.
2871
2872 * ``filters`` (optional). A list of ids of the filters for this
2873 logger.
2874
2875 * ``handlers`` (optional). A list of ids of the handlers for this
2876 logger.
2877
2878 The specified loggers will be configured according to the level,
2879 propagation, filters and handlers specified.
2880
2881* `root` - this will be the configuration for the root logger.
2882 Processing of the configuration will be as for any logger, except
2883 that the ``propagate`` setting will not be applicable.
2884
2885* `incremental` - whether the configuration is to be interpreted as
2886 incremental to the existing configuration. This value defaults to
2887 ``False``, which means that the specified configuration replaces the
2888 existing configuration with the same semantics as used by the
2889 existing :func:`fileConfig` API.
2890
2891 If the specified value is ``True``, the configuration is processed
2892 as described in the section on :ref:`logging-config-dict-incremental`.
2893
2894* `disable_existing_loggers` - whether any existing loggers are to be
2895 disabled. This setting mirrors the parameter of the same name in
2896 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
2897 This value is ignored if `incremental` is ``True``.
2898
2899.. _logging-config-dict-incremental:
2900
2901Incremental Configuration
2902"""""""""""""""""""""""""
2903
2904It is difficult to provide complete flexibility for incremental
2905configuration. For example, because objects such as filters
2906and formatters are anonymous, once a configuration is set up, it is
2907not possible to refer to such anonymous objects when augmenting a
2908configuration.
2909
2910Furthermore, there is not a compelling case for arbitrarily altering
2911the object graph of loggers, handlers, filters, formatters at
2912run-time, once a configuration is set up; the verbosity of loggers and
2913handlers can be controlled just by setting levels (and, in the case of
2914loggers, propagation flags). Changing the object graph arbitrarily in
2915a safe way is problematic in a multi-threaded environment; while not
2916impossible, the benefits are not worth the complexity it adds to the
2917implementation.
2918
2919Thus, when the ``incremental`` key of a configuration dict is present
2920and is ``True``, the system will completely ignore any ``formatters`` and
2921``filters`` entries, and process only the ``level``
2922settings in the ``handlers`` entries, and the ``level`` and
2923``propagate`` settings in the ``loggers`` and ``root`` entries.
2924
2925Using a value in the configuration dict lets configurations to be sent
2926over the wire as pickled dicts to a socket listener. Thus, the logging
2927verbosity of a long-running application can be altered over time with
2928no need to stop and restart the application.
2929
2930.. _logging-config-dict-connections:
2931
2932Object connections
2933""""""""""""""""""
2934
2935The schema describes a set of logging objects - loggers,
2936handlers, formatters, filters - which are connected to each other in
2937an object graph. Thus, the schema needs to represent connections
2938between the objects. For example, say that, once configured, a
2939particular logger has attached to it a particular handler. For the
2940purposes of this discussion, we can say that the logger represents the
2941source, and the handler the destination, of a connection between the
2942two. Of course in the configured objects this is represented by the
2943logger holding a reference to the handler. In the configuration dict,
2944this is done by giving each destination object an id which identifies
2945it unambiguously, and then using the id in the source object's
2946configuration to indicate that a connection exists between the source
2947and the destination object with that id.
2948
2949So, for example, consider the following YAML snippet::
2950
2951 formatters:
2952 brief:
2953 # configuration for formatter with id 'brief' goes here
2954 precise:
2955 # configuration for formatter with id 'precise' goes here
2956 handlers:
2957 h1: #This is an id
2958 # configuration of handler with id 'h1' goes here
2959 formatter: brief
2960 h2: #This is another id
2961 # configuration of handler with id 'h2' goes here
2962 formatter: precise
2963 loggers:
2964 foo.bar.baz:
2965 # other configuration for logger 'foo.bar.baz'
2966 handlers: [h1, h2]
2967
2968(Note: YAML used here because it's a little more readable than the
2969equivalent Python source form for the dictionary.)
2970
2971The ids for loggers are the logger names which would be used
2972programmatically to obtain a reference to those loggers, e.g.
2973``foo.bar.baz``. The ids for Formatters and Filters can be any string
2974value (such as ``brief``, ``precise`` above) and they are transient,
2975in that they are only meaningful for processing the configuration
2976dictionary and used to determine connections between objects, and are
2977not persisted anywhere when the configuration call is complete.
2978
2979The above snippet indicates that logger named ``foo.bar.baz`` should
2980have two handlers attached to it, which are described by the handler
2981ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
2982``brief``, and the formatter for ``h2`` is that described by id
2983``precise``.
2984
2985
2986.. _logging-config-dict-userdef:
2987
2988User-defined objects
2989""""""""""""""""""""
2990
2991The schema supports user-defined objects for handlers, filters and
2992formatters. (Loggers do not need to have different types for
2993different instances, so there is no support in this configuration
2994schema for user-defined logger classes.)
2995
2996Objects to be configured are described by dictionaries
2997which detail their configuration. In some places, the logging system
2998will be able to infer from the context how an object is to be
2999instantiated, but when a user-defined object is to be instantiated,
3000the system will not know how to do this. In order to provide complete
3001flexibility for user-defined object instantiation, the user needs
3002to provide a 'factory' - a callable which is called with a
3003configuration dictionary and which returns the instantiated object.
3004This is signalled by an absolute import path to the factory being
3005made available under the special key ``'()'``. Here's a concrete
3006example::
3007
3008 formatters:
3009 brief:
3010 format: '%(message)s'
3011 default:
3012 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3013 datefmt: '%Y-%m-%d %H:%M:%S'
3014 custom:
3015 (): my.package.customFormatterFactory
3016 bar: baz
3017 spam: 99.9
3018 answer: 42
3019
3020The above YAML snippet defines three formatters. The first, with id
3021``brief``, is a standard :class:`logging.Formatter` instance with the
3022specified format string. The second, with id ``default``, has a
3023longer format and also defines the time format explicitly, and will
3024result in a :class:`logging.Formatter` initialized with those two format
3025strings. Shown in Python source form, the ``brief`` and ``default``
3026formatters have configuration sub-dictionaries::
3027
3028 {
3029 'format' : '%(message)s'
3030 }
3031
3032and::
3033
3034 {
3035 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3036 'datefmt' : '%Y-%m-%d %H:%M:%S'
3037 }
3038
3039respectively, and as these dictionaries do not contain the special key
3040``'()'``, the instantiation is inferred from the context: as a result,
3041standard :class:`logging.Formatter` instances are created. The
3042configuration sub-dictionary for the third formatter, with id
3043``custom``, is::
3044
3045 {
3046 '()' : 'my.package.customFormatterFactory',
3047 'bar' : 'baz',
3048 'spam' : 99.9,
3049 'answer' : 42
3050 }
3051
3052and this contains the special key ``'()'``, which means that
3053user-defined instantiation is wanted. In this case, the specified
3054factory callable will be used. If it is an actual callable it will be
3055used directly - otherwise, if you specify a string (as in the example)
3056the actual callable will be located using normal import mechanisms.
3057The callable will be called with the **remaining** items in the
3058configuration sub-dictionary as keyword arguments. In the above
3059example, the formatter with id ``custom`` will be assumed to be
3060returned by the call::
3061
3062 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3063
3064The key ``'()'`` has been used as the special key because it is not a
3065valid keyword parameter name, and so will not clash with the names of
3066the keyword arguments used in the call. The ``'()'`` also serves as a
3067mnemonic that the corresponding value is a callable.
3068
3069
3070.. _logging-config-dict-externalobj:
3071
3072Access to external objects
3073""""""""""""""""""""""""""
3074
3075There are times where a configuration needs to refer to objects
3076external to the configuration, for example ``sys.stderr``. If the
3077configuration dict is constructed using Python code, this is
3078straightforward, but a problem arises when the configuration is
3079provided via a text file (e.g. JSON, YAML). In a text file, there is
3080no standard way to distinguish ``sys.stderr`` from the literal string
3081``'sys.stderr'``. To facilitate this distinction, the configuration
3082system looks for certain special prefixes in string values and
3083treat them specially. For example, if the literal string
3084``'ext://sys.stderr'`` is provided as a value in the configuration,
3085then the ``ext://`` will be stripped off and the remainder of the
3086value processed using normal import mechanisms.
3087
3088The handling of such prefixes is done in a way analogous to protocol
3089handling: there is a generic mechanism to look for prefixes which
3090match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3091whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3092in a prefix-dependent manner and the result of the processing replaces
3093the string value. If the prefix is not recognised, then the string
3094value will be left as-is.
3095
3096
3097.. _logging-config-dict-internalobj:
3098
3099Access to internal objects
3100""""""""""""""""""""""""""
3101
3102As well as external objects, there is sometimes also a need to refer
3103to objects in the configuration. This will be done implicitly by the
3104configuration system for things that it knows about. For example, the
3105string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3106automatically be converted to the value ``logging.DEBUG``, and the
3107``handlers``, ``filters`` and ``formatter`` entries will take an
3108object id and resolve to the appropriate destination object.
3109
3110However, a more generic mechanism is needed for user-defined
3111objects which are not known to the :mod:`logging` module. For
3112example, consider :class:`logging.handlers.MemoryHandler`, which takes
3113a ``target`` argument which is another handler to delegate to. Since
3114the system already knows about this class, then in the configuration,
3115the given ``target`` just needs to be the object id of the relevant
3116target handler, and the system will resolve to the handler from the
3117id. If, however, a user defines a ``my.package.MyHandler`` which has
3118an ``alternate`` handler, the configuration system would not know that
3119the ``alternate`` referred to a handler. To cater for this, a generic
3120resolution system allows the user to specify::
3121
3122 handlers:
3123 file:
3124 # configuration of file handler goes here
3125
3126 custom:
3127 (): my.package.MyHandler
3128 alternate: cfg://handlers.file
3129
3130The literal string ``'cfg://handlers.file'`` will be resolved in an
3131analogous way to strings with the ``ext://`` prefix, but looking
3132in the configuration itself rather than the import namespace. The
3133mechanism allows access by dot or by index, in a similar way to
3134that provided by ``str.format``. Thus, given the following snippet::
3135
3136 handlers:
3137 email:
3138 class: logging.handlers.SMTPHandler
3139 mailhost: localhost
3140 fromaddr: my_app@domain.tld
3141 toaddrs:
3142 - support_team@domain.tld
3143 - dev_team@domain.tld
3144 subject: Houston, we have a problem.
3145
3146in the configuration, the string ``'cfg://handlers'`` would resolve to
3147the dict with key ``handlers``, the string ``'cfg://handlers.email``
3148would resolve to the dict with key ``email`` in the ``handlers`` dict,
3149and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3150resolve to ``'dev_team.domain.tld'`` and the string
3151``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3152``'support_team@domain.tld'``. The ``subject`` value could be accessed
3153using either ``'cfg://handlers.email.subject'`` or, equivalently,
3154``'cfg://handlers.email[subject]'``. The latter form only needs to be
3155used if the key contains spaces or non-alphanumeric characters. If an
3156index value consists only of decimal digits, access will be attempted
3157using the corresponding integer value, falling back to the string
3158value if needed.
3159
3160Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3161resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3162If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3163the system will attempt to retrieve the value from
3164``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3165to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3166fails.
3167
Georg Brandl8ec7f652007-08-15 14:28:01 +00003168.. _logging-config-fileformat:
3169
3170Configuration file format
3171^^^^^^^^^^^^^^^^^^^^^^^^^
3172
Georg Brandl392c6fc2008-05-25 07:25:25 +00003173The configuration file format understood by :func:`fileConfig` is based on
Vinay Sajip51104862009-01-02 18:53:04 +00003174:mod:`ConfigParser` functionality. The file must contain sections called
3175``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3176entities of each type which are defined in the file. For each such entity,
3177there is a separate section which identifies how that entity is configured.
3178Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant
3179configuration details are held in a section ``[logger_log01]``. Similarly, a
3180handler called ``hand01`` in the ``[handlers]`` section will have its
3181configuration held in a section called ``[handler_hand01]``, while a formatter
3182called ``form01`` in the ``[formatters]`` section will have its configuration
3183specified in a section called ``[formatter_form01]``. The root logger
3184configuration must be specified in a section called ``[logger_root]``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003185
3186Examples of these sections in the file are given below. ::
3187
3188 [loggers]
3189 keys=root,log02,log03,log04,log05,log06,log07
3190
3191 [handlers]
3192 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3193
3194 [formatters]
3195 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3196
3197The root logger must specify a level and a list of handlers. An example of a
3198root logger section is given below. ::
3199
3200 [logger_root]
3201 level=NOTSET
3202 handlers=hand01
3203
3204The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3205``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3206logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3207package's namespace.
3208
3209The ``handlers`` entry is a comma-separated list of handler names, which must
3210appear in the ``[handlers]`` section. These names must appear in the
3211``[handlers]`` section and have corresponding sections in the configuration
3212file.
3213
3214For loggers other than the root logger, some additional information is required.
3215This is illustrated by the following example. ::
3216
3217 [logger_parser]
3218 level=DEBUG
3219 handlers=hand01
3220 propagate=1
3221 qualname=compiler.parser
3222
3223The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3224except that if a non-root logger's level is specified as ``NOTSET``, the system
3225consults loggers higher up the hierarchy to determine the effective level of the
3226logger. The ``propagate`` entry is set to 1 to indicate that messages must
3227propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3228indicate that messages are **not** propagated to handlers up the hierarchy. The
3229``qualname`` entry is the hierarchical channel name of the logger, that is to
3230say the name used by the application to get the logger.
3231
3232Sections which specify handler configuration are exemplified by the following.
3233::
3234
3235 [handler_hand01]
3236 class=StreamHandler
3237 level=NOTSET
3238 formatter=form01
3239 args=(sys.stdout,)
3240
3241The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3242in the ``logging`` package's namespace). The ``level`` is interpreted as for
3243loggers, and ``NOTSET`` is taken to mean "log everything".
3244
Vinay Sajip2a649f92008-07-18 09:00:35 +00003245.. versionchanged:: 2.6
3246 Added support for resolving the handler's class as a dotted module and class
3247 name.
3248
Georg Brandl8ec7f652007-08-15 14:28:01 +00003249The ``formatter`` entry indicates the key name of the formatter for this
3250handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3251If a name is specified, it must appear in the ``[formatters]`` section and have
3252a corresponding section in the configuration file.
3253
3254The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3255package's namespace, is the list of arguments to the constructor for the handler
3256class. Refer to the constructors for the relevant handlers, or to the examples
3257below, to see how typical entries are constructed. ::
3258
3259 [handler_hand02]
3260 class=FileHandler
3261 level=DEBUG
3262 formatter=form02
3263 args=('python.log', 'w')
3264
3265 [handler_hand03]
3266 class=handlers.SocketHandler
3267 level=INFO
3268 formatter=form03
3269 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3270
3271 [handler_hand04]
3272 class=handlers.DatagramHandler
3273 level=WARN
3274 formatter=form04
3275 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3276
3277 [handler_hand05]
3278 class=handlers.SysLogHandler
3279 level=ERROR
3280 formatter=form05
3281 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3282
3283 [handler_hand06]
3284 class=handlers.NTEventLogHandler
3285 level=CRITICAL
3286 formatter=form06
3287 args=('Python Application', '', 'Application')
3288
3289 [handler_hand07]
3290 class=handlers.SMTPHandler
3291 level=WARN
3292 formatter=form07
3293 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3294
3295 [handler_hand08]
3296 class=handlers.MemoryHandler
3297 level=NOTSET
3298 formatter=form08
3299 target=
3300 args=(10, ERROR)
3301
3302 [handler_hand09]
3303 class=handlers.HTTPHandler
3304 level=NOTSET
3305 formatter=form09
3306 args=('localhost:9022', '/log', 'GET')
3307
3308Sections which specify formatter configuration are typified by the following. ::
3309
3310 [formatter_form01]
3311 format=F1 %(asctime)s %(levelname)s %(message)s
3312 datefmt=
3313 class=logging.Formatter
3314
3315The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Georg Brandlb19be572007-12-29 10:57:00 +00003316the :func:`strftime`\ -compatible date/time format string. If empty, the
3317package substitutes ISO8601 format date/times, which is almost equivalent to
3318specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3319also specifies milliseconds, which are appended to the result of using the above
3320format string, with a comma separator. An example time in ISO8601 format is
3321``2003-01-23 00:29:50,411``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003322
3323The ``class`` entry is optional. It indicates the name of the formatter's class
3324(as a dotted module and class name.) This option is useful for instantiating a
3325:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3326exception tracebacks in an expanded or condensed format.
3327
Georg Brandlc37f2882007-12-04 17:46:27 +00003328
3329Configuration server example
3330^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3331
3332Here is an example of a module using the logging configuration server::
3333
3334 import logging
3335 import logging.config
3336 import time
3337 import os
3338
3339 # read initial config file
3340 logging.config.fileConfig("logging.conf")
3341
3342 # create and start listener on port 9999
3343 t = logging.config.listen(9999)
3344 t.start()
3345
3346 logger = logging.getLogger("simpleExample")
3347
3348 try:
3349 # loop through logging calls to see the difference
3350 # new configurations make, until Ctrl+C is pressed
3351 while True:
3352 logger.debug("debug message")
3353 logger.info("info message")
3354 logger.warn("warn message")
3355 logger.error("error message")
3356 logger.critical("critical message")
3357 time.sleep(5)
3358 except KeyboardInterrupt:
3359 # cleanup
3360 logging.config.stopListening()
3361 t.join()
3362
3363And here is a script that takes a filename and sends that file to the server,
3364properly preceded with the binary-encoded length, as the new logging
3365configuration::
3366
3367 #!/usr/bin/env python
Benjamin Petersona7b55a32009-02-20 03:31:23 +00003368 import socket, sys, struct
Georg Brandlc37f2882007-12-04 17:46:27 +00003369
3370 data_to_send = open(sys.argv[1], "r").read()
3371
3372 HOST = 'localhost'
3373 PORT = 9999
3374 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3375 print "connecting..."
3376 s.connect((HOST, PORT))
3377 print "sending config..."
3378 s.send(struct.pack(">L", len(data_to_send)))
3379 s.send(data_to_send)
3380 s.close()
3381 print "complete"
3382
3383
3384More examples
3385-------------
3386
3387Multiple handlers and formatters
3388^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3389
3390Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3391or maximum quota for the number of handlers you may add. Sometimes it will be
3392beneficial for an application to log all messages of all severities to a text
3393file while simultaneously logging errors or above to the console. To set this
3394up, simply configure the appropriate handlers. The logging calls in the
3395application code will remain unchanged. Here is a slight modification to the
3396previous simple module-based configuration example::
3397
3398 import logging
3399
3400 logger = logging.getLogger("simple_example")
3401 logger.setLevel(logging.DEBUG)
3402 # create file handler which logs even debug messages
3403 fh = logging.FileHandler("spam.log")
3404 fh.setLevel(logging.DEBUG)
3405 # create console handler with a higher log level
3406 ch = logging.StreamHandler()
3407 ch.setLevel(logging.ERROR)
3408 # create formatter and add it to the handlers
3409 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3410 ch.setFormatter(formatter)
3411 fh.setFormatter(formatter)
3412 # add the handlers to logger
3413 logger.addHandler(ch)
3414 logger.addHandler(fh)
3415
3416 # "application" code
3417 logger.debug("debug message")
3418 logger.info("info message")
3419 logger.warn("warn message")
3420 logger.error("error message")
3421 logger.critical("critical message")
3422
3423Notice that the "application" code does not care about multiple handlers. All
3424that changed was the addition and configuration of a new handler named *fh*.
3425
3426The ability to create new handlers with higher- or lower-severity filters can be
3427very helpful when writing and testing an application. Instead of using many
3428``print`` statements for debugging, use ``logger.debug``: Unlike the print
3429statements, which you will have to delete or comment out later, the logger.debug
3430statements can remain intact in the source code and remain dormant until you
3431need them again. At that time, the only change that needs to happen is to
3432modify the severity level of the logger and/or handler to debug.
3433
3434
3435Using logging in multiple modules
3436^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3437
3438It was mentioned above that multiple calls to
3439``logging.getLogger('someLogger')`` return a reference to the same logger
3440object. This is true not only within the same module, but also across modules
3441as long as it is in the same Python interpreter process. It is true for
3442references to the same object; additionally, application code can define and
3443configure a parent logger in one module and create (but not configure) a child
3444logger in a separate module, and all logger calls to the child will pass up to
3445the parent. Here is a main module::
3446
3447 import logging
3448 import auxiliary_module
3449
3450 # create logger with "spam_application"
3451 logger = logging.getLogger("spam_application")
3452 logger.setLevel(logging.DEBUG)
3453 # create file handler which logs even debug messages
3454 fh = logging.FileHandler("spam.log")
3455 fh.setLevel(logging.DEBUG)
3456 # create console handler with a higher log level
3457 ch = logging.StreamHandler()
3458 ch.setLevel(logging.ERROR)
3459 # create formatter and add it to the handlers
3460 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3461 fh.setFormatter(formatter)
3462 ch.setFormatter(formatter)
3463 # add the handlers to the logger
3464 logger.addHandler(fh)
3465 logger.addHandler(ch)
3466
3467 logger.info("creating an instance of auxiliary_module.Auxiliary")
3468 a = auxiliary_module.Auxiliary()
3469 logger.info("created an instance of auxiliary_module.Auxiliary")
3470 logger.info("calling auxiliary_module.Auxiliary.do_something")
3471 a.do_something()
3472 logger.info("finished auxiliary_module.Auxiliary.do_something")
3473 logger.info("calling auxiliary_module.some_function()")
3474 auxiliary_module.some_function()
3475 logger.info("done with auxiliary_module.some_function()")
3476
3477Here is the auxiliary module::
3478
3479 import logging
3480
3481 # create logger
3482 module_logger = logging.getLogger("spam_application.auxiliary")
3483
3484 class Auxiliary:
3485 def __init__(self):
3486 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3487 self.logger.info("creating an instance of Auxiliary")
3488 def do_something(self):
3489 self.logger.info("doing something")
3490 a = 1 + 1
3491 self.logger.info("done doing something")
3492
3493 def some_function():
3494 module_logger.info("received a call to \"some_function\"")
3495
3496The output looks like this::
3497
Vinay Sajipe28fa292008-01-07 15:30:36 +00003498 2005-03-23 23:47:11,663 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003499 creating an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003500 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003501 creating an instance of Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003502 2005-03-23 23:47:11,665 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003503 created an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003504 2005-03-23 23:47:11,668 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003505 calling auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003506 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003507 doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003508 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003509 done doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003510 2005-03-23 23:47:11,670 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003511 finished auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003512 2005-03-23 23:47:11,671 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003513 calling auxiliary_module.some_function()
Vinay Sajipe28fa292008-01-07 15:30:36 +00003514 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003515 received a call to "some_function"
Vinay Sajipe28fa292008-01-07 15:30:36 +00003516 2005-03-23 23:47:11,673 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003517 done with auxiliary_module.some_function()
3518