blob: 838f91afcd314dc14fea6ffe9b285b7b8b63c7f5 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
17Logging is performed by calling methods on instances of the :class:`Logger`
18class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +000019conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +000020separators. For example, a logger named "scan" is the parent of loggers
21"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
22and indicate the area of an application in which a logged message originates.
23
24Logged messages also have levels of importance associated with them. The default
25levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
26:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
27importance of a logged message by calling an appropriate method of
28:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
29:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
30constrained to use these levels: you can specify your own and use a more general
31:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
32
Christian Heimes8b0facf2007-12-04 19:30:01 +000033
34Logging tutorial
35----------------
36
37The key benefit of having the logging API provided by a standard library module
38is that all Python modules can participate in logging, so your application log
39can include messages from third-party modules.
40
41It is, of course, possible to log messages with different verbosity levels or to
42different destinations. Support for writing log messages to files, HTTP
43GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Christian Heimesc3f30c42008-02-22 16:37:40 +000044mechanisms are all supported by the standard module. You can also create your
Christian Heimes8b0facf2007-12-04 19:30:01 +000045own log destination class if you have special requirements not met by any of the
46built-in classes.
47
48Simple examples
49^^^^^^^^^^^^^^^
50
51.. sectionauthor:: Doug Hellmann
52.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
53
54Most applications are probably going to want to log to a file, so let's start
55with that case. Using the :func:`basicConfig` function, we can set up the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056default handler so that debug messages are written to a file (in the example,
57we assume that you have the appropriate permissions to create a file called
58*example.log* in the current directory)::
Christian Heimes8b0facf2007-12-04 19:30:01 +000059
60 import logging
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000061 LOG_FILENAME = 'example.log'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Christian Heimes8b0facf2007-12-04 19:30:01 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smith5c01a8d2009-06-04 18:20:51 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Christian Heimes8b0facf2007-12-04 19:30:01 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000080 LOG_FILENAME = 'logging_rotatingfile_example.out'
Christian Heimes8b0facf2007-12-04 19:30:01 +000081
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
Georg Brandlf6945182008-02-01 11:56:49 +0000100 print(filename)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000105 logging_rotatingfile_example.out
106 logging_rotatingfile_example.out.1
107 logging_rotatingfile_example.out.2
108 logging_rotatingfile_example.out.3
109 logging_rotatingfile_example.out.4
110 logging_rotatingfile_example.out.5
Christian Heimes8b0facf2007-12-04 19:30:01 +0000111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112The most current file is always :file:`logging_rotatingfile_example.out`,
Christian Heimes8b0facf2007-12-04 19:30:01 +0000113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smith5c01a8d2009-06-04 18:20:51 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipb6d065f2009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Christian Heimesdcca98d2008-02-25 13:19:43 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000249name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000270requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
294defines the interface that all handlers should have and establishes some
295default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000303instantiate formatter classes, although you could likely subclass the formatter
304if your application needs special behavior. The constructor takes two optional
305arguments: a message format string and a date format string. If there is no
306message format string, the default is to use the raw message. If there is no
307date format string, the default date format is::
308
309 %Y-%m-%d %H:%M:%S
310
311with the milliseconds tacked on at the end.
312
313The message format string uses ``%(<dictionary key>)s`` styled string
314substitution; the possible keys are documented in :ref:`formatter-objects`.
315
316The following message format string will log the time in a human-readable
317format, the severity of the message, and the contents of the message, in that
318order::
319
320 "%(asctime)s - %(levelname)s - %(message)s"
321
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000322Formatters use a user-configurable function to convert the creation time of a
323record to a tuple. By default, :func:`time.localtime` is used; to change this
324for a particular formatter instance, set the ``converter`` attribute of the
325instance to a function with the same signature as :func:`time.localtime` or
326:func:`time.gmtime`. To change it for all formatters, for example if you want
327all logging times to be shown in GMT, set the ``converter`` attribute in the
328Formatter class (to ``time.gmtime`` for GMT display).
329
Christian Heimes8b0facf2007-12-04 19:30:01 +0000330
331Configuring Logging
332^^^^^^^^^^^^^^^^^^^
333
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000334Programmers can configure logging in three ways:
335
3361. Creating loggers, handlers, and formatters explicitly using Python
337 code that calls the configuration methods listed above.
3382. Creating a logging config file and reading it using the :func:`fileConfig`
339 function.
3403. Creating a dictionary of configuration information and passing it
341 to the :func:`dictConfig` function.
342
343The following example configures a very simple logger, a console
344handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000345
346 import logging
347
348 # create logger
349 logger = logging.getLogger("simple_example")
350 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000351
Christian Heimes8b0facf2007-12-04 19:30:01 +0000352 # create console handler and set level to debug
353 ch = logging.StreamHandler()
354 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000355
Christian Heimes8b0facf2007-12-04 19:30:01 +0000356 # create formatter
357 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000358
Christian Heimes8b0facf2007-12-04 19:30:01 +0000359 # add formatter to ch
360 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000361
Christian Heimes8b0facf2007-12-04 19:30:01 +0000362 # add ch to logger
363 logger.addHandler(ch)
364
365 # "application" code
366 logger.debug("debug message")
367 logger.info("info message")
368 logger.warn("warn message")
369 logger.error("error message")
370 logger.critical("critical message")
371
372Running this module from the command line produces the following output::
373
374 $ python simple_logging_module.py
375 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
376 2005-03-19 15:10:26,620 - simple_example - INFO - info message
377 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
378 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
379 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
380
381The following Python module creates a logger, handler, and formatter nearly
382identical to those in the example listed above, with the only difference being
383the names of the objects::
384
385 import logging
386 import logging.config
387
388 logging.config.fileConfig("logging.conf")
389
390 # create logger
391 logger = logging.getLogger("simpleExample")
392
393 # "application" code
394 logger.debug("debug message")
395 logger.info("info message")
396 logger.warn("warn message")
397 logger.error("error message")
398 logger.critical("critical message")
399
400Here is the logging.conf file::
401
402 [loggers]
403 keys=root,simpleExample
404
405 [handlers]
406 keys=consoleHandler
407
408 [formatters]
409 keys=simpleFormatter
410
411 [logger_root]
412 level=DEBUG
413 handlers=consoleHandler
414
415 [logger_simpleExample]
416 level=DEBUG
417 handlers=consoleHandler
418 qualname=simpleExample
419 propagate=0
420
421 [handler_consoleHandler]
422 class=StreamHandler
423 level=DEBUG
424 formatter=simpleFormatter
425 args=(sys.stdout,)
426
427 [formatter_simpleFormatter]
428 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
429 datefmt=
430
431The output is nearly identical to that of the non-config-file-based example::
432
433 $ python simple_logging_config.py
434 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
435 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
436 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
437 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
438 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
439
440You can see that the config file approach has a few advantages over the Python
441code approach, mainly separation of configuration and code and the ability of
442noncoders to easily modify the logging properties.
443
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000444Note that the class names referenced in config files need to be either relative
445to the logging module, or absolute values which can be resolved using normal
446import mechanisms. Thus, you could use either `handlers.WatchedFileHandler`
447(relative to the logging module) or `mypackage.mymodule.MyHandler` (for a
448class defined in package `mypackage` and module `mymodule`, where `mypackage`
449is available on the Python import path).
450
Benjamin Peterson56894b52010-06-28 00:16:12 +0000451In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000452dictionaries to hold configuration information. This provides a superset of the
453functionality of the config-file-based approach outlined above, and is the
454recommended configuration method for new applications and deployments. Because
455a Python dictionary is used to hold configuration information, and since you
456can populate that dictionary using different means, you have more options for
457configuration. For example, you can use a configuration file in JSON format,
458or, if you have access to YAML processing functionality, a file in YAML
459format, to populate the configuration dictionary. Or, of course, you can
460construct the dictionary in Python code, receive it in pickled form over a
461socket, or use whatever approach makes sense for your application.
462
463Here's an example of the same configuration as above, in YAML format for
464the new dictionary-based approach::
465
466 version: 1
467 formatters:
468 simple:
469 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
470 handlers:
471 console:
472 class: logging.StreamHandler
473 level: DEBUG
474 formatter: simple
475 stream: ext://sys.stdout
476 loggers:
477 simpleExample:
478 level: DEBUG
479 handlers: [console]
480 propagate: no
481 root:
482 level: DEBUG
483 handlers: [console]
484
485For more information about logging using a dictionary, see
486:ref:`logging-config-api`.
487
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000488.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000489
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000490Configuring Logging for a Library
491^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
492
493When developing a library which uses logging, some consideration needs to be
494given to its configuration. If the using application does not use logging, and
495library code makes logging calls, then a one-off message "No handlers could be
496found for logger X.Y.Z" is printed to the console. This message is intended
497to catch mistakes in logging configuration, but will confuse an application
498developer who is not aware of logging by the library.
499
500In addition to documenting how a library uses logging, a good way to configure
501library logging so that it does not cause a spurious message is to add a
502handler which does nothing. This avoids the message being printed, since a
503handler will be found: it just doesn't produce any output. If the library user
504configures logging for application use, presumably that configuration will add
505some handlers, and if levels are suitably configured then logging calls made
506in library code will send output to those handlers, as normal.
507
508A do-nothing handler can be simply defined as follows::
509
510 import logging
511
512 class NullHandler(logging.Handler):
513 def emit(self, record):
514 pass
515
516An instance of this handler should be added to the top-level logger of the
517logging namespace used by the library. If all logging by a library *foo* is
518done using loggers with names matching "foo.x.y", then the code::
519
520 import logging
521
522 h = NullHandler()
523 logging.getLogger("foo").addHandler(h)
524
525should have the desired effect. If an organisation produces a number of
526libraries, then the logger name specified can be "orgname.foo" rather than
527just "foo".
528
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000529**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
530than* :class:`NullHandler` *to your library's loggers*. This is because the
531configuration of handlers is the prerogative of the application developer who
532uses your library. The application developer knows their target audience and
533what handlers are most appropriate for their application: if you add handlers
534"under the hood", you might well interfere with their ability to carry out
535unit tests and deliver logs which suit their requirements.
536
Georg Brandlf9734072008-12-07 15:30:06 +0000537.. versionadded:: 3.1
Vinay Sajip4039aff2010-09-11 10:25:28 +0000538
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000539The :class:`NullHandler` class was not present in previous versions, but is
540now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000541
542
Christian Heimes8b0facf2007-12-04 19:30:01 +0000543
544Logging Levels
545--------------
546
Georg Brandl116aa622007-08-15 14:28:22 +0000547The numeric values of logging levels are given in the following table. These are
548primarily of interest if you want to define your own levels, and need them to
549have specific values relative to the predefined levels. If you define a level
550with the same numeric value, it overwrites the predefined value; the predefined
551name is lost.
552
553+--------------+---------------+
554| Level | Numeric value |
555+==============+===============+
556| ``CRITICAL`` | 50 |
557+--------------+---------------+
558| ``ERROR`` | 40 |
559+--------------+---------------+
560| ``WARNING`` | 30 |
561+--------------+---------------+
562| ``INFO`` | 20 |
563+--------------+---------------+
564| ``DEBUG`` | 10 |
565+--------------+---------------+
566| ``NOTSET`` | 0 |
567+--------------+---------------+
568
569Levels can also be associated with loggers, being set either by the developer or
570through loading a saved logging configuration. When a logging method is called
571on a logger, the logger compares its own level with the level associated with
572the method call. If the logger's level is higher than the method call's, no
573logging message is actually generated. This is the basic mechanism controlling
574the verbosity of logging output.
575
576Logging messages are encoded as instances of the :class:`LogRecord` class. When
577a logger decides to actually log an event, a :class:`LogRecord` instance is
578created from the logging message.
579
580Logging messages are subjected to a dispatch mechanism through the use of
581:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
582class. Handlers are responsible for ensuring that a logged message (in the form
583of a :class:`LogRecord`) ends up in a particular location (or set of locations)
584which is useful for the target audience for that message (such as end users,
585support desk staff, system administrators, developers). Handlers are passed
586:class:`LogRecord` instances intended for particular destinations. Each logger
587can have zero, one or more handlers associated with it (via the
588:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
589directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000590of the logger* are called to dispatch the message (unless the *propagate* flag
591for a logger is set to a false value, at which point the passing to ancestor
592handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000593
594Just as for loggers, handlers can have levels associated with them. A handler's
595level acts as a filter in the same way as a logger's level does. If a handler
596decides to actually dispatch an event, the :meth:`emit` method is used to send
597the message to its destination. Most user-defined subclasses of :class:`Handler`
598will need to override this :meth:`emit`.
599
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000600.. _custom-levels:
601
602Custom Levels
603^^^^^^^^^^^^^
604
605Defining your own levels is possible, but should not be necessary, as the
606existing levels have been chosen on the basis of practical experience.
607However, if you are convinced that you need custom levels, great care should
608be exercised when doing this, and it is possibly *a very bad idea to define
609custom levels if you are developing a library*. That's because if multiple
610library authors all define their own custom levels, there is a chance that
611the logging output from such multiple libraries used together will be
612difficult for the using developer to control and/or interpret, because a
613given numeric value might mean different things for different libraries.
614
615
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000616Useful Handlers
617---------------
618
Georg Brandl116aa622007-08-15 14:28:22 +0000619In addition to the base :class:`Handler` class, many useful subclasses are
620provided:
621
Vinay Sajip121a1c42010-09-08 10:46:15 +0000622#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000623 objects).
624
Vinay Sajip121a1c42010-09-08 10:46:15 +0000625#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000626
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000627.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000628
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000629#. :class:`BaseRotatingHandler` is the base class for handlers that
630 rotate log files at a certain point. It is not meant to be instantiated
631 directly. Instead, use :class:`RotatingFileHandler` or
632 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000633
Vinay Sajip121a1c42010-09-08 10:46:15 +0000634#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000635 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Vinay Sajip121a1c42010-09-08 10:46:15 +0000637#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000638 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
Vinay Sajip121a1c42010-09-08 10:46:15 +0000640#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000641 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000642
Vinay Sajip121a1c42010-09-08 10:46:15 +0000643#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000644 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Vinay Sajip121a1c42010-09-08 10:46:15 +0000646#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000647 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Vinay Sajip121a1c42010-09-08 10:46:15 +0000649#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000650 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Vinay Sajip121a1c42010-09-08 10:46:15 +0000652#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000653 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000654
Vinay Sajip121a1c42010-09-08 10:46:15 +0000655#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000656 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
Vinay Sajip121a1c42010-09-08 10:46:15 +0000658#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000659 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000661#. :class:`WatchedFileHandler` instances watch the file they are
662 logging to. If the file changes, it is closed and reopened using the file
663 name. This handler is only useful on Unix-like systems; Windows does not
664 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000665
Vinay Sajip121a1c42010-09-08 10:46:15 +0000666#. :class:`QueueHandler` instances send messages to a queue, such as
667 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
668
Vinay Sajip30bf1222009-01-10 19:23:34 +0000669.. currentmodule:: logging
670
Georg Brandlf9734072008-12-07 15:30:06 +0000671#. :class:`NullHandler` instances do nothing with error messages. They are used
672 by library developers who want to use logging, but want to avoid the "No
673 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000674 the library user has not configured logging. See :ref:`library-config` for
675 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000676
677.. versionadded:: 3.1
678
679The :class:`NullHandler` class was not present in previous versions.
680
Vinay Sajip121a1c42010-09-08 10:46:15 +0000681.. versionadded:: 3.2
682
683The :class:`QueueHandler` class was not present in previous versions.
684
Vinay Sajipa17775f2008-12-30 07:32:59 +0000685The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
686classes are defined in the core logging package. The other handlers are
687defined in a sub- module, :mod:`logging.handlers`. (There is also another
688sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690Logged messages are formatted for presentation through instances of the
691:class:`Formatter` class. They are initialized with a format string suitable for
692use with the % operator and a dictionary.
693
694For formatting multiple messages in a batch, instances of
695:class:`BufferingFormatter` can be used. In addition to the format string (which
696is applied to each message in the batch), there is provision for header and
697trailer format strings.
698
699When filtering based on logger level and/or handler level is not enough,
700instances of :class:`Filter` can be added to both :class:`Logger` and
701:class:`Handler` instances (through their :meth:`addFilter` method). Before
702deciding to process a message further, both loggers and handlers consult all
703their filters for permission. If any filter returns a false value, the message
704is not processed further.
705
706The basic :class:`Filter` functionality allows filtering by specific logger
707name. If this feature is used, messages sent to the named logger and its
708children are allowed through the filter, and all others dropped.
709
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000710Module-Level Functions
711----------------------
712
Georg Brandl116aa622007-08-15 14:28:22 +0000713In addition to the classes described above, there are a number of module- level
714functions.
715
716
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000717.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000719 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000720 logger which is the root logger of the hierarchy. If specified, the name is
721 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
722 Choice of these names is entirely up to the developer who is using logging.
723
724 All calls to this function with a given name return the same logger instance.
725 This means that logger instances never need to be passed between different parts
726 of an application.
727
728
729.. function:: getLoggerClass()
730
731 Return either the standard :class:`Logger` class, or the last class passed to
732 :func:`setLoggerClass`. This function may be called from within a new class
733 definition, to ensure that installing a customised :class:`Logger` class will
734 not undo customisations already applied by other code. For example::
735
736 class MyLogger(logging.getLoggerClass()):
737 # ... override behaviour here
738
739
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000740.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000741
742 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
743 message format string, and the *args* are the arguments which are merged into
744 *msg* using the string formatting operator. (Note that this means that you can
745 use keywords in the format string, together with a single dictionary argument.)
746
747 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
748 which, if it does not evaluate as false, causes exception information to be
749 added to the logging message. If an exception tuple (in the format returned by
750 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
751 is called to get the exception information.
752
753 The other optional keyword argument is *extra* which can be used to pass a
754 dictionary which is used to populate the __dict__ of the LogRecord created for
755 the logging event with user-defined attributes. These custom attributes can then
756 be used as you like. For example, they could be incorporated into logged
757 messages. For example::
758
759 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
760 logging.basicConfig(format=FORMAT)
761 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
762 logging.warning("Protocol problem: %s", "connection reset", extra=d)
763
Vinay Sajip4039aff2010-09-11 10:25:28 +0000764 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000765
766 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
767
768 The keys in the dictionary passed in *extra* should not clash with the keys used
769 by the logging system. (See the :class:`Formatter` documentation for more
770 information on which keys are used by the logging system.)
771
772 If you choose to use these attributes in logged messages, you need to exercise
773 some care. In the above example, for instance, the :class:`Formatter` has been
774 set up with a format string which expects 'clientip' and 'user' in the attribute
775 dictionary of the LogRecord. If these are missing, the message will not be
776 logged because a string formatting exception will occur. So in this case, you
777 always need to pass the *extra* dictionary with these keys.
778
779 While this might be annoying, this feature is intended for use in specialized
780 circumstances, such as multi-threaded servers where the same code executes in
781 many contexts, and interesting conditions which arise are dependent on this
782 context (such as remote client IP address and authenticated user name, in the
783 above example). In such circumstances, it is likely that specialized
784 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
785
Georg Brandl116aa622007-08-15 14:28:22 +0000786
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000787.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789 Logs a message with level :const:`INFO` on the root logger. The arguments are
790 interpreted as for :func:`debug`.
791
792
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000793.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795 Logs a message with level :const:`WARNING` on the root logger. The arguments are
796 interpreted as for :func:`debug`.
797
798
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000799.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801 Logs a message with level :const:`ERROR` on the root logger. The arguments are
802 interpreted as for :func:`debug`.
803
804
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000805.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
808 are interpreted as for :func:`debug`.
809
810
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000811.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000812
813 Logs a message with level :const:`ERROR` on the root logger. The arguments are
814 interpreted as for :func:`debug`. Exception info is added to the logging
815 message. This function should only be called from an exception handler.
816
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000817.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000818
819 Logs a message with level *level* on the root logger. The other arguments are
820 interpreted as for :func:`debug`.
821
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000822 PLEASE NOTE: The above module-level functions which delegate to the root
823 logger should *not* be used in threads, in versions of Python earlier than
824 2.7.1 and 3.2, unless at least one handler has been added to the root
825 logger *before* the threads are started. These convenience functions call
826 :func:`basicConfig` to ensure that at least one handler is available; in
827 earlier versions of Python, this can (under rare circumstances) lead to
828 handlers being added multiple times to the root logger, which can in turn
829 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831.. function:: disable(lvl)
832
833 Provides an overriding level *lvl* for all loggers which takes precedence over
834 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000835 output down across the whole application, this function can be useful. Its
836 effect is to disable all logging calls of severity *lvl* and below, so that
837 if you call it with a value of INFO, then all INFO and DEBUG events would be
838 discarded, whereas those of severity WARNING and above would be processed
839 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841
842.. function:: addLevelName(lvl, levelName)
843
844 Associates level *lvl* with text *levelName* in an internal dictionary, which is
845 used to map numeric levels to a textual representation, for example when a
846 :class:`Formatter` formats a message. This function can also be used to define
847 your own levels. The only constraints are that all levels used must be
848 registered using this function, levels should be positive integers and they
849 should increase in increasing order of severity.
850
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000851 NOTE: If you are thinking of defining your own levels, please see the section
852 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +0000853
854.. function:: getLevelName(lvl)
855
856 Returns the textual representation of logging level *lvl*. If the level is one
857 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
858 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
859 have associated levels with names using :func:`addLevelName` then the name you
860 have associated with *lvl* is returned. If a numeric value corresponding to one
861 of the defined levels is passed in, the corresponding string representation is
862 returned. Otherwise, the string "Level %s" % lvl is returned.
863
864
865.. function:: makeLogRecord(attrdict)
866
867 Creates and returns a new :class:`LogRecord` instance whose attributes are
868 defined by *attrdict*. This function is useful for taking a pickled
869 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
870 it as a :class:`LogRecord` instance at the receiving end.
871
872
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000873.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000874
875 Does basic configuration for the logging system by creating a
876 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000877 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000878 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
879 if no handlers are defined for the root logger.
880
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000881 This function does nothing if the root logger already has handlers
882 configured for it.
883
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000884 PLEASE NOTE: This function should be called from the main thread
885 before other threads are started. In versions of Python prior to
886 2.7.1 and 3.2, if this function is called from multiple threads,
887 it is possible (in rare circumstances) that a handler will be added
888 to the root logger more than once, leading to unexpected results
889 such as messages being duplicated in the log.
890
Georg Brandl116aa622007-08-15 14:28:22 +0000891 The following keyword arguments are supported.
892
893 +--------------+---------------------------------------------+
894 | Format | Description |
895 +==============+=============================================+
896 | ``filename`` | Specifies that a FileHandler be created, |
897 | | using the specified filename, rather than a |
898 | | StreamHandler. |
899 +--------------+---------------------------------------------+
900 | ``filemode`` | Specifies the mode to open the file, if |
901 | | filename is specified (if filemode is |
902 | | unspecified, it defaults to 'a'). |
903 +--------------+---------------------------------------------+
904 | ``format`` | Use the specified format string for the |
905 | | handler. |
906 +--------------+---------------------------------------------+
907 | ``datefmt`` | Use the specified date/time format. |
908 +--------------+---------------------------------------------+
909 | ``level`` | Set the root logger level to the specified |
910 | | level. |
911 +--------------+---------------------------------------------+
912 | ``stream`` | Use the specified stream to initialize the |
913 | | StreamHandler. Note that this argument is |
914 | | incompatible with 'filename' - if both are |
915 | | present, 'stream' is ignored. |
916 +--------------+---------------------------------------------+
917
Georg Brandl116aa622007-08-15 14:28:22 +0000918.. function:: shutdown()
919
920 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000921 closing all handlers. This should be called at application exit and no
922 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924
925.. function:: setLoggerClass(klass)
926
927 Tells the logging system to use the class *klass* when instantiating a logger.
928 The class should define :meth:`__init__` such that only a name argument is
929 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
930 function is typically called before any loggers are instantiated by applications
931 which need to use custom logger behavior.
932
933
934.. seealso::
935
936 :pep:`282` - A Logging System
937 The proposal which described this feature for inclusion in the Python standard
938 library.
939
Christian Heimes255f53b2007-12-08 15:33:56 +0000940 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000941 This is the original source for the :mod:`logging` package. The version of the
942 package available from this site is suitable for use with Python 1.5.2, 2.1.x
943 and 2.2.x, which do not include the :mod:`logging` package in the standard
944 library.
945
Vinay Sajip4039aff2010-09-11 10:25:28 +0000946.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948Logger Objects
949--------------
950
951Loggers have the following attributes and methods. Note that Loggers are never
952instantiated directly, but always through the module-level function
953``logging.getLogger(name)``.
954
Vinay Sajip0258ce82010-09-22 20:34:53 +0000955.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957.. attribute:: Logger.propagate
958
959 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000960 its child loggers to the handlers of higher level (ancestor) loggers. The
961 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000962
963
964.. method:: Logger.setLevel(lvl)
965
966 Sets the threshold for this logger to *lvl*. Logging messages which are less
967 severe than *lvl* will be ignored. When a logger is created, the level is set to
968 :const:`NOTSET` (which causes all messages to be processed when the logger is
969 the root logger, or delegation to the parent when the logger is a non-root
970 logger). Note that the root logger is created with level :const:`WARNING`.
971
972 The term "delegation to the parent" means that if a logger has a level of
973 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
974 a level other than NOTSET is found, or the root is reached.
975
976 If an ancestor is found with a level other than NOTSET, then that ancestor's
977 level is treated as the effective level of the logger where the ancestor search
978 began, and is used to determine how a logging event is handled.
979
980 If the root is reached, and it has a level of NOTSET, then all messages will be
981 processed. Otherwise, the root's level will be used as the effective level.
982
983
984.. method:: Logger.isEnabledFor(lvl)
985
986 Indicates if a message of severity *lvl* would be processed by this logger.
987 This method checks first the module-level level set by
988 ``logging.disable(lvl)`` and then the logger's effective level as determined
989 by :meth:`getEffectiveLevel`.
990
991
992.. method:: Logger.getEffectiveLevel()
993
994 Indicates the effective level for this logger. If a value other than
995 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
996 the hierarchy is traversed towards the root until a value other than
997 :const:`NOTSET` is found, and that value is returned.
998
999
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001000.. method:: Logger.getChild(suffix)
1001
1002 Returns a logger which is a descendant to this logger, as determined by the suffix.
1003 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1004 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1005 convenience method, useful when the parent logger is named using e.g. ``__name__``
1006 rather than a literal string.
1007
1008 .. versionadded:: 3.2
1009
Georg Brandl67b21b72010-08-17 15:07:14 +00001010
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001011.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1014 message format string, and the *args* are the arguments which are merged into
1015 *msg* using the string formatting operator. (Note that this means that you can
1016 use keywords in the format string, together with a single dictionary argument.)
1017
1018 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
1019 which, if it does not evaluate as false, causes exception information to be
1020 added to the logging message. If an exception tuple (in the format returned by
1021 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1022 is called to get the exception information.
1023
1024 The other optional keyword argument is *extra* which can be used to pass a
1025 dictionary which is used to populate the __dict__ of the LogRecord created for
1026 the logging event with user-defined attributes. These custom attributes can then
1027 be used as you like. For example, they could be incorporated into logged
1028 messages. For example::
1029
1030 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1031 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001032 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001033 logger = logging.getLogger("tcpserver")
1034 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1035
1036 would print something like ::
1037
1038 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1039
1040 The keys in the dictionary passed in *extra* should not clash with the keys used
1041 by the logging system. (See the :class:`Formatter` documentation for more
1042 information on which keys are used by the logging system.)
1043
1044 If you choose to use these attributes in logged messages, you need to exercise
1045 some care. In the above example, for instance, the :class:`Formatter` has been
1046 set up with a format string which expects 'clientip' and 'user' in the attribute
1047 dictionary of the LogRecord. If these are missing, the message will not be
1048 logged because a string formatting exception will occur. So in this case, you
1049 always need to pass the *extra* dictionary with these keys.
1050
1051 While this might be annoying, this feature is intended for use in specialized
1052 circumstances, such as multi-threaded servers where the same code executes in
1053 many contexts, and interesting conditions which arise are dependent on this
1054 context (such as remote client IP address and authenticated user name, in the
1055 above example). In such circumstances, it is likely that specialized
1056 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1057
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001059.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061 Logs a message with level :const:`INFO` on this logger. The arguments are
1062 interpreted as for :meth:`debug`.
1063
1064
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001065.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001066
1067 Logs a message with level :const:`WARNING` on this logger. The arguments are
1068 interpreted as for :meth:`debug`.
1069
1070
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001071.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001072
1073 Logs a message with level :const:`ERROR` on this logger. The arguments are
1074 interpreted as for :meth:`debug`.
1075
1076
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001077.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1080 interpreted as for :meth:`debug`.
1081
1082
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001083.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085 Logs a message with integer level *lvl* on this logger. The other arguments are
1086 interpreted as for :meth:`debug`.
1087
1088
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001089.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001090
1091 Logs a message with level :const:`ERROR` on this logger. The arguments are
1092 interpreted as for :meth:`debug`. Exception info is added to the logging
1093 message. This method should only be called from an exception handler.
1094
1095
1096.. method:: Logger.addFilter(filt)
1097
1098 Adds the specified filter *filt* to this logger.
1099
1100
1101.. method:: Logger.removeFilter(filt)
1102
1103 Removes the specified filter *filt* from this logger.
1104
1105
1106.. method:: Logger.filter(record)
1107
1108 Applies this logger's filters to the record and returns a true value if the
1109 record is to be processed.
1110
1111
1112.. method:: Logger.addHandler(hdlr)
1113
1114 Adds the specified handler *hdlr* to this logger.
1115
1116
1117.. method:: Logger.removeHandler(hdlr)
1118
1119 Removes the specified handler *hdlr* from this logger.
1120
1121
1122.. method:: Logger.findCaller()
1123
1124 Finds the caller's source filename and line number. Returns the filename, line
1125 number and function name as a 3-element tuple.
1126
Georg Brandl116aa622007-08-15 14:28:22 +00001127
1128.. method:: Logger.handle(record)
1129
1130 Handles a record by passing it to all handlers associated with this logger and
1131 its ancestors (until a false value of *propagate* is found). This method is used
1132 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001133 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001134
1135
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001136.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001137
1138 This is a factory method which can be overridden in subclasses to create
1139 specialized :class:`LogRecord` instances.
1140
Vinay Sajip83eadd12010-09-20 10:31:18 +00001141.. method:: Logger.hasHandlers()
1142
1143 Checks to see if this logger has any handlers configured. This is done by
1144 looking for handlers in this logger and its parents in the logger hierarchy.
1145 Returns True if a handler was found, else False. The method stops searching
1146 up the hierarchy whenever a logger with the "propagate" attribute set to
1147 False is found - that will be the last logger which is checked for the
1148 existence of handlers.
1149
1150.. versionadded:: 3.2
1151
1152The :meth:`hasHandlers` method was not present in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001153
1154.. _minimal-example:
1155
1156Basic example
1157-------------
1158
Georg Brandl116aa622007-08-15 14:28:22 +00001159The :mod:`logging` package provides a lot of flexibility, and its configuration
1160can appear daunting. This section demonstrates that simple use of the logging
1161package is possible.
1162
1163The simplest example shows logging to the console::
1164
1165 import logging
1166
1167 logging.debug('A debug message')
1168 logging.info('Some information')
1169 logging.warning('A shot across the bows')
1170
1171If you run the above script, you'll see this::
1172
1173 WARNING:root:A shot across the bows
1174
1175Because no particular logger was specified, the system used the root logger. The
1176debug and info messages didn't appear because by default, the root logger is
1177configured to only handle messages with a severity of WARNING or above. The
1178message format is also a configuration default, as is the output destination of
1179the messages - ``sys.stderr``. The severity level, the message format and
1180destination can be easily changed, as shown in the example below::
1181
1182 import logging
1183
1184 logging.basicConfig(level=logging.DEBUG,
1185 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001186 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001187 filemode='w')
1188 logging.debug('A debug message')
1189 logging.info('Some information')
1190 logging.warning('A shot across the bows')
1191
1192The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001193which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001194something like the following::
1195
1196 2004-07-02 13:00:08,743 DEBUG A debug message
1197 2004-07-02 13:00:08,743 INFO Some information
1198 2004-07-02 13:00:08,743 WARNING A shot across the bows
1199
1200This time, all messages with a severity of DEBUG or above were handled, and the
1201format of the messages was also changed, and output went to the specified file
1202rather than the console.
1203
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001204.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001205
1206Formatting uses the old Python string formatting - see section
1207:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001208specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1209documentation.
1210
1211+-------------------+-----------------------------------------------+
1212| Format | Description |
1213+===================+===============================================+
1214| ``%(name)s`` | Name of the logger (logging channel). |
1215+-------------------+-----------------------------------------------+
1216| ``%(levelname)s`` | Text logging level for the message |
1217| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1218| | ``'ERROR'``, ``'CRITICAL'``). |
1219+-------------------+-----------------------------------------------+
1220| ``%(asctime)s`` | Human-readable time when the |
1221| | :class:`LogRecord` was created. By default |
1222| | this is of the form "2003-07-08 16:49:45,896" |
1223| | (the numbers after the comma are millisecond |
1224| | portion of the time). |
1225+-------------------+-----------------------------------------------+
1226| ``%(message)s`` | The logged message. |
1227+-------------------+-----------------------------------------------+
1228
1229To change the date/time format, you can pass an additional keyword parameter,
1230*datefmt*, as in the following::
1231
1232 import logging
1233
1234 logging.basicConfig(level=logging.DEBUG,
1235 format='%(asctime)s %(levelname)-8s %(message)s',
1236 datefmt='%a, %d %b %Y %H:%M:%S',
1237 filename='/temp/myapp.log',
1238 filemode='w')
1239 logging.debug('A debug message')
1240 logging.info('Some information')
1241 logging.warning('A shot across the bows')
1242
1243which would result in output like ::
1244
1245 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1246 Fri, 02 Jul 2004 13:06:18 INFO Some information
1247 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1248
1249The date format string follows the requirements of :func:`strftime` - see the
1250documentation for the :mod:`time` module.
1251
1252If, instead of sending logging output to the console or a file, you'd rather use
1253a file-like object which you have created separately, you can pass it to
1254:func:`basicConfig` using the *stream* keyword argument. Note that if both
1255*stream* and *filename* keyword arguments are passed, the *stream* argument is
1256ignored.
1257
1258Of course, you can put variable information in your output. To do this, simply
1259have the message be a format string and pass in additional arguments containing
1260the variable information, as in the following example::
1261
1262 import logging
1263
1264 logging.basicConfig(level=logging.DEBUG,
1265 format='%(asctime)s %(levelname)-8s %(message)s',
1266 datefmt='%a, %d %b %Y %H:%M:%S',
1267 filename='/temp/myapp.log',
1268 filemode='w')
1269 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1270
1271which would result in ::
1272
1273 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1274
1275
1276.. _multiple-destinations:
1277
1278Logging to multiple destinations
1279--------------------------------
1280
1281Let's say you want to log to console and file with different message formats and
1282in differing circumstances. Say you want to log messages with levels of DEBUG
1283and higher to file, and those messages at level INFO and higher to the console.
1284Let's also assume that the file should contain timestamps, but the console
1285messages should not. Here's how you can achieve this::
1286
1287 import logging
1288
1289 # set up logging to file - see previous section for more details
1290 logging.basicConfig(level=logging.DEBUG,
1291 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1292 datefmt='%m-%d %H:%M',
1293 filename='/temp/myapp.log',
1294 filemode='w')
1295 # define a Handler which writes INFO messages or higher to the sys.stderr
1296 console = logging.StreamHandler()
1297 console.setLevel(logging.INFO)
1298 # set a format which is simpler for console use
1299 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1300 # tell the handler to use this format
1301 console.setFormatter(formatter)
1302 # add the handler to the root logger
1303 logging.getLogger('').addHandler(console)
1304
1305 # Now, we can log to the root logger, or any other logger. First the root...
1306 logging.info('Jackdaws love my big sphinx of quartz.')
1307
1308 # Now, define a couple of other loggers which might represent areas in your
1309 # application:
1310
1311 logger1 = logging.getLogger('myapp.area1')
1312 logger2 = logging.getLogger('myapp.area2')
1313
1314 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1315 logger1.info('How quickly daft jumping zebras vex.')
1316 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1317 logger2.error('The five boxing wizards jump quickly.')
1318
1319When you run this, on the console you will see ::
1320
1321 root : INFO Jackdaws love my big sphinx of quartz.
1322 myapp.area1 : INFO How quickly daft jumping zebras vex.
1323 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1324 myapp.area2 : ERROR The five boxing wizards jump quickly.
1325
1326and in the file you will see something like ::
1327
1328 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1329 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1330 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1331 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1332 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1333
1334As you can see, the DEBUG message only shows up in the file. The other messages
1335are sent to both destinations.
1336
1337This example uses console and file handlers, but you can use any number and
1338combination of handlers you choose.
1339
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001340.. _logging-exceptions:
1341
1342Exceptions raised during logging
1343--------------------------------
1344
1345The logging package is designed to swallow exceptions which occur while logging
1346in production. This is so that errors which occur while handling logging events
1347- such as logging misconfiguration, network or other similar errors - do not
1348cause the application using logging to terminate prematurely.
1349
1350:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1351swallowed. Other exceptions which occur during the :meth:`emit` method of a
1352:class:`Handler` subclass are passed to its :meth:`handleError` method.
1353
1354The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001355to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1356traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001357
Georg Brandlef871f62010-03-12 10:06:40 +00001358**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001359during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001360occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001361usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001362
Christian Heimes790c8232008-01-07 21:14:23 +00001363.. _context-info:
1364
1365Adding contextual information to your logging output
1366----------------------------------------------------
1367
1368Sometimes you want logging output to contain contextual information in
1369addition to the parameters passed to the logging call. For example, in a
1370networked application, it may be desirable to log client-specific information
1371in the log (e.g. remote client's username, or IP address). Although you could
1372use the *extra* parameter to achieve this, it's not always convenient to pass
1373the information in this way. While it might be tempting to create
1374:class:`Logger` instances on a per-connection basis, this is not a good idea
1375because these instances are not garbage collected. While this is not a problem
1376in practice, when the number of :class:`Logger` instances is dependent on the
1377level of granularity you want to use in logging an application, it could
1378be hard to manage if the number of :class:`Logger` instances becomes
1379effectively unbounded.
1380
Vinay Sajipc31be632010-09-06 22:18:20 +00001381
1382Using LoggerAdapters to impart contextual information
1383^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1384
Christian Heimes04c420f2008-01-18 18:40:46 +00001385An easy way in which you can pass contextual information to be output along
1386with logging event information is to use the :class:`LoggerAdapter` class.
1387This class is designed to look like a :class:`Logger`, so that you can call
1388:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1389:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1390same signatures as their counterparts in :class:`Logger`, so you can use the
1391two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001392
Christian Heimes04c420f2008-01-18 18:40:46 +00001393When you create an instance of :class:`LoggerAdapter`, you pass it a
1394:class:`Logger` instance and a dict-like object which contains your contextual
1395information. When you call one of the logging methods on an instance of
1396:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1397:class:`Logger` passed to its constructor, and arranges to pass the contextual
1398information in the delegated call. Here's a snippet from the code of
1399:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001400
Christian Heimes04c420f2008-01-18 18:40:46 +00001401 def debug(self, msg, *args, **kwargs):
1402 """
1403 Delegate a debug call to the underlying logger, after adding
1404 contextual information from this adapter instance.
1405 """
1406 msg, kwargs = self.process(msg, kwargs)
1407 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001408
Christian Heimes04c420f2008-01-18 18:40:46 +00001409The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1410information is added to the logging output. It's passed the message and
1411keyword arguments of the logging call, and it passes back (potentially)
1412modified versions of these to use in the call to the underlying logger. The
1413default implementation of this method leaves the message alone, but inserts
1414an "extra" key in the keyword argument whose value is the dict-like object
1415passed to the constructor. Of course, if you had passed an "extra" keyword
1416argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001417
Christian Heimes04c420f2008-01-18 18:40:46 +00001418The advantage of using "extra" is that the values in the dict-like object are
1419merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1420customized strings with your :class:`Formatter` instances which know about
1421the keys of the dict-like object. If you need a different method, e.g. if you
1422want to prepend or append the contextual information to the message string,
1423you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1424to do what you need. Here's an example script which uses this class, which
1425also illustrates what dict-like behaviour is needed from an arbitrary
1426"dict-like" object for use in the constructor::
1427
Christian Heimes587c2bf2008-01-19 16:21:02 +00001428 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001429
Christian Heimes587c2bf2008-01-19 16:21:02 +00001430 class ConnInfo:
1431 """
1432 An example class which shows how an arbitrary class can be used as
1433 the 'extra' context information repository passed to a LoggerAdapter.
1434 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001435
Christian Heimes587c2bf2008-01-19 16:21:02 +00001436 def __getitem__(self, name):
1437 """
1438 To allow this instance to look like a dict.
1439 """
1440 from random import choice
1441 if name == "ip":
1442 result = choice(["127.0.0.1", "192.168.0.1"])
1443 elif name == "user":
1444 result = choice(["jim", "fred", "sheila"])
1445 else:
1446 result = self.__dict__.get(name, "?")
1447 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001448
Christian Heimes587c2bf2008-01-19 16:21:02 +00001449 def __iter__(self):
1450 """
1451 To allow iteration over keys, which will be merged into
1452 the LogRecord dict before formatting and output.
1453 """
1454 keys = ["ip", "user"]
1455 keys.extend(self.__dict__.keys())
1456 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001457
Christian Heimes587c2bf2008-01-19 16:21:02 +00001458 if __name__ == "__main__":
1459 from random import choice
1460 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1461 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1462 { "ip" : "123.231.231.123", "user" : "sheila" })
1463 logging.basicConfig(level=logging.DEBUG,
1464 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1465 a1.debug("A debug message")
1466 a1.info("An info message with %s", "some parameters")
1467 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1468 for x in range(10):
1469 lvl = choice(levels)
1470 lvlname = logging.getLevelName(lvl)
1471 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001472
1473When this script is run, the output should look something like this::
1474
Christian Heimes587c2bf2008-01-19 16:21:02 +00001475 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1476 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1477 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
1478 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
1479 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
1480 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
1481 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
1482 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
1483 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
1484 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
1485 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
1486 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Christian Heimes04c420f2008-01-18 18:40:46 +00001487
Christian Heimes790c8232008-01-07 21:14:23 +00001488
Vinay Sajipac007992010-09-17 12:45:26 +00001489.. _filters-contextual:
1490
Vinay Sajipc31be632010-09-06 22:18:20 +00001491Using Filters to impart contextual information
1492^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1493
1494You can also add contextual information to log output using a user-defined
1495:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1496passed to them, including adding additional attributes which can then be output
1497using a suitable format string, or if needed a custom :class:`Formatter`.
1498
1499For example in a web application, the request being processed (or at least,
1500the interesting parts of it) can be stored in a threadlocal
1501(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1502add, say, information from the request - say, the remote IP address and remote
1503user's username - to the ``LogRecord``, using the attribute names 'ip' and
1504'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1505string can be used to get similar output to that shown above. Here's an example
1506script::
1507
1508 import logging
1509 from random import choice
1510
1511 class ContextFilter(logging.Filter):
1512 """
1513 This is a filter which injects contextual information into the log.
1514
1515 Rather than use actual contextual information, we just use random
1516 data in this demo.
1517 """
1518
1519 USERS = ['jim', 'fred', 'sheila']
1520 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1521
1522 def filter(self, record):
1523
1524 record.ip = choice(ContextFilter.IPS)
1525 record.user = choice(ContextFilter.USERS)
1526 return True
1527
1528 if __name__ == "__main__":
1529 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1530 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1531 { "ip" : "123.231.231.123", "user" : "sheila" })
1532 logging.basicConfig(level=logging.DEBUG,
1533 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1534 a1 = logging.getLogger("a.b.c")
1535 a2 = logging.getLogger("d.e.f")
1536
1537 f = ContextFilter()
1538 a1.addFilter(f)
1539 a2.addFilter(f)
1540 a1.debug("A debug message")
1541 a1.info("An info message with %s", "some parameters")
1542 for x in range(10):
1543 lvl = choice(levels)
1544 lvlname = logging.getLevelName(lvl)
1545 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1546
1547which, when run, produces something like::
1548
1549 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1550 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1551 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1552 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters
1553 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters
1554 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters
1555 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
1556 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1557 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters
1558 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
1559 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters
1560 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters
1561
1562
Vinay Sajipd31f3632010-06-29 15:31:15 +00001563.. _multiple-processes:
1564
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001565Logging to a single file from multiple processes
1566------------------------------------------------
1567
1568Although logging is thread-safe, and logging to a single file from multiple
1569threads in a single process *is* supported, logging to a single file from
1570*multiple processes* is *not* supported, because there is no standard way to
1571serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001572need to log to a single file from multiple processes, one way of doing this is
1573to have all the processes log to a :class:`SocketHandler`, and have a separate
1574process which implements a socket server which reads from the socket and logs
1575to file. (If you prefer, you can dedicate one thread in one of the existing
1576processes to perform this function.) The following section documents this
1577approach in more detail and includes a working socket receiver which can be
1578used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001579
Vinay Sajip5a92b132009-08-15 23:35:08 +00001580If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001581:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001582:class:`Lock` class from this module to serialize access to the file from
1583your processes. The existing :class:`FileHandler` and subclasses do not make
1584use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001585Note that at present, the :mod:`multiprocessing` module does not provide
1586working lock functionality on all platforms (see
1587http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001588
Vinay Sajip121a1c42010-09-08 10:46:15 +00001589.. currentmodule:: logging.handlers
1590
1591Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1592all logging events to one of the processes in your multi-process application.
1593The following example script demonstrates how you can do this; in the example
1594a separate listener process listens for events sent by other processes and logs
1595them according to its own logging configuration. Although the example only
1596demonstrates one way of doing it (for example, you may want to use a listener
1597thread rather than a separate listener process - the implementation would be
1598analogous) it does allow for completely different logging configurations for
1599the listener and the other processes in your application, and can be used as
1600the basis for code meeting your own specific requirements::
1601
1602 # You'll need these imports in your own code
1603 import logging
1604 import logging.handlers
1605 import multiprocessing
1606
1607 # Next two import lines for this demo only
1608 from random import choice, random
1609 import time
1610
1611 #
1612 # Because you'll want to define the logging configurations for listener and workers, the
1613 # listener and worker process functions take a configurer parameter which is a callable
1614 # for configuring logging for that process. These functions are also passed the queue,
1615 # which they use for communication.
1616 #
1617 # In practice, you can configure the listener however you want, but note that in this
1618 # simple example, the listener does not apply level or filter logic to received records.
1619 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1620 # sending events which would be filtered out between processes.
1621 #
1622 # The size of the rotated files is made small so you can see the results easily.
1623 def listener_configurer():
1624 root = logging.getLogger()
1625 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
1626 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1627 h.setFormatter(f)
1628 root.addHandler(h)
1629
1630 # This is the listener process top-level loop: wait for logging events
1631 # (LogRecords)on the queue and handle them, quit when you get a None for a
1632 # LogRecord.
1633 def listener_process(queue, configurer):
1634 configurer()
1635 while True:
1636 try:
1637 record = queue.get()
1638 if record is None: # We send this as a sentinel to tell the listener to quit.
1639 break
1640 logger = logging.getLogger(record.name)
1641 logger.handle(record) # No level or filter logic applied - just do it!
1642 except (KeyboardInterrupt, SystemExit):
1643 raise
1644 except:
1645 import sys, traceback
1646 print >> sys.stderr, 'Whoops! Problem:'
1647 traceback.print_exc(file=sys.stderr)
1648
1649 # Arrays used for random selections in this demo
1650
1651 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1652 logging.ERROR, logging.CRITICAL]
1653
1654 LOGGERS = ['a.b.c', 'd.e.f']
1655
1656 MESSAGES = [
1657 'Random message #1',
1658 'Random message #2',
1659 'Random message #3',
1660 ]
1661
1662 # The worker configuration is done at the start of the worker process run.
1663 # Note that on Windows you can't rely on fork semantics, so each process
1664 # will run the logging configuration code when it starts.
1665 def worker_configurer(queue):
1666 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1667 root = logging.getLogger()
1668 root.addHandler(h)
1669 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
1670
1671 # This is the worker process top-level loop, which just logs ten events with
1672 # random intervening delays before terminating.
1673 # The print messages are just so you know it's doing something!
1674 def worker_process(queue, configurer):
1675 configurer(queue)
1676 name = multiprocessing.current_process().name
1677 print('Worker started: %s' % name)
1678 for i in range(10):
1679 time.sleep(random())
1680 logger = logging.getLogger(choice(LOGGERS))
1681 level = choice(LEVELS)
1682 message = choice(MESSAGES)
1683 logger.log(level, message)
1684 print('Worker finished: %s' % name)
1685
1686 # Here's where the demo gets orchestrated. Create the queue, create and start
1687 # the listener, create ten workers and start them, wait for them to finish,
1688 # then send a None to the queue to tell the listener to finish.
1689 def main():
1690 queue = multiprocessing.Queue(-1)
1691 listener = multiprocessing.Process(target=listener_process,
1692 args=(queue, listener_configurer))
1693 listener.start()
1694 workers = []
1695 for i in range(10):
1696 worker = multiprocessing.Process(target=worker_process,
1697 args=(queue, worker_configurer))
1698 workers.append(worker)
1699 worker.start()
1700 for w in workers:
1701 w.join()
1702 queue.put_nowait(None)
1703 listener.join()
1704
1705 if __name__ == '__main__':
1706 main()
1707
1708
1709.. currentmodule:: logging
1710
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001711
Georg Brandl116aa622007-08-15 14:28:22 +00001712.. _network-logging:
1713
1714Sending and receiving logging events across a network
1715-----------------------------------------------------
1716
1717Let's say you want to send logging events across a network, and handle them at
1718the receiving end. A simple way of doing this is attaching a
1719:class:`SocketHandler` instance to the root logger at the sending end::
1720
1721 import logging, logging.handlers
1722
1723 rootLogger = logging.getLogger('')
1724 rootLogger.setLevel(logging.DEBUG)
1725 socketHandler = logging.handlers.SocketHandler('localhost',
1726 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1727 # don't bother with a formatter, since a socket handler sends the event as
1728 # an unformatted pickle
1729 rootLogger.addHandler(socketHandler)
1730
1731 # Now, we can log to the root logger, or any other logger. First the root...
1732 logging.info('Jackdaws love my big sphinx of quartz.')
1733
1734 # Now, define a couple of other loggers which might represent areas in your
1735 # application:
1736
1737 logger1 = logging.getLogger('myapp.area1')
1738 logger2 = logging.getLogger('myapp.area2')
1739
1740 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1741 logger1.info('How quickly daft jumping zebras vex.')
1742 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1743 logger2.error('The five boxing wizards jump quickly.')
1744
Alexandre Vassalottice261952008-05-12 02:31:37 +00001745At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001746module. Here is a basic working example::
1747
Georg Brandla35f4b92009-05-31 16:41:59 +00001748 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001749 import logging
1750 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001751 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001752 import struct
1753
1754
Alexandre Vassalottice261952008-05-12 02:31:37 +00001755 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001756 """Handler for a streaming logging request.
1757
1758 This basically logs the record using whatever logging policy is
1759 configured locally.
1760 """
1761
1762 def handle(self):
1763 """
1764 Handle multiple requests - each expected to be a 4-byte length,
1765 followed by the LogRecord in pickle format. Logs the record
1766 according to whatever policy is configured locally.
1767 """
Collin Winter46334482007-09-10 00:49:57 +00001768 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001769 chunk = self.connection.recv(4)
1770 if len(chunk) < 4:
1771 break
1772 slen = struct.unpack(">L", chunk)[0]
1773 chunk = self.connection.recv(slen)
1774 while len(chunk) < slen:
1775 chunk = chunk + self.connection.recv(slen - len(chunk))
1776 obj = self.unPickle(chunk)
1777 record = logging.makeLogRecord(obj)
1778 self.handleLogRecord(record)
1779
1780 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001781 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001782
1783 def handleLogRecord(self, record):
1784 # if a name is specified, we use the named logger rather than the one
1785 # implied by the record.
1786 if self.server.logname is not None:
1787 name = self.server.logname
1788 else:
1789 name = record.name
1790 logger = logging.getLogger(name)
1791 # N.B. EVERY record gets logged. This is because Logger.handle
1792 # is normally called AFTER logger-level filtering. If you want
1793 # to do filtering, do it at the client end to save wasting
1794 # cycles and network bandwidth!
1795 logger.handle(record)
1796
Alexandre Vassalottice261952008-05-12 02:31:37 +00001797 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001798 """simple TCP socket-based logging receiver suitable for testing.
1799 """
1800
1801 allow_reuse_address = 1
1802
1803 def __init__(self, host='localhost',
1804 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1805 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001806 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001807 self.abort = 0
1808 self.timeout = 1
1809 self.logname = None
1810
1811 def serve_until_stopped(self):
1812 import select
1813 abort = 0
1814 while not abort:
1815 rd, wr, ex = select.select([self.socket.fileno()],
1816 [], [],
1817 self.timeout)
1818 if rd:
1819 self.handle_request()
1820 abort = self.abort
1821
1822 def main():
1823 logging.basicConfig(
1824 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1825 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001826 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001827 tcpserver.serve_until_stopped()
1828
1829 if __name__ == "__main__":
1830 main()
1831
1832First run the server, and then the client. On the client side, nothing is
1833printed on the console; on the server side, you should see something like::
1834
1835 About to start TCP server...
1836 59 root INFO Jackdaws love my big sphinx of quartz.
1837 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1838 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1839 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1840 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1841
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001842Note that there are some security issues with pickle in some scenarios. If
1843these affect you, you can use an alternative serialization scheme by overriding
1844the :meth:`makePickle` method and implementing your alternative there, as
1845well as adapting the above script to use your alternative serialization.
1846
Vinay Sajip4039aff2010-09-11 10:25:28 +00001847.. _arbitrary-object-messages:
1848
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001849Using arbitrary objects as messages
1850-----------------------------------
1851
1852In the preceding sections and examples, it has been assumed that the message
1853passed when logging the event is a string. However, this is not the only
1854possibility. You can pass an arbitrary object as a message, and its
1855:meth:`__str__` method will be called when the logging system needs to convert
1856it to a string representation. In fact, if you want to, you can avoid
1857computing a string representation altogether - for example, the
1858:class:`SocketHandler` emits an event by pickling it and sending it over the
1859wire.
1860
Vinay Sajip55778922010-09-23 09:09:15 +00001861Dealing with handlers that block
1862--------------------------------
1863
1864.. currentmodule:: logging.handlers
1865
1866Sometimes you have to get your logging handlers to do their work without
1867blocking the thread you’re logging from. This is common in Web applications,
1868though of course it also occurs in other scenarios.
1869
1870A common culprit which demonstrates sluggish behaviour is the
1871:class:`SMTPHandler`: sending emails can take a long time, for a
1872number of reasons outside the developer’s control (for example, a poorly
1873performing mail or network infrastructure). But almost any network-based
1874handler can block: Even a :class:`SocketHandler` operation may do a
1875DNS query under the hood which is too slow (and this query can be deep in the
1876socket library code, below the Python layer, and outside your control).
1877
1878One solution is to use a two-part approach. For the first part, attach only a
1879:class:`QueueHandler` to those loggers which are accessed from
1880performance-critical threads. They simply write to their queue, which can be
1881sized to a large enough capacity or initialized with no upper bound to their
1882size. The write to the queue will typically be accepted quickly, though you
1883will probably need to catch the :ref:`queue.Full` exception as a precaution
1884in your code. If you are a library developer who has performance-critical
1885threads in their code, be sure to document this (together with a suggestion to
1886attach only ``QueueHandlers`` to your loggers) for the benefit of other
1887developers who will use your code.
1888
1889The second part of the solution is :class:`QueueListener`, which has been
1890designed as the counterpart to :class:`QueueHandler`. A
1891:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
1892and it fires up an internal thread which listens to its queue for LogRecords
1893sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
1894matter). The ``LogRecords`` are removed from the queue and passed to the
1895handlers for processing.
1896
1897The advantage of having a separate :class:`QueueListener` class is that you
1898can use the same instance to service multiple ``QueueHandlers``. This is more
1899resource-friendly than, say, having threaded versions of the existing handler
1900classes, which would eat up one thread per handler for no particular benefit.
1901
1902An example of using these two classes follows (imports omitted)::
1903
1904 que = queue.Queue(-1) # no limit on size
1905 queue_handler = QueueHandler(que)
1906 handler = logging.StreamHandler()
1907 listener = QueueListener(que, handler)
1908 root = logging.getLogger()
1909 root.addHandler(queue_handler)
1910 formatter = logging.Formatter('%(threadName)s: %(message)s')
1911 handler.setFormatter(formatter)
1912 listener.start()
1913 # The log output will display the thread which generated
1914 # the event (the main thread) rather than the internal
1915 # thread which monitors the internal queue. This is what
1916 # you want to happen.
1917 root.warning('Look out!')
1918 listener.stop()
1919
1920which, when run, will produce::
1921
1922 MainThread: Look out!
1923
1924
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001925Optimization
1926------------
1927
1928Formatting of message arguments is deferred until it cannot be avoided.
1929However, computing the arguments passed to the logging method can also be
1930expensive, and you may want to avoid doing it if the logger will just throw
1931away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1932method which takes a level argument and returns true if the event would be
1933created by the Logger for that level of call. You can write code like this::
1934
1935 if logger.isEnabledFor(logging.DEBUG):
1936 logger.debug("Message with %s, %s", expensive_func1(),
1937 expensive_func2())
1938
1939so that if the logger's threshold is set above ``DEBUG``, the calls to
1940:func:`expensive_func1` and :func:`expensive_func2` are never made.
1941
1942There are other optimizations which can be made for specific applications which
1943need more precise control over what logging information is collected. Here's a
1944list of things you can do to avoid processing during logging which you don't
1945need:
1946
1947+-----------------------------------------------+----------------------------------------+
1948| What you don't want to collect | How to avoid collecting it |
1949+===============================================+========================================+
1950| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1951+-----------------------------------------------+----------------------------------------+
1952| Threading information. | Set ``logging.logThreads`` to ``0``. |
1953+-----------------------------------------------+----------------------------------------+
1954| Process information. | Set ``logging.logProcesses`` to ``0``. |
1955+-----------------------------------------------+----------------------------------------+
1956
1957Also note that the core logging module only includes the basic handlers. If
1958you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1959take up any memory.
1960
1961.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001962
1963Handler Objects
1964---------------
1965
1966Handlers have the following attributes and methods. Note that :class:`Handler`
1967is never instantiated directly; this class acts as a base for more useful
1968subclasses. However, the :meth:`__init__` method in subclasses needs to call
1969:meth:`Handler.__init__`.
1970
1971
1972.. method:: Handler.__init__(level=NOTSET)
1973
1974 Initializes the :class:`Handler` instance by setting its level, setting the list
1975 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1976 serializing access to an I/O mechanism.
1977
1978
1979.. method:: Handler.createLock()
1980
1981 Initializes a thread lock which can be used to serialize access to underlying
1982 I/O functionality which may not be threadsafe.
1983
1984
1985.. method:: Handler.acquire()
1986
1987 Acquires the thread lock created with :meth:`createLock`.
1988
1989
1990.. method:: Handler.release()
1991
1992 Releases the thread lock acquired with :meth:`acquire`.
1993
1994
1995.. method:: Handler.setLevel(lvl)
1996
1997 Sets the threshold for this handler to *lvl*. Logging messages which are less
1998 severe than *lvl* will be ignored. When a handler is created, the level is set
1999 to :const:`NOTSET` (which causes all messages to be processed).
2000
2001
2002.. method:: Handler.setFormatter(form)
2003
2004 Sets the :class:`Formatter` for this handler to *form*.
2005
2006
2007.. method:: Handler.addFilter(filt)
2008
2009 Adds the specified filter *filt* to this handler.
2010
2011
2012.. method:: Handler.removeFilter(filt)
2013
2014 Removes the specified filter *filt* from this handler.
2015
2016
2017.. method:: Handler.filter(record)
2018
2019 Applies this handler's filters to the record and returns a true value if the
2020 record is to be processed.
2021
2022
2023.. method:: Handler.flush()
2024
2025 Ensure all logging output has been flushed. This version does nothing and is
2026 intended to be implemented by subclasses.
2027
2028
2029.. method:: Handler.close()
2030
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002031 Tidy up any resources used by the handler. This version does no output but
2032 removes the handler from an internal list of handlers which is closed when
2033 :func:`shutdown` is called. Subclasses should ensure that this gets called
2034 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002035
2036
2037.. method:: Handler.handle(record)
2038
2039 Conditionally emits the specified logging record, depending on filters which may
2040 have been added to the handler. Wraps the actual emission of the record with
2041 acquisition/release of the I/O thread lock.
2042
2043
2044.. method:: Handler.handleError(record)
2045
2046 This method should be called from handlers when an exception is encountered
2047 during an :meth:`emit` call. By default it does nothing, which means that
2048 exceptions get silently ignored. This is what is mostly wanted for a logging
2049 system - most users will not care about errors in the logging system, they are
2050 more interested in application errors. You could, however, replace this with a
2051 custom handler if you wish. The specified record is the one which was being
2052 processed when the exception occurred.
2053
2054
2055.. method:: Handler.format(record)
2056
2057 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2058 default formatter for the module.
2059
2060
2061.. method:: Handler.emit(record)
2062
2063 Do whatever it takes to actually log the specified logging record. This version
2064 is intended to be implemented by subclasses and so raises a
2065 :exc:`NotImplementedError`.
2066
2067
Vinay Sajipd31f3632010-06-29 15:31:15 +00002068.. _stream-handler:
2069
Georg Brandl116aa622007-08-15 14:28:22 +00002070StreamHandler
2071^^^^^^^^^^^^^
2072
2073The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2074sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2075file-like object (or, more precisely, any object which supports :meth:`write`
2076and :meth:`flush` methods).
2077
2078
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002079.. currentmodule:: logging
2080
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002081.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002082
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002083 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002084 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2085 will be used.
2086
2087
Benjamin Petersone41251e2008-04-25 01:59:09 +00002088 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002089
Benjamin Petersone41251e2008-04-25 01:59:09 +00002090 If a formatter is specified, it is used to format the record. The record
2091 is then written to the stream with a trailing newline. If exception
2092 information is present, it is formatted using
2093 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002094
2095
Benjamin Petersone41251e2008-04-25 01:59:09 +00002096 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002097
Benjamin Petersone41251e2008-04-25 01:59:09 +00002098 Flushes the stream by calling its :meth:`flush` method. Note that the
2099 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002100 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002101
2102
Vinay Sajipd31f3632010-06-29 15:31:15 +00002103.. _file-handler:
2104
Georg Brandl116aa622007-08-15 14:28:22 +00002105FileHandler
2106^^^^^^^^^^^
2107
2108The :class:`FileHandler` class, located in the core :mod:`logging` package,
2109sends logging output to a disk file. It inherits the output functionality from
2110:class:`StreamHandler`.
2111
2112
Vinay Sajipd31f3632010-06-29 15:31:15 +00002113.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002114
2115 Returns a new instance of the :class:`FileHandler` class. The specified file is
2116 opened and used as the stream for logging. If *mode* is not specified,
2117 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002118 with that encoding. If *delay* is true, then file opening is deferred until the
2119 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002120
2121
Benjamin Petersone41251e2008-04-25 01:59:09 +00002122 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002123
Benjamin Petersone41251e2008-04-25 01:59:09 +00002124 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002125
2126
Benjamin Petersone41251e2008-04-25 01:59:09 +00002127 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002128
Benjamin Petersone41251e2008-04-25 01:59:09 +00002129 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002130
Vinay Sajipd31f3632010-06-29 15:31:15 +00002131.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002132
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002133NullHandler
2134^^^^^^^^^^^
2135
2136.. versionadded:: 3.1
2137
2138The :class:`NullHandler` class, located in the core :mod:`logging` package,
2139does not do any formatting or output. It is essentially a "no-op" handler
2140for use by library developers.
2141
2142
2143.. class:: NullHandler()
2144
2145 Returns a new instance of the :class:`NullHandler` class.
2146
2147
2148 .. method:: emit(record)
2149
2150 This method does nothing.
2151
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002152 .. method:: handle(record)
2153
2154 This method does nothing.
2155
2156 .. method:: createLock()
2157
2158 This method returns `None` for the lock, since there is no
2159 underlying I/O to which access needs to be serialized.
2160
2161
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002162See :ref:`library-config` for more information on how to use
2163:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002164
Vinay Sajipd31f3632010-06-29 15:31:15 +00002165.. _watched-file-handler:
2166
Georg Brandl116aa622007-08-15 14:28:22 +00002167WatchedFileHandler
2168^^^^^^^^^^^^^^^^^^
2169
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002170.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002171
Georg Brandl116aa622007-08-15 14:28:22 +00002172The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2173module, is a :class:`FileHandler` which watches the file it is logging to. If
2174the file changes, it is closed and reopened using the file name.
2175
2176A file change can happen because of usage of programs such as *newsyslog* and
2177*logrotate* which perform log file rotation. This handler, intended for use
2178under Unix/Linux, watches the file to see if it has changed since the last emit.
2179(A file is deemed to have changed if its device or inode have changed.) If the
2180file has changed, the old file stream is closed, and the file opened to get a
2181new stream.
2182
2183This handler is not appropriate for use under Windows, because under Windows
2184open log files cannot be moved or renamed - logging opens the files with
2185exclusive locks - and so there is no need for such a handler. Furthermore,
2186*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2187this value.
2188
2189
Christian Heimese7a15bb2008-01-24 16:21:45 +00002190.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002191
2192 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2193 file is opened and used as the stream for logging. If *mode* is not specified,
2194 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002195 with that encoding. If *delay* is true, then file opening is deferred until the
2196 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002197
2198
Benjamin Petersone41251e2008-04-25 01:59:09 +00002199 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002200
Benjamin Petersone41251e2008-04-25 01:59:09 +00002201 Outputs the record to the file, but first checks to see if the file has
2202 changed. If it has, the existing stream is flushed and closed and the
2203 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002204
Vinay Sajipd31f3632010-06-29 15:31:15 +00002205.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002206
2207RotatingFileHandler
2208^^^^^^^^^^^^^^^^^^^
2209
2210The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2211module, supports rotation of disk log files.
2212
2213
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002214.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002215
2216 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2217 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002218 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2219 with that encoding. If *delay* is true, then file opening is deferred until the
2220 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002221
2222 You can use the *maxBytes* and *backupCount* values to allow the file to
2223 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2224 the file is closed and a new file is silently opened for output. Rollover occurs
2225 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2226 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2227 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2228 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2229 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2230 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2231 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2232 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2233 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2234
2235
Benjamin Petersone41251e2008-04-25 01:59:09 +00002236 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002237
Benjamin Petersone41251e2008-04-25 01:59:09 +00002238 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002239
2240
Benjamin Petersone41251e2008-04-25 01:59:09 +00002241 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002242
Benjamin Petersone41251e2008-04-25 01:59:09 +00002243 Outputs the record to the file, catering for rollover as described
2244 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002245
Vinay Sajipd31f3632010-06-29 15:31:15 +00002246.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002247
2248TimedRotatingFileHandler
2249^^^^^^^^^^^^^^^^^^^^^^^^
2250
2251The :class:`TimedRotatingFileHandler` class, located in the
2252:mod:`logging.handlers` module, supports rotation of disk log files at certain
2253timed intervals.
2254
2255
Vinay Sajipd31f3632010-06-29 15:31:15 +00002256.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002257
2258 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2259 specified file is opened and used as the stream for logging. On rotating it also
2260 sets the filename suffix. Rotating happens based on the product of *when* and
2261 *interval*.
2262
2263 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002264 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002265
Christian Heimesb558a2e2008-03-02 22:46:37 +00002266 +----------------+-----------------------+
2267 | Value | Type of interval |
2268 +================+=======================+
2269 | ``'S'`` | Seconds |
2270 +----------------+-----------------------+
2271 | ``'M'`` | Minutes |
2272 +----------------+-----------------------+
2273 | ``'H'`` | Hours |
2274 +----------------+-----------------------+
2275 | ``'D'`` | Days |
2276 +----------------+-----------------------+
2277 | ``'W'`` | Week day (0=Monday) |
2278 +----------------+-----------------------+
2279 | ``'midnight'`` | Roll over at midnight |
2280 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002281
Christian Heimesb558a2e2008-03-02 22:46:37 +00002282 The system will save old log files by appending extensions to the filename.
2283 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002284 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002285 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002286
2287 When computing the next rollover time for the first time (when the handler
2288 is created), the last modification time of an existing log file, or else
2289 the current time, is used to compute when the next rotation will occur.
2290
Georg Brandl0c77a822008-06-10 16:37:50 +00002291 If the *utc* argument is true, times in UTC will be used; otherwise
2292 local time is used.
2293
2294 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002295 will be kept, and if more would be created when rollover occurs, the oldest
2296 one is deleted. The deletion logic uses the interval to determine which
2297 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002298
Vinay Sajipd31f3632010-06-29 15:31:15 +00002299 If *delay* is true, then file opening is deferred until the first call to
2300 :meth:`emit`.
2301
Georg Brandl116aa622007-08-15 14:28:22 +00002302
Benjamin Petersone41251e2008-04-25 01:59:09 +00002303 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002304
Benjamin Petersone41251e2008-04-25 01:59:09 +00002305 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002306
2307
Benjamin Petersone41251e2008-04-25 01:59:09 +00002308 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002309
Benjamin Petersone41251e2008-04-25 01:59:09 +00002310 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002311
2312
Vinay Sajipd31f3632010-06-29 15:31:15 +00002313.. _socket-handler:
2314
Georg Brandl116aa622007-08-15 14:28:22 +00002315SocketHandler
2316^^^^^^^^^^^^^
2317
2318The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2319sends logging output to a network socket. The base class uses a TCP socket.
2320
2321
2322.. class:: SocketHandler(host, port)
2323
2324 Returns a new instance of the :class:`SocketHandler` class intended to
2325 communicate with a remote machine whose address is given by *host* and *port*.
2326
2327
Benjamin Petersone41251e2008-04-25 01:59:09 +00002328 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002329
Benjamin Petersone41251e2008-04-25 01:59:09 +00002330 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002331
2332
Benjamin Petersone41251e2008-04-25 01:59:09 +00002333 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002334
Benjamin Petersone41251e2008-04-25 01:59:09 +00002335 Pickles the record's attribute dictionary and writes it to the socket in
2336 binary format. If there is an error with the socket, silently drops the
2337 packet. If the connection was previously lost, re-establishes the
2338 connection. To unpickle the record at the receiving end into a
2339 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002340
2341
Benjamin Petersone41251e2008-04-25 01:59:09 +00002342 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002343
Benjamin Petersone41251e2008-04-25 01:59:09 +00002344 Handles an error which has occurred during :meth:`emit`. The most likely
2345 cause is a lost connection. Closes the socket so that we can retry on the
2346 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002347
2348
Benjamin Petersone41251e2008-04-25 01:59:09 +00002349 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002350
Benjamin Petersone41251e2008-04-25 01:59:09 +00002351 This is a factory method which allows subclasses to define the precise
2352 type of socket they want. The default implementation creates a TCP socket
2353 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002354
2355
Benjamin Petersone41251e2008-04-25 01:59:09 +00002356 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002357
Benjamin Petersone41251e2008-04-25 01:59:09 +00002358 Pickles the record's attribute dictionary in binary format with a length
2359 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002360
Vinay Sajipd31f3632010-06-29 15:31:15 +00002361 Note that pickles aren't completely secure. If you are concerned about
2362 security, you may want to override this method to implement a more secure
2363 mechanism. For example, you can sign pickles using HMAC and then verify
2364 them on the receiving end, or alternatively you can disable unpickling of
2365 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002366
Benjamin Petersone41251e2008-04-25 01:59:09 +00002367 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002368
Benjamin Petersone41251e2008-04-25 01:59:09 +00002369 Send a pickled string *packet* to the socket. This function allows for
2370 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002371
2372
Vinay Sajipd31f3632010-06-29 15:31:15 +00002373.. _datagram-handler:
2374
Georg Brandl116aa622007-08-15 14:28:22 +00002375DatagramHandler
2376^^^^^^^^^^^^^^^
2377
2378The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2379module, inherits from :class:`SocketHandler` to support sending logging messages
2380over UDP sockets.
2381
2382
2383.. class:: DatagramHandler(host, port)
2384
2385 Returns a new instance of the :class:`DatagramHandler` class intended to
2386 communicate with a remote machine whose address is given by *host* and *port*.
2387
2388
Benjamin Petersone41251e2008-04-25 01:59:09 +00002389 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002390
Benjamin Petersone41251e2008-04-25 01:59:09 +00002391 Pickles the record's attribute dictionary and writes it to the socket in
2392 binary format. If there is an error with the socket, silently drops the
2393 packet. To unpickle the record at the receiving end into a
2394 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002395
2396
Benjamin Petersone41251e2008-04-25 01:59:09 +00002397 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002398
Benjamin Petersone41251e2008-04-25 01:59:09 +00002399 The factory method of :class:`SocketHandler` is here overridden to create
2400 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002401
2402
Benjamin Petersone41251e2008-04-25 01:59:09 +00002403 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002404
Benjamin Petersone41251e2008-04-25 01:59:09 +00002405 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002406
2407
Vinay Sajipd31f3632010-06-29 15:31:15 +00002408.. _syslog-handler:
2409
Georg Brandl116aa622007-08-15 14:28:22 +00002410SysLogHandler
2411^^^^^^^^^^^^^
2412
2413The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2414supports sending logging messages to a remote or local Unix syslog.
2415
2416
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002417.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002418
2419 Returns a new instance of the :class:`SysLogHandler` class intended to
2420 communicate with a remote Unix machine whose address is given by *address* in
2421 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002422 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002423 alternative to providing a ``(host, port)`` tuple is providing an address as a
2424 string, for example "/dev/log". In this case, a Unix domain socket is used to
2425 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002426 :const:`LOG_USER` is used. The type of socket opened depends on the
2427 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2428 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2429 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2430
Vinay Sajip972412d2010-09-23 20:31:24 +00002431 Note that if your server is not listening on UDP port 514,
2432 :class:`SysLogHandler` may appear not to work. In that case, check what
2433 address you should be using for a domain socket - it's system dependent.
2434 For example, on Linux it's usually "/dev/log" but on OS/X it's
2435 "/var/run/syslog". You'll need to check your platform and use the
2436 appropriate address (you may need to do this check at runtime if your
2437 application needs to run on several platforms). On Windows, you pretty
2438 much have to use the UDP option.
2439
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002440 .. versionchanged:: 3.2
2441 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002442
2443
Benjamin Petersone41251e2008-04-25 01:59:09 +00002444 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002445
Benjamin Petersone41251e2008-04-25 01:59:09 +00002446 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002447
2448
Benjamin Petersone41251e2008-04-25 01:59:09 +00002449 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002450
Benjamin Petersone41251e2008-04-25 01:59:09 +00002451 The record is formatted, and then sent to the syslog server. If exception
2452 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002453
2454
Benjamin Petersone41251e2008-04-25 01:59:09 +00002455 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002456
Benjamin Petersone41251e2008-04-25 01:59:09 +00002457 Encodes the facility and priority into an integer. You can pass in strings
2458 or integers - if strings are passed, internal mapping dictionaries are
2459 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002460
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002461 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2462 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002463
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002464 **Priorities**
2465
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002466 +--------------------------+---------------+
2467 | Name (string) | Symbolic value|
2468 +==========================+===============+
2469 | ``alert`` | LOG_ALERT |
2470 +--------------------------+---------------+
2471 | ``crit`` or ``critical`` | LOG_CRIT |
2472 +--------------------------+---------------+
2473 | ``debug`` | LOG_DEBUG |
2474 +--------------------------+---------------+
2475 | ``emerg`` or ``panic`` | LOG_EMERG |
2476 +--------------------------+---------------+
2477 | ``err`` or ``error`` | LOG_ERR |
2478 +--------------------------+---------------+
2479 | ``info`` | LOG_INFO |
2480 +--------------------------+---------------+
2481 | ``notice`` | LOG_NOTICE |
2482 +--------------------------+---------------+
2483 | ``warn`` or ``warning`` | LOG_WARNING |
2484 +--------------------------+---------------+
2485
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002486 **Facilities**
2487
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002488 +---------------+---------------+
2489 | Name (string) | Symbolic value|
2490 +===============+===============+
2491 | ``auth`` | LOG_AUTH |
2492 +---------------+---------------+
2493 | ``authpriv`` | LOG_AUTHPRIV |
2494 +---------------+---------------+
2495 | ``cron`` | LOG_CRON |
2496 +---------------+---------------+
2497 | ``daemon`` | LOG_DAEMON |
2498 +---------------+---------------+
2499 | ``ftp`` | LOG_FTP |
2500 +---------------+---------------+
2501 | ``kern`` | LOG_KERN |
2502 +---------------+---------------+
2503 | ``lpr`` | LOG_LPR |
2504 +---------------+---------------+
2505 | ``mail`` | LOG_MAIL |
2506 +---------------+---------------+
2507 | ``news`` | LOG_NEWS |
2508 +---------------+---------------+
2509 | ``syslog`` | LOG_SYSLOG |
2510 +---------------+---------------+
2511 | ``user`` | LOG_USER |
2512 +---------------+---------------+
2513 | ``uucp`` | LOG_UUCP |
2514 +---------------+---------------+
2515 | ``local0`` | LOG_LOCAL0 |
2516 +---------------+---------------+
2517 | ``local1`` | LOG_LOCAL1 |
2518 +---------------+---------------+
2519 | ``local2`` | LOG_LOCAL2 |
2520 +---------------+---------------+
2521 | ``local3`` | LOG_LOCAL3 |
2522 +---------------+---------------+
2523 | ``local4`` | LOG_LOCAL4 |
2524 +---------------+---------------+
2525 | ``local5`` | LOG_LOCAL5 |
2526 +---------------+---------------+
2527 | ``local6`` | LOG_LOCAL6 |
2528 +---------------+---------------+
2529 | ``local7`` | LOG_LOCAL7 |
2530 +---------------+---------------+
2531
2532 .. method:: mapPriority(levelname)
2533
2534 Maps a logging level name to a syslog priority name.
2535 You may need to override this if you are using custom levels, or
2536 if the default algorithm is not suitable for your needs. The
2537 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2538 ``CRITICAL`` to the equivalent syslog names, and all other level
2539 names to "warning".
2540
2541.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002542
2543NTEventLogHandler
2544^^^^^^^^^^^^^^^^^
2545
2546The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2547module, supports sending logging messages to a local Windows NT, Windows 2000 or
2548Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2549extensions for Python installed.
2550
2551
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002552.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002553
2554 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2555 used to define the application name as it appears in the event log. An
2556 appropriate registry entry is created using this name. The *dllname* should give
2557 the fully qualified pathname of a .dll or .exe which contains message
2558 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2559 - this is installed with the Win32 extensions and contains some basic
2560 placeholder message definitions. Note that use of these placeholders will make
2561 your event logs big, as the entire message source is held in the log. If you
2562 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2563 contains the message definitions you want to use in the event log). The
2564 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2565 defaults to ``'Application'``.
2566
2567
Benjamin Petersone41251e2008-04-25 01:59:09 +00002568 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002569
Benjamin Petersone41251e2008-04-25 01:59:09 +00002570 At this point, you can remove the application name from the registry as a
2571 source of event log entries. However, if you do this, you will not be able
2572 to see the events as you intended in the Event Log Viewer - it needs to be
2573 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002574 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002575
2576
Benjamin Petersone41251e2008-04-25 01:59:09 +00002577 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002578
Benjamin Petersone41251e2008-04-25 01:59:09 +00002579 Determines the message ID, event category and event type, and then logs
2580 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002581
2582
Benjamin Petersone41251e2008-04-25 01:59:09 +00002583 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002584
Benjamin Petersone41251e2008-04-25 01:59:09 +00002585 Returns the event category for the record. Override this if you want to
2586 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002587
2588
Benjamin Petersone41251e2008-04-25 01:59:09 +00002589 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002590
Benjamin Petersone41251e2008-04-25 01:59:09 +00002591 Returns the event type for the record. Override this if you want to
2592 specify your own types. This version does a mapping using the handler's
2593 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2594 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2595 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2596 your own levels, you will either need to override this method or place a
2597 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002598
2599
Benjamin Petersone41251e2008-04-25 01:59:09 +00002600 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002601
Benjamin Petersone41251e2008-04-25 01:59:09 +00002602 Returns the message ID for the record. If you are using your own messages,
2603 you could do this by having the *msg* passed to the logger being an ID
2604 rather than a format string. Then, in here, you could use a dictionary
2605 lookup to get the message ID. This version returns 1, which is the base
2606 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002607
Vinay Sajipd31f3632010-06-29 15:31:15 +00002608.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002609
2610SMTPHandler
2611^^^^^^^^^^^
2612
2613The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2614supports sending logging messages to an email address via SMTP.
2615
2616
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002617.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002618
2619 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2620 initialized with the from and to addresses and subject line of the email. The
2621 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2622 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2623 the standard SMTP port is used. If your SMTP server requires authentication, you
2624 can specify a (username, password) tuple for the *credentials* argument.
2625
Georg Brandl116aa622007-08-15 14:28:22 +00002626
Benjamin Petersone41251e2008-04-25 01:59:09 +00002627 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002628
Benjamin Petersone41251e2008-04-25 01:59:09 +00002629 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002630
2631
Benjamin Petersone41251e2008-04-25 01:59:09 +00002632 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002633
Benjamin Petersone41251e2008-04-25 01:59:09 +00002634 If you want to specify a subject line which is record-dependent, override
2635 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002636
Vinay Sajipd31f3632010-06-29 15:31:15 +00002637.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002638
2639MemoryHandler
2640^^^^^^^^^^^^^
2641
2642The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2643supports buffering of logging records in memory, periodically flushing them to a
2644:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2645event of a certain severity or greater is seen.
2646
2647:class:`MemoryHandler` is a subclass of the more general
2648:class:`BufferingHandler`, which is an abstract class. This buffers logging
2649records in memory. Whenever each record is added to the buffer, a check is made
2650by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2651should, then :meth:`flush` is expected to do the needful.
2652
2653
2654.. class:: BufferingHandler(capacity)
2655
2656 Initializes the handler with a buffer of the specified capacity.
2657
2658
Benjamin Petersone41251e2008-04-25 01:59:09 +00002659 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002660
Benjamin Petersone41251e2008-04-25 01:59:09 +00002661 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2662 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002663
2664
Benjamin Petersone41251e2008-04-25 01:59:09 +00002665 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002666
Benjamin Petersone41251e2008-04-25 01:59:09 +00002667 You can override this to implement custom flushing behavior. This version
2668 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002669
2670
Benjamin Petersone41251e2008-04-25 01:59:09 +00002671 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002672
Benjamin Petersone41251e2008-04-25 01:59:09 +00002673 Returns true if the buffer is up to capacity. This method can be
2674 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002675
2676
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002677.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002678
2679 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2680 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2681 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2682 set using :meth:`setTarget` before this handler does anything useful.
2683
2684
Benjamin Petersone41251e2008-04-25 01:59:09 +00002685 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002686
Benjamin Petersone41251e2008-04-25 01:59:09 +00002687 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2688 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002689
2690
Benjamin Petersone41251e2008-04-25 01:59:09 +00002691 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002692
Benjamin Petersone41251e2008-04-25 01:59:09 +00002693 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00002694 records to the target, if there is one. The buffer is also cleared when
2695 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002696
2697
Benjamin Petersone41251e2008-04-25 01:59:09 +00002698 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002699
Benjamin Petersone41251e2008-04-25 01:59:09 +00002700 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002701
2702
Benjamin Petersone41251e2008-04-25 01:59:09 +00002703 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002704
Benjamin Petersone41251e2008-04-25 01:59:09 +00002705 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002706
2707
Vinay Sajipd31f3632010-06-29 15:31:15 +00002708.. _http-handler:
2709
Georg Brandl116aa622007-08-15 14:28:22 +00002710HTTPHandler
2711^^^^^^^^^^^
2712
2713The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2714supports sending logging messages to a Web server, using either ``GET`` or
2715``POST`` semantics.
2716
2717
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002718.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002719
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002720 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
2721 of the form ``host:port``, should you need to use a specific port number.
2722 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
2723 connection will be used. If *credentials* is specified, it should be a
2724 2-tuple consisting of userid and password, which will be placed in an HTTP
2725 'Authorization' header using Basic authentication. If you specify
2726 credentials, you should also specify secure=True so that your userid and
2727 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00002728
2729
Benjamin Petersone41251e2008-04-25 01:59:09 +00002730 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002731
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002732 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002733
2734
Vinay Sajip121a1c42010-09-08 10:46:15 +00002735.. _queue-handler:
2736
2737
2738QueueHandler
2739^^^^^^^^^^^^
2740
2741The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
2742supports sending logging messages to a queue, such as those implemented in the
2743:mod:`queue` or :mod:`multiprocessing` modules.
2744
Vinay Sajip0637d492010-09-23 08:15:54 +00002745Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
2746to let handlers do their work on a separate thread from the one which does the
2747logging. This is important in Web applications and also other service
2748applications where threads servicing clients need to respond as quickly as
2749possible, while any potentially slow operations (such as sending an email via
2750:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002751
2752.. class:: QueueHandler(queue)
2753
2754 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00002755 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00002756 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00002757 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002758
2759
2760 .. method:: emit(record)
2761
Vinay Sajip0258ce82010-09-22 20:34:53 +00002762 Enqueues the result of preparing the LogRecord.
2763
2764 .. method:: prepare(record)
2765
2766 Prepares a record for queuing. The object returned by this
2767 method is enqueued.
2768
2769 The base implementation formats the record to merge the message
2770 and arguments, and removes unpickleable items from the record
2771 in-place.
2772
2773 You might want to override this method if you want to convert
2774 the record to a dict or JSON string, or send a modified copy
2775 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002776
2777 .. method:: enqueue(record)
2778
2779 Enqueues the record on the queue using ``put_nowait()``; you may
2780 want to override this if you want to use blocking behaviour, or a
2781 timeout, or a customised queue implementation.
2782
2783
2784.. versionadded:: 3.2
2785
2786The :class:`QueueHandler` class was not present in previous versions.
2787
Vinay Sajip0637d492010-09-23 08:15:54 +00002788.. queue-listener:
2789
2790QueueListener
2791^^^^^^^^^^^^^
2792
2793The :class:`QueueListener` class, located in the :mod:`logging.handlers`
2794module, supports receiving logging messages from a queue, such as those
2795implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
2796messages are received from a queue in an internal thread and passed, on
2797the same thread, to one or more handlers for processing.
2798
2799Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
2800to let handlers do their work on a separate thread from the one which does the
2801logging. This is important in Web applications and also other service
2802applications where threads servicing clients need to respond as quickly as
2803possible, while any potentially slow operations (such as sending an email via
2804:class:`SMTPHandler`) are done on a separate thread.
2805
2806.. class:: QueueListener(queue, *handlers)
2807
2808 Returns a new instance of the :class:`QueueListener` class. The instance is
2809 initialized with the queue to send messages to and a list of handlers which
2810 will handle entries placed on the queue. The queue can be any queue-
2811 like object; it's passed as-is to the :meth:`dequeue` method, which needs
2812 to know how to get messages from it.
2813
2814 .. method:: dequeue(block)
2815
2816 Dequeues a record and return it, optionally blocking.
2817
2818 The base implementation uses ``get()``. You may want to override this
2819 method if you want to use timeouts or work with custom queue
2820 implementations.
2821
2822 .. method:: prepare(record)
2823
2824 Prepare a record for handling.
2825
2826 This implementation just returns the passed-in record. You may want to
2827 override this method if you need to do any custom marshalling or
2828 manipulation of the record before passing it to the handlers.
2829
2830 .. method:: handle(record)
2831
2832 Handle a record.
2833
2834 This just loops through the handlers offering them the record
2835 to handle. The actual object passed to the handlers is that which
2836 is returned from :meth:`prepare`.
2837
2838 .. method:: start()
2839
2840 Starts the listener.
2841
2842 This starts up a background thread to monitor the queue for
2843 LogRecords to process.
2844
2845 .. method:: stop()
2846
2847 Stops the listener.
2848
2849 This asks the thread to terminate, and then waits for it to do so.
2850 Note that if you don't call this before your application exits, there
2851 may be some records still left on the queue, which won't be processed.
2852
2853.. versionadded:: 3.2
2854
2855The :class:`QueueListener` class was not present in previous versions.
2856
Vinay Sajip63891ed2010-09-13 20:02:39 +00002857.. _zeromq-handlers:
2858
Vinay Sajip0637d492010-09-23 08:15:54 +00002859Subclassing QueueHandler
2860^^^^^^^^^^^^^^^^^^^^^^^^
2861
Vinay Sajip63891ed2010-09-13 20:02:39 +00002862You can use a :class:`QueueHandler` subclass to send messages to other kinds
2863of queues, for example a ZeroMQ "publish" socket. In the example below,the
2864socket is created separately and passed to the handler (as its 'queue')::
2865
2866 import zmq # using pyzmq, the Python binding for ZeroMQ
2867 import json # for serializing records portably
2868
2869 ctx = zmq.Context()
2870 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
2871 sock.bind('tcp://*:5556') # or wherever
2872
2873 class ZeroMQSocketHandler(QueueHandler):
2874 def enqueue(self, record):
2875 data = json.dumps(record.__dict__)
2876 self.queue.send(data)
2877
Vinay Sajip0055c422010-09-14 09:42:39 +00002878 handler = ZeroMQSocketHandler(sock)
2879
2880
Vinay Sajip63891ed2010-09-13 20:02:39 +00002881Of course there are other ways of organizing this, for example passing in the
2882data needed by the handler to create the socket::
2883
2884 class ZeroMQSocketHandler(QueueHandler):
2885 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
2886 self.ctx = ctx or zmq.Context()
2887 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00002888 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00002889 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00002890
2891 def enqueue(self, record):
2892 data = json.dumps(record.__dict__)
2893 self.queue.send(data)
2894
Vinay Sajipde726922010-09-14 06:59:24 +00002895 def close(self):
2896 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00002897
Vinay Sajip0637d492010-09-23 08:15:54 +00002898Subclassing QueueListener
2899^^^^^^^^^^^^^^^^^^^^^^^^^
2900
2901You can also subclass :class:`QueueListener` to get messages from other kinds
2902of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
2903
2904 class ZeroMQSocketListener(QueueListener):
2905 def __init__(self, uri, *handlers, **kwargs):
2906 self.ctx = kwargs.get('ctx') or zmq.Context()
2907 socket = zmq.Socket(self.ctx, zmq.SUB)
2908 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
2909 socket.connect(uri)
2910
2911 def dequeue(self):
2912 msg = self.queue.recv()
2913 return logging.makeLogRecord(json.loads(msg))
2914
Christian Heimes8b0facf2007-12-04 19:30:01 +00002915.. _formatter-objects:
2916
Georg Brandl116aa622007-08-15 14:28:22 +00002917Formatter Objects
2918-----------------
2919
Benjamin Peterson75edad02009-01-01 15:05:06 +00002920.. currentmodule:: logging
2921
Georg Brandl116aa622007-08-15 14:28:22 +00002922:class:`Formatter`\ s have the following attributes and methods. They are
2923responsible for converting a :class:`LogRecord` to (usually) a string which can
2924be interpreted by either a human or an external system. The base
2925:class:`Formatter` allows a formatting string to be specified. If none is
2926supplied, the default value of ``'%(message)s'`` is used.
2927
2928A Formatter can be initialized with a format string which makes use of knowledge
2929of the :class:`LogRecord` attributes - such as the default value mentioned above
2930making use of the fact that the user's message and arguments are pre-formatted
2931into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002932standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00002933for more information on string formatting.
2934
2935Currently, the useful mapping keys in a :class:`LogRecord` are:
2936
2937+-------------------------+-----------------------------------------------+
2938| Format | Description |
2939+=========================+===============================================+
2940| ``%(name)s`` | Name of the logger (logging channel). |
2941+-------------------------+-----------------------------------------------+
2942| ``%(levelno)s`` | Numeric logging level for the message |
2943| | (:const:`DEBUG`, :const:`INFO`, |
2944| | :const:`WARNING`, :const:`ERROR`, |
2945| | :const:`CRITICAL`). |
2946+-------------------------+-----------------------------------------------+
2947| ``%(levelname)s`` | Text logging level for the message |
2948| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2949| | ``'ERROR'``, ``'CRITICAL'``). |
2950+-------------------------+-----------------------------------------------+
2951| ``%(pathname)s`` | Full pathname of the source file where the |
2952| | logging call was issued (if available). |
2953+-------------------------+-----------------------------------------------+
2954| ``%(filename)s`` | Filename portion of pathname. |
2955+-------------------------+-----------------------------------------------+
2956| ``%(module)s`` | Module (name portion of filename). |
2957+-------------------------+-----------------------------------------------+
2958| ``%(funcName)s`` | Name of function containing the logging call. |
2959+-------------------------+-----------------------------------------------+
2960| ``%(lineno)d`` | Source line number where the logging call was |
2961| | issued (if available). |
2962+-------------------------+-----------------------------------------------+
2963| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2964| | (as returned by :func:`time.time`). |
2965+-------------------------+-----------------------------------------------+
2966| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2967| | created, relative to the time the logging |
2968| | module was loaded. |
2969+-------------------------+-----------------------------------------------+
2970| ``%(asctime)s`` | Human-readable time when the |
2971| | :class:`LogRecord` was created. By default |
2972| | this is of the form "2003-07-08 16:49:45,896" |
2973| | (the numbers after the comma are millisecond |
2974| | portion of the time). |
2975+-------------------------+-----------------------------------------------+
2976| ``%(msecs)d`` | Millisecond portion of the time when the |
2977| | :class:`LogRecord` was created. |
2978+-------------------------+-----------------------------------------------+
2979| ``%(thread)d`` | Thread ID (if available). |
2980+-------------------------+-----------------------------------------------+
2981| ``%(threadName)s`` | Thread name (if available). |
2982+-------------------------+-----------------------------------------------+
2983| ``%(process)d`` | Process ID (if available). |
2984+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00002985| ``%(processName)s`` | Process name (if available). |
2986+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002987| ``%(message)s`` | The logged message, computed as ``msg % |
2988| | args``. |
2989+-------------------------+-----------------------------------------------+
2990
Georg Brandl116aa622007-08-15 14:28:22 +00002991
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002992.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002993
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002994 Returns a new instance of the :class:`Formatter` class. The instance is
2995 initialized with a format string for the message as a whole, as well as a
2996 format string for the date/time portion of a message. If no *fmt* is
2997 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
2998 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00002999
Benjamin Petersone41251e2008-04-25 01:59:09 +00003000 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003001
Benjamin Petersone41251e2008-04-25 01:59:09 +00003002 The record's attribute dictionary is used as the operand to a string
3003 formatting operation. Returns the resulting string. Before formatting the
3004 dictionary, a couple of preparatory steps are carried out. The *message*
3005 attribute of the record is computed using *msg* % *args*. If the
3006 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3007 to format the event time. If there is exception information, it is
3008 formatted using :meth:`formatException` and appended to the message. Note
3009 that the formatted exception information is cached in attribute
3010 *exc_text*. This is useful because the exception information can be
3011 pickled and sent across the wire, but you should be careful if you have
3012 more than one :class:`Formatter` subclass which customizes the formatting
3013 of exception information. In this case, you will have to clear the cached
3014 value after a formatter has done its formatting, so that the next
3015 formatter to handle the event doesn't use the cached value but
3016 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003017
3018
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003019 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003020
Benjamin Petersone41251e2008-04-25 01:59:09 +00003021 This method should be called from :meth:`format` by a formatter which
3022 wants to make use of a formatted time. This method can be overridden in
3023 formatters to provide for any specific requirement, but the basic behavior
3024 is as follows: if *datefmt* (a string) is specified, it is used with
3025 :func:`time.strftime` to format the creation time of the
3026 record. Otherwise, the ISO8601 format is used. The resulting string is
3027 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003028
3029
Benjamin Petersone41251e2008-04-25 01:59:09 +00003030 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003031
Benjamin Petersone41251e2008-04-25 01:59:09 +00003032 Formats the specified exception information (a standard exception tuple as
3033 returned by :func:`sys.exc_info`) as a string. This default implementation
3034 just uses :func:`traceback.print_exception`. The resulting string is
3035 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003036
Vinay Sajipd31f3632010-06-29 15:31:15 +00003037.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003038
3039Filter Objects
3040--------------
3041
3042:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
3043more sophisticated filtering than is provided by levels. The base filter class
3044only allows events which are below a certain point in the logger hierarchy. For
3045example, a filter initialized with "A.B" will allow events logged by loggers
3046"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
3047initialized with the empty string, all events are passed.
3048
3049
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003050.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003051
3052 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3053 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003054 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003055
3056
Benjamin Petersone41251e2008-04-25 01:59:09 +00003057 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003058
Benjamin Petersone41251e2008-04-25 01:59:09 +00003059 Is the specified record to be logged? Returns zero for no, nonzero for
3060 yes. If deemed appropriate, the record may be modified in-place by this
3061 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003062
Vinay Sajip81010212010-08-19 19:17:41 +00003063Note that filters attached to handlers are consulted whenever an event is
3064emitted by the handler, whereas filters attached to loggers are consulted
3065whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3066etc.) This means that events which have been generated by descendant loggers
3067will not be filtered by a logger's filter setting, unless the filter has also
3068been applied to those descendant loggers.
3069
Vinay Sajipac007992010-09-17 12:45:26 +00003070Other uses for filters
3071^^^^^^^^^^^^^^^^^^^^^^
3072
3073Although filters are used primarily to filter records based on more
3074sophisticated criteria than levels, they get to see every record which is
3075processed by the handler or logger they're attached to: this can be useful if
3076you want to do things like counting how many records were processed by a
3077particular logger or handler, or adding, changing or removing attributes in
3078the LogRecord being processed. Obviously changing the LogRecord needs to be
3079done with some care, but it does allow the injection of contextual information
3080into logs (see :ref:`filters-contextual`).
3081
Vinay Sajipd31f3632010-06-29 15:31:15 +00003082.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003083
3084LogRecord Objects
3085-----------------
3086
Vinay Sajip4039aff2010-09-11 10:25:28 +00003087:class:`LogRecord` instances are created automatically by the :class:`Logger`
3088every time something is logged, and can be created manually via
3089:func:`makeLogRecord` (for example, from a pickled event received over the
3090wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003091
3092
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003093.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003094
Vinay Sajip4039aff2010-09-11 10:25:28 +00003095 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003096
Vinay Sajip4039aff2010-09-11 10:25:28 +00003097 The primary information is passed in :attr:`msg` and :attr:`args`, which
3098 are combined using ``msg % args`` to create the :attr:`message` field of the
3099 record.
3100
3101 .. attribute:: args
3102
3103 Tuple of arguments to be used in formatting :attr:`msg`.
3104
3105 .. attribute:: exc_info
3106
3107 Exception tuple (à la `sys.exc_info`) or `None` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003108 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003109
3110 .. attribute:: func
3111
3112 Name of the function of origin (i.e. in which the logging call was made).
3113
3114 .. attribute:: lineno
3115
3116 Line number in the source file of origin.
3117
3118 .. attribute:: lvl
3119
3120 Numeric logging level.
3121
3122 .. attribute:: message
3123
3124 Bound to the result of :meth:`getMessage` when
3125 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3126
3127 .. attribute:: msg
3128
3129 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3130 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3131
3132 .. attribute:: name
3133
3134 Name of the logger that emitted the record.
3135
3136 .. attribute:: pathname
3137
3138 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003139
Benjamin Petersone41251e2008-04-25 01:59:09 +00003140 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003141
Benjamin Petersone41251e2008-04-25 01:59:09 +00003142 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003143 user-supplied arguments with the message. If the user-supplied message
3144 argument to the logging call is not a string, :func:`str` is called on it to
3145 convert it to a string. This allows use of user-defined classes as
3146 messages, whose ``__str__`` method can return the actual format string to
3147 be used.
3148
3149 .. versionchanged:: 2.5
3150 *func* was added.
Benjamin Petersone41251e2008-04-25 01:59:09 +00003151
Vinay Sajipd31f3632010-06-29 15:31:15 +00003152.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003153
Christian Heimes04c420f2008-01-18 18:40:46 +00003154LoggerAdapter Objects
3155---------------------
3156
Christian Heimes04c420f2008-01-18 18:40:46 +00003157:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003158information into logging calls. For a usage example , see the section on
3159`adding contextual information to your logging output`__.
3160
3161__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00003162
3163.. class:: LoggerAdapter(logger, extra)
3164
3165 Returns an instance of :class:`LoggerAdapter` initialized with an
3166 underlying :class:`Logger` instance and a dict-like object.
3167
Benjamin Petersone41251e2008-04-25 01:59:09 +00003168 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003169
Benjamin Petersone41251e2008-04-25 01:59:09 +00003170 Modifies the message and/or keyword arguments passed to a logging call in
3171 order to insert contextual information. This implementation takes the object
3172 passed as *extra* to the constructor and adds it to *kwargs* using key
3173 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3174 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003175
Vinay Sajipc84f0162010-09-21 11:25:39 +00003176In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003177methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003178:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3179:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3180:meth:`hasHandlers`. These methods have the same signatures as their
3181counterparts in :class:`Logger`, so you can use the two types of instances
3182interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003183
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003184.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003185 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3186 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3187 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003188
Georg Brandl116aa622007-08-15 14:28:22 +00003189
3190Thread Safety
3191-------------
3192
3193The logging module is intended to be thread-safe without any special work
3194needing to be done by its clients. It achieves this though using threading
3195locks; there is one lock to serialize access to the module's shared data, and
3196each handler also creates a lock to serialize access to its underlying I/O.
3197
Benjamin Petersond23f8222009-04-05 19:13:16 +00003198If you are implementing asynchronous signal handlers using the :mod:`signal`
3199module, you may not be able to use logging from within such handlers. This is
3200because lock implementations in the :mod:`threading` module are not always
3201re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003202
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003203
3204Integration with the warnings module
3205------------------------------------
3206
3207The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3208with the :mod:`warnings` module.
3209
3210.. function:: captureWarnings(capture)
3211
3212 This function is used to turn the capture of warnings by logging on and
3213 off.
3214
3215 If `capture` is `True`, warnings issued by the :mod:`warnings` module
3216 will be redirected to the logging system. Specifically, a warning will be
3217 formatted using :func:`warnings.formatwarning` and the resulting string
3218 logged to a logger named "py.warnings" with a severity of `WARNING`.
3219
3220 If `capture` is `False`, the redirection of warnings to the logging system
3221 will stop, and warnings will be redirected to their original destinations
3222 (i.e. those in effect before `captureWarnings(True)` was called).
3223
3224
Georg Brandl116aa622007-08-15 14:28:22 +00003225Configuration
3226-------------
3227
3228
3229.. _logging-config-api:
3230
3231Configuration functions
3232^^^^^^^^^^^^^^^^^^^^^^^
3233
Georg Brandl116aa622007-08-15 14:28:22 +00003234The following functions configure the logging module. They are located in the
3235:mod:`logging.config` module. Their use is optional --- you can configure the
3236logging module using these functions or by making calls to the main API (defined
3237in :mod:`logging` itself) and defining handlers which are declared either in
3238:mod:`logging` or :mod:`logging.handlers`.
3239
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003240.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003241
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003242 Takes the logging configuration from a dictionary. The contents of
3243 this dictionary are described in :ref:`logging-config-dictschema`
3244 below.
3245
3246 If an error is encountered during configuration, this function will
3247 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3248 or :exc:`ImportError` with a suitably descriptive message. The
3249 following is a (possibly incomplete) list of conditions which will
3250 raise an error:
3251
3252 * A ``level`` which is not a string or which is a string not
3253 corresponding to an actual logging level.
3254 * A ``propagate`` value which is not a boolean.
3255 * An id which does not have a corresponding destination.
3256 * A non-existent handler id found during an incremental call.
3257 * An invalid logger name.
3258 * Inability to resolve to an internal or external object.
3259
3260 Parsing is performed by the :class:`DictConfigurator` class, whose
3261 constructor is passed the dictionary used for configuration, and
3262 has a :meth:`configure` method. The :mod:`logging.config` module
3263 has a callable attribute :attr:`dictConfigClass`
3264 which is initially set to :class:`DictConfigurator`.
3265 You can replace the value of :attr:`dictConfigClass` with a
3266 suitable implementation of your own.
3267
3268 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3269 the specified dictionary, and then calls the :meth:`configure` method on
3270 the returned object to put the configuration into effect::
3271
3272 def dictConfig(config):
3273 dictConfigClass(config).configure()
3274
3275 For example, a subclass of :class:`DictConfigurator` could call
3276 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3277 set up custom prefixes which would be usable in the subsequent
3278 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3279 this new subclass, and then :func:`dictConfig` could be called exactly as
3280 in the default, uncustomized state.
3281
3282.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003283
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003284 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003285 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003286 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003287 configurations (if the developer provides a mechanism to present the choices
3288 and load the chosen configuration). Defaults to be passed to the ConfigParser
3289 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003290
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003291
3292.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003293
3294 Starts up a socket server on the specified port, and listens for new
3295 configurations. If no port is specified, the module's default
3296 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3297 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3298 :class:`Thread` instance on which you can call :meth:`start` to start the
3299 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003300 call :func:`stopListening`.
3301
3302 To send a configuration to the socket, read in the configuration file and
3303 send it to the socket as a string of bytes preceded by a four-byte length
3304 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003305
3306
3307.. function:: stopListening()
3308
Christian Heimes8b0facf2007-12-04 19:30:01 +00003309 Stops the listening server which was created with a call to :func:`listen`.
3310 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003311 :func:`listen`.
3312
3313
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003314.. _logging-config-dictschema:
3315
3316Configuration dictionary schema
3317^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3318
3319Describing a logging configuration requires listing the various
3320objects to create and the connections between them; for example, you
3321may create a handler named "console" and then say that the logger
3322named "startup" will send its messages to the "console" handler.
3323These objects aren't limited to those provided by the :mod:`logging`
3324module because you might write your own formatter or handler class.
3325The parameters to these classes may also need to include external
3326objects such as ``sys.stderr``. The syntax for describing these
3327objects and connections is defined in :ref:`logging-config-dict-connections`
3328below.
3329
3330Dictionary Schema Details
3331"""""""""""""""""""""""""
3332
3333The dictionary passed to :func:`dictConfig` must contain the following
3334keys:
3335
3336* `version` - to be set to an integer value representing the schema
3337 version. The only valid value at present is 1, but having this key
3338 allows the schema to evolve while still preserving backwards
3339 compatibility.
3340
3341All other keys are optional, but if present they will be interpreted
3342as described below. In all cases below where a 'configuring dict' is
3343mentioned, it will be checked for the special ``'()'`` key to see if a
3344custom instantiation is required. If so, the mechanism described in
3345:ref:`logging-config-dict-userdef` below is used to create an instance;
3346otherwise, the context is used to determine what to instantiate.
3347
3348* `formatters` - the corresponding value will be a dict in which each
3349 key is a formatter id and each value is a dict describing how to
3350 configure the corresponding Formatter instance.
3351
3352 The configuring dict is searched for keys ``format`` and ``datefmt``
3353 (with defaults of ``None``) and these are used to construct a
3354 :class:`logging.Formatter` instance.
3355
3356* `filters` - the corresponding value will be a dict in which each key
3357 is a filter id and each value is a dict describing how to configure
3358 the corresponding Filter instance.
3359
3360 The configuring dict is searched for the key ``name`` (defaulting to the
3361 empty string) and this is used to construct a :class:`logging.Filter`
3362 instance.
3363
3364* `handlers` - the corresponding value will be a dict in which each
3365 key is a handler id and each value is a dict describing how to
3366 configure the corresponding Handler instance.
3367
3368 The configuring dict is searched for the following keys:
3369
3370 * ``class`` (mandatory). This is the fully qualified name of the
3371 handler class.
3372
3373 * ``level`` (optional). The level of the handler.
3374
3375 * ``formatter`` (optional). The id of the formatter for this
3376 handler.
3377
3378 * ``filters`` (optional). A list of ids of the filters for this
3379 handler.
3380
3381 All *other* keys are passed through as keyword arguments to the
3382 handler's constructor. For example, given the snippet::
3383
3384 handlers:
3385 console:
3386 class : logging.StreamHandler
3387 formatter: brief
3388 level : INFO
3389 filters: [allow_foo]
3390 stream : ext://sys.stdout
3391 file:
3392 class : logging.handlers.RotatingFileHandler
3393 formatter: precise
3394 filename: logconfig.log
3395 maxBytes: 1024
3396 backupCount: 3
3397
3398 the handler with id ``console`` is instantiated as a
3399 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3400 stream. The handler with id ``file`` is instantiated as a
3401 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3402 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3403
3404* `loggers` - the corresponding value will be a dict in which each key
3405 is a logger name and each value is a dict describing how to
3406 configure the corresponding Logger instance.
3407
3408 The configuring dict is searched for the following keys:
3409
3410 * ``level`` (optional). The level of the logger.
3411
3412 * ``propagate`` (optional). The propagation setting of the logger.
3413
3414 * ``filters`` (optional). A list of ids of the filters for this
3415 logger.
3416
3417 * ``handlers`` (optional). A list of ids of the handlers for this
3418 logger.
3419
3420 The specified loggers will be configured according to the level,
3421 propagation, filters and handlers specified.
3422
3423* `root` - this will be the configuration for the root logger.
3424 Processing of the configuration will be as for any logger, except
3425 that the ``propagate`` setting will not be applicable.
3426
3427* `incremental` - whether the configuration is to be interpreted as
3428 incremental to the existing configuration. This value defaults to
3429 ``False``, which means that the specified configuration replaces the
3430 existing configuration with the same semantics as used by the
3431 existing :func:`fileConfig` API.
3432
3433 If the specified value is ``True``, the configuration is processed
3434 as described in the section on :ref:`logging-config-dict-incremental`.
3435
3436* `disable_existing_loggers` - whether any existing loggers are to be
3437 disabled. This setting mirrors the parameter of the same name in
3438 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
3439 This value is ignored if `incremental` is ``True``.
3440
3441.. _logging-config-dict-incremental:
3442
3443Incremental Configuration
3444"""""""""""""""""""""""""
3445
3446It is difficult to provide complete flexibility for incremental
3447configuration. For example, because objects such as filters
3448and formatters are anonymous, once a configuration is set up, it is
3449not possible to refer to such anonymous objects when augmenting a
3450configuration.
3451
3452Furthermore, there is not a compelling case for arbitrarily altering
3453the object graph of loggers, handlers, filters, formatters at
3454run-time, once a configuration is set up; the verbosity of loggers and
3455handlers can be controlled just by setting levels (and, in the case of
3456loggers, propagation flags). Changing the object graph arbitrarily in
3457a safe way is problematic in a multi-threaded environment; while not
3458impossible, the benefits are not worth the complexity it adds to the
3459implementation.
3460
3461Thus, when the ``incremental`` key of a configuration dict is present
3462and is ``True``, the system will completely ignore any ``formatters`` and
3463``filters`` entries, and process only the ``level``
3464settings in the ``handlers`` entries, and the ``level`` and
3465``propagate`` settings in the ``loggers`` and ``root`` entries.
3466
3467Using a value in the configuration dict lets configurations to be sent
3468over the wire as pickled dicts to a socket listener. Thus, the logging
3469verbosity of a long-running application can be altered over time with
3470no need to stop and restart the application.
3471
3472.. _logging-config-dict-connections:
3473
3474Object connections
3475""""""""""""""""""
3476
3477The schema describes a set of logging objects - loggers,
3478handlers, formatters, filters - which are connected to each other in
3479an object graph. Thus, the schema needs to represent connections
3480between the objects. For example, say that, once configured, a
3481particular logger has attached to it a particular handler. For the
3482purposes of this discussion, we can say that the logger represents the
3483source, and the handler the destination, of a connection between the
3484two. Of course in the configured objects this is represented by the
3485logger holding a reference to the handler. In the configuration dict,
3486this is done by giving each destination object an id which identifies
3487it unambiguously, and then using the id in the source object's
3488configuration to indicate that a connection exists between the source
3489and the destination object with that id.
3490
3491So, for example, consider the following YAML snippet::
3492
3493 formatters:
3494 brief:
3495 # configuration for formatter with id 'brief' goes here
3496 precise:
3497 # configuration for formatter with id 'precise' goes here
3498 handlers:
3499 h1: #This is an id
3500 # configuration of handler with id 'h1' goes here
3501 formatter: brief
3502 h2: #This is another id
3503 # configuration of handler with id 'h2' goes here
3504 formatter: precise
3505 loggers:
3506 foo.bar.baz:
3507 # other configuration for logger 'foo.bar.baz'
3508 handlers: [h1, h2]
3509
3510(Note: YAML used here because it's a little more readable than the
3511equivalent Python source form for the dictionary.)
3512
3513The ids for loggers are the logger names which would be used
3514programmatically to obtain a reference to those loggers, e.g.
3515``foo.bar.baz``. The ids for Formatters and Filters can be any string
3516value (such as ``brief``, ``precise`` above) and they are transient,
3517in that they are only meaningful for processing the configuration
3518dictionary and used to determine connections between objects, and are
3519not persisted anywhere when the configuration call is complete.
3520
3521The above snippet indicates that logger named ``foo.bar.baz`` should
3522have two handlers attached to it, which are described by the handler
3523ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3524``brief``, and the formatter for ``h2`` is that described by id
3525``precise``.
3526
3527
3528.. _logging-config-dict-userdef:
3529
3530User-defined objects
3531""""""""""""""""""""
3532
3533The schema supports user-defined objects for handlers, filters and
3534formatters. (Loggers do not need to have different types for
3535different instances, so there is no support in this configuration
3536schema for user-defined logger classes.)
3537
3538Objects to be configured are described by dictionaries
3539which detail their configuration. In some places, the logging system
3540will be able to infer from the context how an object is to be
3541instantiated, but when a user-defined object is to be instantiated,
3542the system will not know how to do this. In order to provide complete
3543flexibility for user-defined object instantiation, the user needs
3544to provide a 'factory' - a callable which is called with a
3545configuration dictionary and which returns the instantiated object.
3546This is signalled by an absolute import path to the factory being
3547made available under the special key ``'()'``. Here's a concrete
3548example::
3549
3550 formatters:
3551 brief:
3552 format: '%(message)s'
3553 default:
3554 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3555 datefmt: '%Y-%m-%d %H:%M:%S'
3556 custom:
3557 (): my.package.customFormatterFactory
3558 bar: baz
3559 spam: 99.9
3560 answer: 42
3561
3562The above YAML snippet defines three formatters. The first, with id
3563``brief``, is a standard :class:`logging.Formatter` instance with the
3564specified format string. The second, with id ``default``, has a
3565longer format and also defines the time format explicitly, and will
3566result in a :class:`logging.Formatter` initialized with those two format
3567strings. Shown in Python source form, the ``brief`` and ``default``
3568formatters have configuration sub-dictionaries::
3569
3570 {
3571 'format' : '%(message)s'
3572 }
3573
3574and::
3575
3576 {
3577 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3578 'datefmt' : '%Y-%m-%d %H:%M:%S'
3579 }
3580
3581respectively, and as these dictionaries do not contain the special key
3582``'()'``, the instantiation is inferred from the context: as a result,
3583standard :class:`logging.Formatter` instances are created. The
3584configuration sub-dictionary for the third formatter, with id
3585``custom``, is::
3586
3587 {
3588 '()' : 'my.package.customFormatterFactory',
3589 'bar' : 'baz',
3590 'spam' : 99.9,
3591 'answer' : 42
3592 }
3593
3594and this contains the special key ``'()'``, which means that
3595user-defined instantiation is wanted. In this case, the specified
3596factory callable will be used. If it is an actual callable it will be
3597used directly - otherwise, if you specify a string (as in the example)
3598the actual callable will be located using normal import mechanisms.
3599The callable will be called with the **remaining** items in the
3600configuration sub-dictionary as keyword arguments. In the above
3601example, the formatter with id ``custom`` will be assumed to be
3602returned by the call::
3603
3604 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3605
3606The key ``'()'`` has been used as the special key because it is not a
3607valid keyword parameter name, and so will not clash with the names of
3608the keyword arguments used in the call. The ``'()'`` also serves as a
3609mnemonic that the corresponding value is a callable.
3610
3611
3612.. _logging-config-dict-externalobj:
3613
3614Access to external objects
3615""""""""""""""""""""""""""
3616
3617There are times where a configuration needs to refer to objects
3618external to the configuration, for example ``sys.stderr``. If the
3619configuration dict is constructed using Python code, this is
3620straightforward, but a problem arises when the configuration is
3621provided via a text file (e.g. JSON, YAML). In a text file, there is
3622no standard way to distinguish ``sys.stderr`` from the literal string
3623``'sys.stderr'``. To facilitate this distinction, the configuration
3624system looks for certain special prefixes in string values and
3625treat them specially. For example, if the literal string
3626``'ext://sys.stderr'`` is provided as a value in the configuration,
3627then the ``ext://`` will be stripped off and the remainder of the
3628value processed using normal import mechanisms.
3629
3630The handling of such prefixes is done in a way analogous to protocol
3631handling: there is a generic mechanism to look for prefixes which
3632match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3633whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3634in a prefix-dependent manner and the result of the processing replaces
3635the string value. If the prefix is not recognised, then the string
3636value will be left as-is.
3637
3638
3639.. _logging-config-dict-internalobj:
3640
3641Access to internal objects
3642""""""""""""""""""""""""""
3643
3644As well as external objects, there is sometimes also a need to refer
3645to objects in the configuration. This will be done implicitly by the
3646configuration system for things that it knows about. For example, the
3647string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3648automatically be converted to the value ``logging.DEBUG``, and the
3649``handlers``, ``filters`` and ``formatter`` entries will take an
3650object id and resolve to the appropriate destination object.
3651
3652However, a more generic mechanism is needed for user-defined
3653objects which are not known to the :mod:`logging` module. For
3654example, consider :class:`logging.handlers.MemoryHandler`, which takes
3655a ``target`` argument which is another handler to delegate to. Since
3656the system already knows about this class, then in the configuration,
3657the given ``target`` just needs to be the object id of the relevant
3658target handler, and the system will resolve to the handler from the
3659id. If, however, a user defines a ``my.package.MyHandler`` which has
3660an ``alternate`` handler, the configuration system would not know that
3661the ``alternate`` referred to a handler. To cater for this, a generic
3662resolution system allows the user to specify::
3663
3664 handlers:
3665 file:
3666 # configuration of file handler goes here
3667
3668 custom:
3669 (): my.package.MyHandler
3670 alternate: cfg://handlers.file
3671
3672The literal string ``'cfg://handlers.file'`` will be resolved in an
3673analogous way to strings with the ``ext://`` prefix, but looking
3674in the configuration itself rather than the import namespace. The
3675mechanism allows access by dot or by index, in a similar way to
3676that provided by ``str.format``. Thus, given the following snippet::
3677
3678 handlers:
3679 email:
3680 class: logging.handlers.SMTPHandler
3681 mailhost: localhost
3682 fromaddr: my_app@domain.tld
3683 toaddrs:
3684 - support_team@domain.tld
3685 - dev_team@domain.tld
3686 subject: Houston, we have a problem.
3687
3688in the configuration, the string ``'cfg://handlers'`` would resolve to
3689the dict with key ``handlers``, the string ``'cfg://handlers.email``
3690would resolve to the dict with key ``email`` in the ``handlers`` dict,
3691and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3692resolve to ``'dev_team.domain.tld'`` and the string
3693``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3694``'support_team@domain.tld'``. The ``subject`` value could be accessed
3695using either ``'cfg://handlers.email.subject'`` or, equivalently,
3696``'cfg://handlers.email[subject]'``. The latter form only needs to be
3697used if the key contains spaces or non-alphanumeric characters. If an
3698index value consists only of decimal digits, access will be attempted
3699using the corresponding integer value, falling back to the string
3700value if needed.
3701
3702Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3703resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3704If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3705the system will attempt to retrieve the value from
3706``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3707to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3708fails.
3709
Georg Brandl116aa622007-08-15 14:28:22 +00003710.. _logging-config-fileformat:
3711
3712Configuration file format
3713^^^^^^^^^^^^^^^^^^^^^^^^^
3714
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003715The configuration file format understood by :func:`fileConfig` is based on
3716:mod:`configparser` functionality. The file must contain sections called
3717``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3718entities of each type which are defined in the file. For each such entity, there
3719is a separate section which identifies how that entity is configured. Thus, for
3720a logger named ``log01`` in the ``[loggers]`` section, the relevant
3721configuration details are held in a section ``[logger_log01]``. Similarly, a
3722handler called ``hand01`` in the ``[handlers]`` section will have its
3723configuration held in a section called ``[handler_hand01]``, while a formatter
3724called ``form01`` in the ``[formatters]`` section will have its configuration
3725specified in a section called ``[formatter_form01]``. The root logger
3726configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003727
3728Examples of these sections in the file are given below. ::
3729
3730 [loggers]
3731 keys=root,log02,log03,log04,log05,log06,log07
3732
3733 [handlers]
3734 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3735
3736 [formatters]
3737 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3738
3739The root logger must specify a level and a list of handlers. An example of a
3740root logger section is given below. ::
3741
3742 [logger_root]
3743 level=NOTSET
3744 handlers=hand01
3745
3746The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3747``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3748logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3749package's namespace.
3750
3751The ``handlers`` entry is a comma-separated list of handler names, which must
3752appear in the ``[handlers]`` section. These names must appear in the
3753``[handlers]`` section and have corresponding sections in the configuration
3754file.
3755
3756For loggers other than the root logger, some additional information is required.
3757This is illustrated by the following example. ::
3758
3759 [logger_parser]
3760 level=DEBUG
3761 handlers=hand01
3762 propagate=1
3763 qualname=compiler.parser
3764
3765The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3766except that if a non-root logger's level is specified as ``NOTSET``, the system
3767consults loggers higher up the hierarchy to determine the effective level of the
3768logger. The ``propagate`` entry is set to 1 to indicate that messages must
3769propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3770indicate that messages are **not** propagated to handlers up the hierarchy. The
3771``qualname`` entry is the hierarchical channel name of the logger, that is to
3772say the name used by the application to get the logger.
3773
3774Sections which specify handler configuration are exemplified by the following.
3775::
3776
3777 [handler_hand01]
3778 class=StreamHandler
3779 level=NOTSET
3780 formatter=form01
3781 args=(sys.stdout,)
3782
3783The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3784in the ``logging`` package's namespace). The ``level`` is interpreted as for
3785loggers, and ``NOTSET`` is taken to mean "log everything".
3786
3787The ``formatter`` entry indicates the key name of the formatter for this
3788handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3789If a name is specified, it must appear in the ``[formatters]`` section and have
3790a corresponding section in the configuration file.
3791
3792The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3793package's namespace, is the list of arguments to the constructor for the handler
3794class. Refer to the constructors for the relevant handlers, or to the examples
3795below, to see how typical entries are constructed. ::
3796
3797 [handler_hand02]
3798 class=FileHandler
3799 level=DEBUG
3800 formatter=form02
3801 args=('python.log', 'w')
3802
3803 [handler_hand03]
3804 class=handlers.SocketHandler
3805 level=INFO
3806 formatter=form03
3807 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3808
3809 [handler_hand04]
3810 class=handlers.DatagramHandler
3811 level=WARN
3812 formatter=form04
3813 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3814
3815 [handler_hand05]
3816 class=handlers.SysLogHandler
3817 level=ERROR
3818 formatter=form05
3819 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3820
3821 [handler_hand06]
3822 class=handlers.NTEventLogHandler
3823 level=CRITICAL
3824 formatter=form06
3825 args=('Python Application', '', 'Application')
3826
3827 [handler_hand07]
3828 class=handlers.SMTPHandler
3829 level=WARN
3830 formatter=form07
3831 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3832
3833 [handler_hand08]
3834 class=handlers.MemoryHandler
3835 level=NOTSET
3836 formatter=form08
3837 target=
3838 args=(10, ERROR)
3839
3840 [handler_hand09]
3841 class=handlers.HTTPHandler
3842 level=NOTSET
3843 formatter=form09
3844 args=('localhost:9022', '/log', 'GET')
3845
3846Sections which specify formatter configuration are typified by the following. ::
3847
3848 [formatter_form01]
3849 format=F1 %(asctime)s %(levelname)s %(message)s
3850 datefmt=
3851 class=logging.Formatter
3852
3853The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003854the :func:`strftime`\ -compatible date/time format string. If empty, the
3855package substitutes ISO8601 format date/times, which is almost equivalent to
3856specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3857also specifies milliseconds, which are appended to the result of using the above
3858format string, with a comma separator. An example time in ISO8601 format is
3859``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00003860
3861The ``class`` entry is optional. It indicates the name of the formatter's class
3862(as a dotted module and class name.) This option is useful for instantiating a
3863:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3864exception tracebacks in an expanded or condensed format.
3865
Christian Heimes8b0facf2007-12-04 19:30:01 +00003866
3867Configuration server example
3868^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3869
3870Here is an example of a module using the logging configuration server::
3871
3872 import logging
3873 import logging.config
3874 import time
3875 import os
3876
3877 # read initial config file
3878 logging.config.fileConfig("logging.conf")
3879
3880 # create and start listener on port 9999
3881 t = logging.config.listen(9999)
3882 t.start()
3883
3884 logger = logging.getLogger("simpleExample")
3885
3886 try:
3887 # loop through logging calls to see the difference
3888 # new configurations make, until Ctrl+C is pressed
3889 while True:
3890 logger.debug("debug message")
3891 logger.info("info message")
3892 logger.warn("warn message")
3893 logger.error("error message")
3894 logger.critical("critical message")
3895 time.sleep(5)
3896 except KeyboardInterrupt:
3897 # cleanup
3898 logging.config.stopListening()
3899 t.join()
3900
3901And here is a script that takes a filename and sends that file to the server,
3902properly preceded with the binary-encoded length, as the new logging
3903configuration::
3904
3905 #!/usr/bin/env python
3906 import socket, sys, struct
3907
3908 data_to_send = open(sys.argv[1], "r").read()
3909
3910 HOST = 'localhost'
3911 PORT = 9999
3912 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00003913 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003914 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00003915 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003916 s.send(struct.pack(">L", len(data_to_send)))
3917 s.send(data_to_send)
3918 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00003919 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003920
3921
3922More examples
3923-------------
3924
3925Multiple handlers and formatters
3926^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3927
3928Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3929or maximum quota for the number of handlers you may add. Sometimes it will be
3930beneficial for an application to log all messages of all severities to a text
3931file while simultaneously logging errors or above to the console. To set this
3932up, simply configure the appropriate handlers. The logging calls in the
3933application code will remain unchanged. Here is a slight modification to the
3934previous simple module-based configuration example::
3935
3936 import logging
3937
3938 logger = logging.getLogger("simple_example")
3939 logger.setLevel(logging.DEBUG)
3940 # create file handler which logs even debug messages
3941 fh = logging.FileHandler("spam.log")
3942 fh.setLevel(logging.DEBUG)
3943 # create console handler with a higher log level
3944 ch = logging.StreamHandler()
3945 ch.setLevel(logging.ERROR)
3946 # create formatter and add it to the handlers
3947 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3948 ch.setFormatter(formatter)
3949 fh.setFormatter(formatter)
3950 # add the handlers to logger
3951 logger.addHandler(ch)
3952 logger.addHandler(fh)
3953
3954 # "application" code
3955 logger.debug("debug message")
3956 logger.info("info message")
3957 logger.warn("warn message")
3958 logger.error("error message")
3959 logger.critical("critical message")
3960
3961Notice that the "application" code does not care about multiple handlers. All
3962that changed was the addition and configuration of a new handler named *fh*.
3963
3964The ability to create new handlers with higher- or lower-severity filters can be
3965very helpful when writing and testing an application. Instead of using many
3966``print`` statements for debugging, use ``logger.debug``: Unlike the print
3967statements, which you will have to delete or comment out later, the logger.debug
3968statements can remain intact in the source code and remain dormant until you
3969need them again. At that time, the only change that needs to happen is to
3970modify the severity level of the logger and/or handler to debug.
3971
3972
3973Using logging in multiple modules
3974^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3975
3976It was mentioned above that multiple calls to
3977``logging.getLogger('someLogger')`` return a reference to the same logger
3978object. This is true not only within the same module, but also across modules
3979as long as it is in the same Python interpreter process. It is true for
3980references to the same object; additionally, application code can define and
3981configure a parent logger in one module and create (but not configure) a child
3982logger in a separate module, and all logger calls to the child will pass up to
3983the parent. Here is a main module::
3984
3985 import logging
3986 import auxiliary_module
3987
3988 # create logger with "spam_application"
3989 logger = logging.getLogger("spam_application")
3990 logger.setLevel(logging.DEBUG)
3991 # create file handler which logs even debug messages
3992 fh = logging.FileHandler("spam.log")
3993 fh.setLevel(logging.DEBUG)
3994 # create console handler with a higher log level
3995 ch = logging.StreamHandler()
3996 ch.setLevel(logging.ERROR)
3997 # create formatter and add it to the handlers
3998 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3999 fh.setFormatter(formatter)
4000 ch.setFormatter(formatter)
4001 # add the handlers to the logger
4002 logger.addHandler(fh)
4003 logger.addHandler(ch)
4004
4005 logger.info("creating an instance of auxiliary_module.Auxiliary")
4006 a = auxiliary_module.Auxiliary()
4007 logger.info("created an instance of auxiliary_module.Auxiliary")
4008 logger.info("calling auxiliary_module.Auxiliary.do_something")
4009 a.do_something()
4010 logger.info("finished auxiliary_module.Auxiliary.do_something")
4011 logger.info("calling auxiliary_module.some_function()")
4012 auxiliary_module.some_function()
4013 logger.info("done with auxiliary_module.some_function()")
4014
4015Here is the auxiliary module::
4016
4017 import logging
4018
4019 # create logger
4020 module_logger = logging.getLogger("spam_application.auxiliary")
4021
4022 class Auxiliary:
4023 def __init__(self):
4024 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4025 self.logger.info("creating an instance of Auxiliary")
4026 def do_something(self):
4027 self.logger.info("doing something")
4028 a = 1 + 1
4029 self.logger.info("done doing something")
4030
4031 def some_function():
4032 module_logger.info("received a call to \"some_function\"")
4033
4034The output looks like this::
4035
Christian Heimes043d6f62008-01-07 17:19:16 +00004036 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004037 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004038 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004039 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004040 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004041 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004042 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004043 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004044 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004045 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004046 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004047 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004048 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004049 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004050 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004051 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004052 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004053 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004054 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004055 done with auxiliary_module.some_function()
4056