blob: 252685c3e98ceb09317d60840e9a7697fbe22bd0 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl8ec7f652007-08-15 14:28:01 +000012.. index:: pair: Errors; logging
13
14.. versionadded:: 2.3
15
16This module defines functions and classes which implement a flexible error
17logging system for applications.
18
19Logging is performed by calling methods on instances of the :class:`Logger`
20class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandla7395032007-10-21 12:15:05 +000021conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl8ec7f652007-08-15 14:28:01 +000022separators. For example, a logger named "scan" is the parent of loggers
23"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
24and indicate the area of an application in which a logged message originates.
25
26Logged messages also have levels of importance associated with them. The default
27levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
28:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
29importance of a logged message by calling an appropriate method of
30:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
31:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
32constrained to use these levels: you can specify your own and use a more general
33:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
34
Georg Brandlc37f2882007-12-04 17:46:27 +000035
36Logging tutorial
37----------------
38
39The key benefit of having the logging API provided by a standard library module
40is that all Python modules can participate in logging, so your application log
41can include messages from third-party modules.
42
43It is, of course, possible to log messages with different verbosity levels or to
44different destinations. Support for writing log messages to files, HTTP
45GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Georg Brandl907a7202008-02-22 12:31:45 +000046mechanisms are all supported by the standard module. You can also create your
Georg Brandlc37f2882007-12-04 17:46:27 +000047own log destination class if you have special requirements not met by any of the
48built-in classes.
49
50Simple examples
51^^^^^^^^^^^^^^^
52
53.. sectionauthor:: Doug Hellmann
54.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
55
56Most applications are probably going to want to log to a file, so let's start
57with that case. Using the :func:`basicConfig` function, we can set up the
58default handler so that debug messages are written to a file::
59
60 import logging
61 LOG_FILENAME = '/tmp/logging_example.out'
Vinay Sajipf778bec2009-09-22 17:23:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Georg Brandlc37f2882007-12-04 17:46:27 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smithe7dbebb2009-06-04 17:58:15 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Georg Brandlc37f2882007-12-04 17:46:27 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
80 LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
81
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
100 print filename
101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
105 /tmp/logging_rotatingfile_example.out
106 /tmp/logging_rotatingfile_example.out.1
107 /tmp/logging_rotatingfile_example.out.2
108 /tmp/logging_rotatingfile_example.out.3
109 /tmp/logging_rotatingfile_example.out.4
110 /tmp/logging_rotatingfile_example.out.5
111
112The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smithe7dbebb2009-06-04 17:58:15 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Georg Brandlc37f2882007-12-04 17:46:27 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipa7d44002009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Georg Brandlc37f2882007-12-04 17:46:27 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Brett Cannon499969a2008-02-25 05:33:07 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajip497256b2010-04-07 09:40:52 +0000249if it is provided, or ``root`` if not. The names are period-separated
Georg Brandlc37f2882007-12-04 17:46:27 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Georg Brandlc37f2882007-12-04 17:46:27 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Georg Brandl907a7202008-02-22 12:31:45 +0000270requires three individual handlers where each handler is responsible for sending
Georg Brandlc37f2882007-12-04 17:46:27 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Georg Brandlc37f2882007-12-04 17:46:27 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
Vinay Sajip497256b2010-04-07 09:40:52 +0000294defines the interface that all handlers should have and establishes some
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000295default behavior that child classes can use (or override).
Georg Brandlc37f2882007-12-04 17:46:27 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Brett Cannon499969a2008-02-25 05:33:07 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Georg Brandlc37f2882007-12-04 17:46:27 +0000303instantiate formatter classes, although you could likely subclass the formatter
304if your application needs special behavior. The constructor takes two optional
305arguments: a message format string and a date format string. If there is no
306message format string, the default is to use the raw message. If there is no
307date format string, the default date format is::
308
309 %Y-%m-%d %H:%M:%S
310
311with the milliseconds tacked on at the end.
312
313The message format string uses ``%(<dictionary key>)s`` styled string
Vinay Sajip4b782332009-01-19 06:49:19 +0000314substitution; the possible keys are documented in :ref:`formatter`.
Georg Brandlc37f2882007-12-04 17:46:27 +0000315
316The following message format string will log the time in a human-readable
317format, the severity of the message, and the contents of the message, in that
318order::
319
320 "%(asctime)s - %(levelname)s - %(message)s"
321
322
323Configuring Logging
324^^^^^^^^^^^^^^^^^^^
325
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000326Programmers can configure logging in three ways:
327
3281. Creating loggers, handlers, and formatters explicitly using Python
329 code that calls the configuration methods listed above.
3302. Creating a logging config file and reading it using the :func:`fileConfig`
331 function.
3323. Creating a dictionary of configuration information and passing it
333 to the :func:`dictConfig` function.
334
335The following example configures a very simple logger, a console
336handler, and a simple formatter using Python code:
Georg Brandlc37f2882007-12-04 17:46:27 +0000337
338 import logging
339
340 # create logger
341 logger = logging.getLogger("simple_example")
342 logger.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000343
Georg Brandlc37f2882007-12-04 17:46:27 +0000344 # create console handler and set level to debug
345 ch = logging.StreamHandler()
346 ch.setLevel(logging.DEBUG)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000347
Georg Brandlc37f2882007-12-04 17:46:27 +0000348 # create formatter
349 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000350
Georg Brandlc37f2882007-12-04 17:46:27 +0000351 # add formatter to ch
352 ch.setFormatter(formatter)
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +0000353
Georg Brandlc37f2882007-12-04 17:46:27 +0000354 # add ch to logger
355 logger.addHandler(ch)
356
357 # "application" code
358 logger.debug("debug message")
359 logger.info("info message")
360 logger.warn("warn message")
361 logger.error("error message")
362 logger.critical("critical message")
363
364Running this module from the command line produces the following output::
365
366 $ python simple_logging_module.py
367 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
368 2005-03-19 15:10:26,620 - simple_example - INFO - info message
369 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
370 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
371 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
372
373The following Python module creates a logger, handler, and formatter nearly
374identical to those in the example listed above, with the only difference being
375the names of the objects::
376
377 import logging
378 import logging.config
379
380 logging.config.fileConfig("logging.conf")
381
382 # create logger
383 logger = logging.getLogger("simpleExample")
384
385 # "application" code
386 logger.debug("debug message")
387 logger.info("info message")
388 logger.warn("warn message")
389 logger.error("error message")
390 logger.critical("critical message")
391
392Here is the logging.conf file::
393
394 [loggers]
395 keys=root,simpleExample
396
397 [handlers]
398 keys=consoleHandler
399
400 [formatters]
401 keys=simpleFormatter
402
403 [logger_root]
404 level=DEBUG
405 handlers=consoleHandler
406
407 [logger_simpleExample]
408 level=DEBUG
409 handlers=consoleHandler
410 qualname=simpleExample
411 propagate=0
412
413 [handler_consoleHandler]
414 class=StreamHandler
415 level=DEBUG
416 formatter=simpleFormatter
417 args=(sys.stdout,)
418
419 [formatter_simpleFormatter]
420 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
421 datefmt=
422
423The output is nearly identical to that of the non-config-file-based example::
424
425 $ python simple_logging_config.py
426 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
427 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
428 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
429 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
430 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
431
432You can see that the config file approach has a few advantages over the Python
433code approach, mainly separation of configuration and code and the ability of
434noncoders to easily modify the logging properties.
435
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000436Note that the class names referenced in config files need to be either relative
437to the logging module, or absolute values which can be resolved using normal
Georg Brandlf6d367452010-03-12 10:02:03 +0000438import mechanisms. Thus, you could use either :class:`handlers.WatchedFileHandler`
439(relative to the logging module) or :class:`mypackage.mymodule.MyHandler` (for a
440class defined in package :mod:`mypackage` and module :mod:`mymodule`, where
441:mod:`mypackage` is available on the Python import path).
Vinay Sajip0e6e97d2010-02-04 20:23:45 +0000442
Vinay Sajip99505c82009-01-10 13:38:04 +0000443.. _library-config:
444
Vinay Sajip34bfda52008-09-01 15:08:07 +0000445Configuring Logging for a Library
446^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
447
448When developing a library which uses logging, some consideration needs to be
449given to its configuration. If the using application does not use logging, and
450library code makes logging calls, then a one-off message "No handlers could be
451found for logger X.Y.Z" is printed to the console. This message is intended
452to catch mistakes in logging configuration, but will confuse an application
453developer who is not aware of logging by the library.
454
455In addition to documenting how a library uses logging, a good way to configure
456library logging so that it does not cause a spurious message is to add a
457handler which does nothing. This avoids the message being printed, since a
458handler will be found: it just doesn't produce any output. If the library user
459configures logging for application use, presumably that configuration will add
460some handlers, and if levels are suitably configured then logging calls made
461in library code will send output to those handlers, as normal.
462
463A do-nothing handler can be simply defined as follows::
464
465 import logging
466
467 class NullHandler(logging.Handler):
468 def emit(self, record):
469 pass
470
471An instance of this handler should be added to the top-level logger of the
472logging namespace used by the library. If all logging by a library *foo* is
473done using loggers with names matching "foo.x.y", then the code::
474
475 import logging
476
477 h = NullHandler()
478 logging.getLogger("foo").addHandler(h)
479
480should have the desired effect. If an organisation produces a number of
481libraries, then the logger name specified can be "orgname.foo" rather than
482just "foo".
483
Vinay Sajip213faca2008-12-03 23:22:58 +0000484.. versionadded:: 2.7
485
486The :class:`NullHandler` class was not present in previous versions, but is now
487included, so that it need not be defined in library code.
488
489
Georg Brandlc37f2882007-12-04 17:46:27 +0000490
491Logging Levels
492--------------
493
Georg Brandl8ec7f652007-08-15 14:28:01 +0000494The numeric values of logging levels are given in the following table. These are
495primarily of interest if you want to define your own levels, and need them to
496have specific values relative to the predefined levels. If you define a level
497with the same numeric value, it overwrites the predefined value; the predefined
498name is lost.
499
500+--------------+---------------+
501| Level | Numeric value |
502+==============+===============+
503| ``CRITICAL`` | 50 |
504+--------------+---------------+
505| ``ERROR`` | 40 |
506+--------------+---------------+
507| ``WARNING`` | 30 |
508+--------------+---------------+
509| ``INFO`` | 20 |
510+--------------+---------------+
511| ``DEBUG`` | 10 |
512+--------------+---------------+
513| ``NOTSET`` | 0 |
514+--------------+---------------+
515
516Levels can also be associated with loggers, being set either by the developer or
517through loading a saved logging configuration. When a logging method is called
518on a logger, the logger compares its own level with the level associated with
519the method call. If the logger's level is higher than the method call's, no
520logging message is actually generated. This is the basic mechanism controlling
521the verbosity of logging output.
522
523Logging messages are encoded as instances of the :class:`LogRecord` class. When
524a logger decides to actually log an event, a :class:`LogRecord` instance is
525created from the logging message.
526
527Logging messages are subjected to a dispatch mechanism through the use of
528:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
529class. Handlers are responsible for ensuring that a logged message (in the form
530of a :class:`LogRecord`) ends up in a particular location (or set of locations)
531which is useful for the target audience for that message (such as end users,
532support desk staff, system administrators, developers). Handlers are passed
533:class:`LogRecord` instances intended for particular destinations. Each logger
534can have zero, one or more handlers associated with it (via the
535:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
536directly associated with a logger, *all handlers associated with all ancestors
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000537of the logger* are called to dispatch the message (unless the *propagate* flag
538for a logger is set to a false value, at which point the passing to ancestor
539handlers stops).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000540
541Just as for loggers, handlers can have levels associated with them. A handler's
542level acts as a filter in the same way as a logger's level does. If a handler
543decides to actually dispatch an event, the :meth:`emit` method is used to send
544the message to its destination. Most user-defined subclasses of :class:`Handler`
545will need to override this :meth:`emit`.
546
Vinay Sajipb5902e62009-01-15 22:48:13 +0000547Useful Handlers
548---------------
549
Georg Brandl8ec7f652007-08-15 14:28:01 +0000550In addition to the base :class:`Handler` class, many useful subclasses are
551provided:
552
Vinay Sajip4b782332009-01-19 06:49:19 +0000553#. :ref:`stream-handler` instances send error messages to streams (file-like
Georg Brandl8ec7f652007-08-15 14:28:01 +0000554 objects).
555
Vinay Sajip4b782332009-01-19 06:49:19 +0000556#. :ref:`file-handler` instances send error messages to disk files.
Vinay Sajipb1a15e42009-01-15 23:04:47 +0000557
Vinay Sajipb5902e62009-01-15 22:48:13 +0000558#. :class:`BaseRotatingHandler` is the base class for handlers that
Vinay Sajip99234c52009-01-12 20:36:18 +0000559 rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajip4b782332009-01-19 06:49:19 +0000560 directly. Instead, use :ref:`rotating-file-handler` or
561 :ref:`timed-rotating-file-handler`.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000562
Vinay Sajip4b782332009-01-19 06:49:19 +0000563#. :ref:`rotating-file-handler` instances send error messages to disk
Vinay Sajipb5902e62009-01-15 22:48:13 +0000564 files, with support for maximum log file sizes and log file rotation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000565
Vinay Sajip4b782332009-01-19 06:49:19 +0000566#. :ref:`timed-rotating-file-handler` instances send error messages to
Vinay Sajipb5902e62009-01-15 22:48:13 +0000567 disk files, rotating the log file at certain timed intervals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
Vinay Sajip4b782332009-01-19 06:49:19 +0000569#. :ref:`socket-handler` instances send error messages to TCP/IP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000570 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
Vinay Sajip4b782332009-01-19 06:49:19 +0000572#. :ref:`datagram-handler` instances send error messages to UDP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000573 sockets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000574
Vinay Sajip4b782332009-01-19 06:49:19 +0000575#. :ref:`smtp-handler` instances send error messages to a designated
Vinay Sajipb5902e62009-01-15 22:48:13 +0000576 email address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000577
Vinay Sajip4b782332009-01-19 06:49:19 +0000578#. :ref:`syslog-handler` instances send error messages to a Unix
Vinay Sajipb5902e62009-01-15 22:48:13 +0000579 syslog daemon, possibly on a remote machine.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000580
Vinay Sajip4b782332009-01-19 06:49:19 +0000581#. :ref:`nt-eventlog-handler` instances send error messages to a
Vinay Sajipb5902e62009-01-15 22:48:13 +0000582 Windows NT/2000/XP event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000583
Vinay Sajip4b782332009-01-19 06:49:19 +0000584#. :ref:`memory-handler` instances send error messages to a buffer
Vinay Sajipb5902e62009-01-15 22:48:13 +0000585 in memory, which is flushed whenever specific criteria are met.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000586
Vinay Sajip4b782332009-01-19 06:49:19 +0000587#. :ref:`http-handler` instances send error messages to an HTTP
Vinay Sajipb5902e62009-01-15 22:48:13 +0000588 server using either ``GET`` or ``POST`` semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589
Vinay Sajip4b782332009-01-19 06:49:19 +0000590#. :ref:`watched-file-handler` instances watch the file they are
Vinay Sajipb5902e62009-01-15 22:48:13 +0000591 logging to. If the file changes, it is closed and reopened using the file
592 name. This handler is only useful on Unix-like systems; Windows does not
593 support the underlying mechanism used.
Vinay Sajipc2211ad2009-01-10 19:22:57 +0000594
Vinay Sajip4b782332009-01-19 06:49:19 +0000595#. :ref:`null-handler` instances do nothing with error messages. They are used
Vinay Sajip213faca2008-12-03 23:22:58 +0000596 by library developers who want to use logging, but want to avoid the "No
597 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip99505c82009-01-10 13:38:04 +0000598 the library user has not configured logging. See :ref:`library-config` for
599 more information.
Vinay Sajip213faca2008-12-03 23:22:58 +0000600
601.. versionadded:: 2.7
602
603The :class:`NullHandler` class was not present in previous versions.
604
Vinay Sajip7cc97552008-12-30 07:01:25 +0000605The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
606classes are defined in the core logging package. The other handlers are
607defined in a sub- module, :mod:`logging.handlers`. (There is also another
608sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
610Logged messages are formatted for presentation through instances of the
611:class:`Formatter` class. They are initialized with a format string suitable for
612use with the % operator and a dictionary.
613
614For formatting multiple messages in a batch, instances of
615:class:`BufferingFormatter` can be used. In addition to the format string (which
616is applied to each message in the batch), there is provision for header and
617trailer format strings.
618
619When filtering based on logger level and/or handler level is not enough,
620instances of :class:`Filter` can be added to both :class:`Logger` and
621:class:`Handler` instances (through their :meth:`addFilter` method). Before
622deciding to process a message further, both loggers and handlers consult all
623their filters for permission. If any filter returns a false value, the message
624is not processed further.
625
626The basic :class:`Filter` functionality allows filtering by specific logger
627name. If this feature is used, messages sent to the named logger and its
628children are allowed through the filter, and all others dropped.
629
Vinay Sajipb5902e62009-01-15 22:48:13 +0000630Module-Level Functions
631----------------------
632
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633In addition to the classes described above, there are a number of module- level
634functions.
635
636
637.. function:: getLogger([name])
638
639 Return a logger with the specified name or, if no name is specified, return a
640 logger which is the root logger of the hierarchy. If specified, the name is
641 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
642 Choice of these names is entirely up to the developer who is using logging.
643
644 All calls to this function with a given name return the same logger instance.
645 This means that logger instances never need to be passed between different parts
646 of an application.
647
648
649.. function:: getLoggerClass()
650
651 Return either the standard :class:`Logger` class, or the last class passed to
652 :func:`setLoggerClass`. This function may be called from within a new class
653 definition, to ensure that installing a customised :class:`Logger` class will
654 not undo customisations already applied by other code. For example::
655
656 class MyLogger(logging.getLoggerClass()):
657 # ... override behaviour here
658
659
660.. function:: debug(msg[, *args[, **kwargs]])
661
662 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
663 message format string, and the *args* are the arguments which are merged into
664 *msg* using the string formatting operator. (Note that this means that you can
665 use keywords in the format string, together with a single dictionary argument.)
666
667 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
668 which, if it does not evaluate as false, causes exception information to be
669 added to the logging message. If an exception tuple (in the format returned by
670 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
671 is called to get the exception information.
672
673 The other optional keyword argument is *extra* which can be used to pass a
674 dictionary which is used to populate the __dict__ of the LogRecord created for
675 the logging event with user-defined attributes. These custom attributes can then
676 be used as you like. For example, they could be incorporated into logged
677 messages. For example::
678
679 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
680 logging.basicConfig(format=FORMAT)
681 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
682 logging.warning("Protocol problem: %s", "connection reset", extra=d)
683
684 would print something like ::
685
686 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
687
688 The keys in the dictionary passed in *extra* should not clash with the keys used
689 by the logging system. (See the :class:`Formatter` documentation for more
690 information on which keys are used by the logging system.)
691
692 If you choose to use these attributes in logged messages, you need to exercise
693 some care. In the above example, for instance, the :class:`Formatter` has been
694 set up with a format string which expects 'clientip' and 'user' in the attribute
695 dictionary of the LogRecord. If these are missing, the message will not be
696 logged because a string formatting exception will occur. So in this case, you
697 always need to pass the *extra* dictionary with these keys.
698
699 While this might be annoying, this feature is intended for use in specialized
700 circumstances, such as multi-threaded servers where the same code executes in
701 many contexts, and interesting conditions which arise are dependent on this
702 context (such as remote client IP address and authenticated user name, in the
703 above example). In such circumstances, it is likely that specialized
704 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
705
706 .. versionchanged:: 2.5
707 *extra* was added.
708
709
710.. function:: info(msg[, *args[, **kwargs]])
711
712 Logs a message with level :const:`INFO` on the root logger. The arguments are
713 interpreted as for :func:`debug`.
714
715
716.. function:: warning(msg[, *args[, **kwargs]])
717
718 Logs a message with level :const:`WARNING` on the root logger. The arguments are
719 interpreted as for :func:`debug`.
720
721
722.. function:: error(msg[, *args[, **kwargs]])
723
724 Logs a message with level :const:`ERROR` on the root logger. The arguments are
725 interpreted as for :func:`debug`.
726
727
728.. function:: critical(msg[, *args[, **kwargs]])
729
730 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
731 are interpreted as for :func:`debug`.
732
733
734.. function:: exception(msg[, *args])
735
736 Logs a message with level :const:`ERROR` on the root logger. The arguments are
737 interpreted as for :func:`debug`. Exception info is added to the logging
738 message. This function should only be called from an exception handler.
739
740
741.. function:: log(level, msg[, *args[, **kwargs]])
742
743 Logs a message with level *level* on the root logger. The other arguments are
744 interpreted as for :func:`debug`.
745
746
747.. function:: disable(lvl)
748
749 Provides an overriding level *lvl* for all loggers which takes precedence over
750 the logger's own level. When the need arises to temporarily throttle logging
Vinay Sajip2060e422010-03-17 15:05:57 +0000751 output down across the whole application, this function can be useful. Its
752 effect is to disable all logging calls of severity *lvl* and below, so that
753 if you call it with a value of INFO, then all INFO and DEBUG events would be
754 discarded, whereas those of severity WARNING and above would be processed
755 according to the logger's effective level.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000756
757
758.. function:: addLevelName(lvl, levelName)
759
760 Associates level *lvl* with text *levelName* in an internal dictionary, which is
761 used to map numeric levels to a textual representation, for example when a
762 :class:`Formatter` formats a message. This function can also be used to define
763 your own levels. The only constraints are that all levels used must be
764 registered using this function, levels should be positive integers and they
765 should increase in increasing order of severity.
766
767
768.. function:: getLevelName(lvl)
769
770 Returns the textual representation of logging level *lvl*. If the level is one
771 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
772 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
773 have associated levels with names using :func:`addLevelName` then the name you
774 have associated with *lvl* is returned. If a numeric value corresponding to one
775 of the defined levels is passed in, the corresponding string representation is
776 returned. Otherwise, the string "Level %s" % lvl is returned.
777
778
779.. function:: makeLogRecord(attrdict)
780
781 Creates and returns a new :class:`LogRecord` instance whose attributes are
782 defined by *attrdict*. This function is useful for taking a pickled
783 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
784 it as a :class:`LogRecord` instance at the receiving end.
785
786
787.. function:: basicConfig([**kwargs])
788
789 Does basic configuration for the logging system by creating a
790 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000791 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000792 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
793 if no handlers are defined for the root logger.
794
Vinay Sajip1c77b7f2009-10-10 20:32:36 +0000795 This function does nothing if the root logger already has handlers
796 configured for it.
Georg Brandldfb5bbd2008-05-09 06:18:27 +0000797
Georg Brandl8ec7f652007-08-15 14:28:01 +0000798 .. versionchanged:: 2.4
799 Formerly, :func:`basicConfig` did not take any keyword arguments.
800
801 The following keyword arguments are supported.
802
803 +--------------+---------------------------------------------+
804 | Format | Description |
805 +==============+=============================================+
806 | ``filename`` | Specifies that a FileHandler be created, |
807 | | using the specified filename, rather than a |
808 | | StreamHandler. |
809 +--------------+---------------------------------------------+
810 | ``filemode`` | Specifies the mode to open the file, if |
811 | | filename is specified (if filemode is |
812 | | unspecified, it defaults to 'a'). |
813 +--------------+---------------------------------------------+
814 | ``format`` | Use the specified format string for the |
815 | | handler. |
816 +--------------+---------------------------------------------+
817 | ``datefmt`` | Use the specified date/time format. |
818 +--------------+---------------------------------------------+
819 | ``level`` | Set the root logger level to the specified |
820 | | level. |
821 +--------------+---------------------------------------------+
822 | ``stream`` | Use the specified stream to initialize the |
823 | | StreamHandler. Note that this argument is |
824 | | incompatible with 'filename' - if both are |
825 | | present, 'stream' is ignored. |
826 +--------------+---------------------------------------------+
827
828
829.. function:: shutdown()
830
831 Informs the logging system to perform an orderly shutdown by flushing and
Vinay Sajip91f0ee42008-03-16 21:35:58 +0000832 closing all handlers. This should be called at application exit and no
833 further use of the logging system should be made after this call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834
835
836.. function:: setLoggerClass(klass)
837
838 Tells the logging system to use the class *klass* when instantiating a logger.
839 The class should define :meth:`__init__` such that only a name argument is
840 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
841 function is typically called before any loggers are instantiated by applications
842 which need to use custom logger behavior.
843
844
845.. seealso::
846
847 :pep:`282` - A Logging System
848 The proposal which described this feature for inclusion in the Python standard
849 library.
850
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000851 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +0000852 This is the original source for the :mod:`logging` package. The version of the
853 package available from this site is suitable for use with Python 1.5.2, 2.1.x
854 and 2.2.x, which do not include the :mod:`logging` package in the standard
855 library.
856
Vinay Sajip4b782332009-01-19 06:49:19 +0000857.. _logger:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000858
859Logger Objects
860--------------
861
862Loggers have the following attributes and methods. Note that Loggers are never
863instantiated directly, but always through the module-level function
864``logging.getLogger(name)``.
865
866
867.. attribute:: Logger.propagate
868
869 If this evaluates to false, logging messages are not passed by this logger or by
Vinay Sajipccd8bc82010-04-06 22:32:37 +0000870 its child loggers to the handlers of higher level (ancestor) loggers. The
871 constructor sets this attribute to 1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
873
874.. method:: Logger.setLevel(lvl)
875
876 Sets the threshold for this logger to *lvl*. Logging messages which are less
877 severe than *lvl* will be ignored. When a logger is created, the level is set to
878 :const:`NOTSET` (which causes all messages to be processed when the logger is
879 the root logger, or delegation to the parent when the logger is a non-root
880 logger). Note that the root logger is created with level :const:`WARNING`.
881
882 The term "delegation to the parent" means that if a logger has a level of
883 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
884 a level other than NOTSET is found, or the root is reached.
885
886 If an ancestor is found with a level other than NOTSET, then that ancestor's
887 level is treated as the effective level of the logger where the ancestor search
888 began, and is used to determine how a logging event is handled.
889
890 If the root is reached, and it has a level of NOTSET, then all messages will be
891 processed. Otherwise, the root's level will be used as the effective level.
892
893
894.. method:: Logger.isEnabledFor(lvl)
895
896 Indicates if a message of severity *lvl* would be processed by this logger.
897 This method checks first the module-level level set by
898 ``logging.disable(lvl)`` and then the logger's effective level as determined
899 by :meth:`getEffectiveLevel`.
900
901
902.. method:: Logger.getEffectiveLevel()
903
904 Indicates the effective level for this logger. If a value other than
905 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
906 the hierarchy is traversed towards the root until a value other than
907 :const:`NOTSET` is found, and that value is returned.
908
909
Vinay Sajip804899b2010-03-22 15:29:01 +0000910.. method:: Logger.getChild(suffix)
911
912 Returns a logger which is a descendant to this logger, as determined by the suffix.
913 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
914 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
915 convenience method, useful when the parent logger is named using e.g. ``__name__``
916 rather than a literal string.
917
918 .. versionadded:: 2.7
919
Georg Brandl8ec7f652007-08-15 14:28:01 +0000920.. method:: Logger.debug(msg[, *args[, **kwargs]])
921
922 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
923 message format string, and the *args* are the arguments which are merged into
924 *msg* using the string formatting operator. (Note that this means that you can
925 use keywords in the format string, together with a single dictionary argument.)
926
927 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
928 which, if it does not evaluate as false, causes exception information to be
929 added to the logging message. If an exception tuple (in the format returned by
930 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
931 is called to get the exception information.
932
933 The other optional keyword argument is *extra* which can be used to pass a
934 dictionary which is used to populate the __dict__ of the LogRecord created for
935 the logging event with user-defined attributes. These custom attributes can then
936 be used as you like. For example, they could be incorporated into logged
937 messages. For example::
938
939 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
940 logging.basicConfig(format=FORMAT)
Neal Norwitz53004282007-10-23 05:44:27 +0000941 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl8ec7f652007-08-15 14:28:01 +0000942 logger = logging.getLogger("tcpserver")
943 logger.warning("Protocol problem: %s", "connection reset", extra=d)
944
945 would print something like ::
946
947 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
948
949 The keys in the dictionary passed in *extra* should not clash with the keys used
950 by the logging system. (See the :class:`Formatter` documentation for more
951 information on which keys are used by the logging system.)
952
953 If you choose to use these attributes in logged messages, you need to exercise
954 some care. In the above example, for instance, the :class:`Formatter` has been
955 set up with a format string which expects 'clientip' and 'user' in the attribute
956 dictionary of the LogRecord. If these are missing, the message will not be
957 logged because a string formatting exception will occur. So in this case, you
958 always need to pass the *extra* dictionary with these keys.
959
960 While this might be annoying, this feature is intended for use in specialized
961 circumstances, such as multi-threaded servers where the same code executes in
962 many contexts, and interesting conditions which arise are dependent on this
963 context (such as remote client IP address and authenticated user name, in the
964 above example). In such circumstances, it is likely that specialized
965 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
966
967 .. versionchanged:: 2.5
968 *extra* was added.
969
970
971.. method:: Logger.info(msg[, *args[, **kwargs]])
972
973 Logs a message with level :const:`INFO` on this logger. The arguments are
974 interpreted as for :meth:`debug`.
975
976
977.. method:: Logger.warning(msg[, *args[, **kwargs]])
978
979 Logs a message with level :const:`WARNING` on this logger. The arguments are
980 interpreted as for :meth:`debug`.
981
982
983.. method:: Logger.error(msg[, *args[, **kwargs]])
984
985 Logs a message with level :const:`ERROR` on this logger. The arguments are
986 interpreted as for :meth:`debug`.
987
988
989.. method:: Logger.critical(msg[, *args[, **kwargs]])
990
991 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
992 interpreted as for :meth:`debug`.
993
994
995.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
996
997 Logs a message with integer level *lvl* on this logger. The other arguments are
998 interpreted as for :meth:`debug`.
999
1000
1001.. method:: Logger.exception(msg[, *args])
1002
1003 Logs a message with level :const:`ERROR` on this logger. The arguments are
1004 interpreted as for :meth:`debug`. Exception info is added to the logging
1005 message. This method should only be called from an exception handler.
1006
1007
1008.. method:: Logger.addFilter(filt)
1009
1010 Adds the specified filter *filt* to this logger.
1011
1012
1013.. method:: Logger.removeFilter(filt)
1014
1015 Removes the specified filter *filt* from this logger.
1016
1017
1018.. method:: Logger.filter(record)
1019
1020 Applies this logger's filters to the record and returns a true value if the
1021 record is to be processed.
1022
1023
1024.. method:: Logger.addHandler(hdlr)
1025
1026 Adds the specified handler *hdlr* to this logger.
1027
1028
1029.. method:: Logger.removeHandler(hdlr)
1030
1031 Removes the specified handler *hdlr* from this logger.
1032
1033
1034.. method:: Logger.findCaller()
1035
1036 Finds the caller's source filename and line number. Returns the filename, line
1037 number and function name as a 3-element tuple.
1038
Matthias Klosef0e29182007-08-16 12:03:44 +00001039 .. versionchanged:: 2.4
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040 The function name was added. In earlier versions, the filename and line number
1041 were returned as a 2-element tuple..
1042
1043
1044.. method:: Logger.handle(record)
1045
1046 Handles a record by passing it to all handlers associated with this logger and
1047 its ancestors (until a false value of *propagate* is found). This method is used
1048 for unpickled records received from a socket, as well as those created locally.
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001049 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050
1051
1052.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
1053
1054 This is a factory method which can be overridden in subclasses to create
1055 specialized :class:`LogRecord` instances.
1056
1057 .. versionchanged:: 2.5
1058 *func* and *extra* were added.
1059
1060
1061.. _minimal-example:
1062
1063Basic example
1064-------------
1065
1066.. versionchanged:: 2.4
1067 formerly :func:`basicConfig` did not take any keyword arguments.
1068
1069The :mod:`logging` package provides a lot of flexibility, and its configuration
1070can appear daunting. This section demonstrates that simple use of the logging
1071package is possible.
1072
1073The simplest example shows logging to the console::
1074
1075 import logging
1076
1077 logging.debug('A debug message')
1078 logging.info('Some information')
1079 logging.warning('A shot across the bows')
1080
1081If you run the above script, you'll see this::
1082
1083 WARNING:root:A shot across the bows
1084
1085Because no particular logger was specified, the system used the root logger. The
1086debug and info messages didn't appear because by default, the root logger is
1087configured to only handle messages with a severity of WARNING or above. The
1088message format is also a configuration default, as is the output destination of
1089the messages - ``sys.stderr``. The severity level, the message format and
1090destination can be easily changed, as shown in the example below::
1091
1092 import logging
1093
1094 logging.basicConfig(level=logging.DEBUG,
1095 format='%(asctime)s %(levelname)s %(message)s',
1096 filename='/tmp/myapp.log',
1097 filemode='w')
1098 logging.debug('A debug message')
1099 logging.info('Some information')
1100 logging.warning('A shot across the bows')
1101
1102The :meth:`basicConfig` method is used to change the configuration defaults,
1103which results in output (written to ``/tmp/myapp.log``) which should look
1104something like the following::
1105
1106 2004-07-02 13:00:08,743 DEBUG A debug message
1107 2004-07-02 13:00:08,743 INFO Some information
1108 2004-07-02 13:00:08,743 WARNING A shot across the bows
1109
1110This time, all messages with a severity of DEBUG or above were handled, and the
1111format of the messages was also changed, and output went to the specified file
1112rather than the console.
1113
1114Formatting uses standard Python string formatting - see section
1115:ref:`string-formatting`. The format string takes the following common
1116specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1117documentation.
1118
1119+-------------------+-----------------------------------------------+
1120| Format | Description |
1121+===================+===============================================+
1122| ``%(name)s`` | Name of the logger (logging channel). |
1123+-------------------+-----------------------------------------------+
1124| ``%(levelname)s`` | Text logging level for the message |
1125| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1126| | ``'ERROR'``, ``'CRITICAL'``). |
1127+-------------------+-----------------------------------------------+
1128| ``%(asctime)s`` | Human-readable time when the |
1129| | :class:`LogRecord` was created. By default |
1130| | this is of the form "2003-07-08 16:49:45,896" |
1131| | (the numbers after the comma are millisecond |
1132| | portion of the time). |
1133+-------------------+-----------------------------------------------+
1134| ``%(message)s`` | The logged message. |
1135+-------------------+-----------------------------------------------+
1136
1137To change the date/time format, you can pass an additional keyword parameter,
1138*datefmt*, as in the following::
1139
1140 import logging
1141
1142 logging.basicConfig(level=logging.DEBUG,
1143 format='%(asctime)s %(levelname)-8s %(message)s',
1144 datefmt='%a, %d %b %Y %H:%M:%S',
1145 filename='/temp/myapp.log',
1146 filemode='w')
1147 logging.debug('A debug message')
1148 logging.info('Some information')
1149 logging.warning('A shot across the bows')
1150
1151which would result in output like ::
1152
1153 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1154 Fri, 02 Jul 2004 13:06:18 INFO Some information
1155 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1156
1157The date format string follows the requirements of :func:`strftime` - see the
1158documentation for the :mod:`time` module.
1159
1160If, instead of sending logging output to the console or a file, you'd rather use
1161a file-like object which you have created separately, you can pass it to
1162:func:`basicConfig` using the *stream* keyword argument. Note that if both
1163*stream* and *filename* keyword arguments are passed, the *stream* argument is
1164ignored.
1165
1166Of course, you can put variable information in your output. To do this, simply
1167have the message be a format string and pass in additional arguments containing
1168the variable information, as in the following example::
1169
1170 import logging
1171
1172 logging.basicConfig(level=logging.DEBUG,
1173 format='%(asctime)s %(levelname)-8s %(message)s',
1174 datefmt='%a, %d %b %Y %H:%M:%S',
1175 filename='/temp/myapp.log',
1176 filemode='w')
1177 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1178
1179which would result in ::
1180
1181 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1182
1183
1184.. _multiple-destinations:
1185
1186Logging to multiple destinations
1187--------------------------------
1188
1189Let's say you want to log to console and file with different message formats and
1190in differing circumstances. Say you want to log messages with levels of DEBUG
1191and higher to file, and those messages at level INFO and higher to the console.
1192Let's also assume that the file should contain timestamps, but the console
1193messages should not. Here's how you can achieve this::
1194
1195 import logging
1196
1197 # set up logging to file - see previous section for more details
1198 logging.basicConfig(level=logging.DEBUG,
1199 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1200 datefmt='%m-%d %H:%M',
1201 filename='/temp/myapp.log',
1202 filemode='w')
1203 # define a Handler which writes INFO messages or higher to the sys.stderr
1204 console = logging.StreamHandler()
1205 console.setLevel(logging.INFO)
1206 # set a format which is simpler for console use
1207 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1208 # tell the handler to use this format
1209 console.setFormatter(formatter)
1210 # add the handler to the root logger
1211 logging.getLogger('').addHandler(console)
1212
1213 # Now, we can log to the root logger, or any other logger. First the root...
1214 logging.info('Jackdaws love my big sphinx of quartz.')
1215
1216 # Now, define a couple of other loggers which might represent areas in your
1217 # application:
1218
1219 logger1 = logging.getLogger('myapp.area1')
1220 logger2 = logging.getLogger('myapp.area2')
1221
1222 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1223 logger1.info('How quickly daft jumping zebras vex.')
1224 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1225 logger2.error('The five boxing wizards jump quickly.')
1226
1227When you run this, on the console you will see ::
1228
1229 root : INFO Jackdaws love my big sphinx of quartz.
1230 myapp.area1 : INFO How quickly daft jumping zebras vex.
1231 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1232 myapp.area2 : ERROR The five boxing wizards jump quickly.
1233
1234and in the file you will see something like ::
1235
1236 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1237 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1238 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1239 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1240 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1241
1242As you can see, the DEBUG message only shows up in the file. The other messages
1243are sent to both destinations.
1244
1245This example uses console and file handlers, but you can use any number and
1246combination of handlers you choose.
1247
Vinay Sajip333c6e72009-08-20 22:04:32 +00001248.. _logging-exceptions:
1249
1250Exceptions raised during logging
1251--------------------------------
1252
1253The logging package is designed to swallow exceptions which occur while logging
1254in production. This is so that errors which occur while handling logging events
1255- such as logging misconfiguration, network or other similar errors - do not
1256cause the application using logging to terminate prematurely.
1257
1258:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1259swallowed. Other exceptions which occur during the :meth:`emit` method of a
1260:class:`Handler` subclass are passed to its :meth:`handleError` method.
1261
1262The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlf6d367452010-03-12 10:02:03 +00001263to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1264traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip333c6e72009-08-20 22:04:32 +00001265
Georg Brandlf6d367452010-03-12 10:02:03 +00001266**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip333c6e72009-08-20 22:04:32 +00001267during development, you typically want to be notified of any exceptions that
Georg Brandlf6d367452010-03-12 10:02:03 +00001268occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip333c6e72009-08-20 22:04:32 +00001269usage.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001270
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001271.. _context-info:
1272
1273Adding contextual information to your logging output
1274----------------------------------------------------
1275
1276Sometimes you want logging output to contain contextual information in
1277addition to the parameters passed to the logging call. For example, in a
1278networked application, it may be desirable to log client-specific information
1279in the log (e.g. remote client's username, or IP address). Although you could
1280use the *extra* parameter to achieve this, it's not always convenient to pass
1281the information in this way. While it might be tempting to create
1282:class:`Logger` instances on a per-connection basis, this is not a good idea
1283because these instances are not garbage collected. While this is not a problem
1284in practice, when the number of :class:`Logger` instances is dependent on the
1285level of granularity you want to use in logging an application, it could
1286be hard to manage if the number of :class:`Logger` instances becomes
1287effectively unbounded.
1288
Vinay Sajipc7403352008-01-18 15:54:14 +00001289An easy way in which you can pass contextual information to be output along
1290with logging event information is to use the :class:`LoggerAdapter` class.
1291This class is designed to look like a :class:`Logger`, so that you can call
1292:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1293:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1294same signatures as their counterparts in :class:`Logger`, so you can use the
1295two types of instances interchangeably.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001296
Vinay Sajipc7403352008-01-18 15:54:14 +00001297When you create an instance of :class:`LoggerAdapter`, you pass it a
1298:class:`Logger` instance and a dict-like object which contains your contextual
1299information. When you call one of the logging methods on an instance of
1300:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1301:class:`Logger` passed to its constructor, and arranges to pass the contextual
1302information in the delegated call. Here's a snippet from the code of
1303:class:`LoggerAdapter`::
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001304
Vinay Sajipc7403352008-01-18 15:54:14 +00001305 def debug(self, msg, *args, **kwargs):
1306 """
1307 Delegate a debug call to the underlying logger, after adding
1308 contextual information from this adapter instance.
1309 """
1310 msg, kwargs = self.process(msg, kwargs)
1311 self.logger.debug(msg, *args, **kwargs)
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001312
Vinay Sajipc7403352008-01-18 15:54:14 +00001313The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1314information is added to the logging output. It's passed the message and
1315keyword arguments of the logging call, and it passes back (potentially)
1316modified versions of these to use in the call to the underlying logger. The
1317default implementation of this method leaves the message alone, but inserts
1318an "extra" key in the keyword argument whose value is the dict-like object
1319passed to the constructor. Of course, if you had passed an "extra" keyword
1320argument in the call to the adapter, it will be silently overwritten.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001321
Vinay Sajipc7403352008-01-18 15:54:14 +00001322The advantage of using "extra" is that the values in the dict-like object are
1323merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1324customized strings with your :class:`Formatter` instances which know about
1325the keys of the dict-like object. If you need a different method, e.g. if you
1326want to prepend or append the contextual information to the message string,
1327you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1328to do what you need. Here's an example script which uses this class, which
1329also illustrates what dict-like behaviour is needed from an arbitrary
1330"dict-like" object for use in the constructor::
1331
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001332 import logging
Vinay Sajip733024a2008-01-21 17:39:22 +00001333
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001334 class ConnInfo:
1335 """
1336 An example class which shows how an arbitrary class can be used as
1337 the 'extra' context information repository passed to a LoggerAdapter.
1338 """
Vinay Sajip733024a2008-01-21 17:39:22 +00001339
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001340 def __getitem__(self, name):
1341 """
1342 To allow this instance to look like a dict.
1343 """
1344 from random import choice
1345 if name == "ip":
1346 result = choice(["127.0.0.1", "192.168.0.1"])
1347 elif name == "user":
1348 result = choice(["jim", "fred", "sheila"])
1349 else:
1350 result = self.__dict__.get(name, "?")
1351 return result
Vinay Sajip733024a2008-01-21 17:39:22 +00001352
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001353 def __iter__(self):
1354 """
1355 To allow iteration over keys, which will be merged into
1356 the LogRecord dict before formatting and output.
1357 """
1358 keys = ["ip", "user"]
1359 keys.extend(self.__dict__.keys())
1360 return keys.__iter__()
Vinay Sajip733024a2008-01-21 17:39:22 +00001361
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001362 if __name__ == "__main__":
1363 from random import choice
1364 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1365 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1366 { "ip" : "123.231.231.123", "user" : "sheila" })
1367 logging.basicConfig(level=logging.DEBUG,
1368 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1369 a1.debug("A debug message")
1370 a1.info("An info message with %s", "some parameters")
1371 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1372 for x in range(10):
1373 lvl = choice(levels)
1374 lvlname = logging.getLevelName(lvl)
1375 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Vinay Sajipc7403352008-01-18 15:54:14 +00001376
1377When this script is run, the output should look something like this::
1378
Georg Brandlf8e6afb2008-01-19 10:11:27 +00001379 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1380 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1381 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
1382 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
1383 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
1384 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
1385 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
1386 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
1387 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
1388 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
1389 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
1390 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Vinay Sajipc7403352008-01-18 15:54:14 +00001391
1392.. versionadded:: 2.6
1393
1394The :class:`LoggerAdapter` class was not present in previous versions.
1395
Vinay Sajip3a0dc302009-08-15 23:23:12 +00001396.. _multiple-processes:
1397
1398Logging to a single file from multiple processes
1399------------------------------------------------
1400
1401Although logging is thread-safe, and logging to a single file from multiple
1402threads in a single process *is* supported, logging to a single file from
1403*multiple processes* is *not* supported, because there is no standard way to
1404serialize access to a single file across multiple processes in Python. If you
1405need to log to a single file from multiple processes, the best way of doing
1406this is to have all the processes log to a :class:`SocketHandler`, and have a
1407separate process which implements a socket server which reads from the socket
1408and logs to file. (If you prefer, you can dedicate one thread in one of the
1409existing processes to perform this function.) The following section documents
1410this approach in more detail and includes a working socket receiver which can
1411be used as a starting point for you to adapt in your own applications.
Vinay Sajipaa0665b2008-01-07 19:40:10 +00001412
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001413If you are using a recent version of Python which includes the
1414:mod:`multiprocessing` module, you can write your own handler which uses the
1415:class:`Lock` class from this module to serialize access to the file from
1416your processes. The existing :class:`FileHandler` and subclasses do not make
1417use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip5e7f6452009-08-17 13:14:37 +00001418Note that at present, the :mod:`multiprocessing` module does not provide
1419working lock functionality on all platforms (see
1420http://bugs.python.org/issue3770).
Vinay Sajip1c0b24f2009-08-15 23:34:47 +00001421
Georg Brandl8ec7f652007-08-15 14:28:01 +00001422.. _network-logging:
1423
1424Sending and receiving logging events across a network
1425-----------------------------------------------------
1426
1427Let's say you want to send logging events across a network, and handle them at
1428the receiving end. A simple way of doing this is attaching a
1429:class:`SocketHandler` instance to the root logger at the sending end::
1430
Benjamin Petersona7b55a32009-02-20 03:31:23 +00001431 import logging, logging.handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +00001432
1433 rootLogger = logging.getLogger('')
1434 rootLogger.setLevel(logging.DEBUG)
1435 socketHandler = logging.handlers.SocketHandler('localhost',
1436 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1437 # don't bother with a formatter, since a socket handler sends the event as
1438 # an unformatted pickle
1439 rootLogger.addHandler(socketHandler)
1440
1441 # Now, we can log to the root logger, or any other logger. First the root...
1442 logging.info('Jackdaws love my big sphinx of quartz.')
1443
1444 # Now, define a couple of other loggers which might represent areas in your
1445 # application:
1446
1447 logger1 = logging.getLogger('myapp.area1')
1448 logger2 = logging.getLogger('myapp.area2')
1449
1450 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1451 logger1.info('How quickly daft jumping zebras vex.')
1452 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1453 logger2.error('The five boxing wizards jump quickly.')
1454
Georg Brandle152a772008-05-24 18:31:28 +00001455At the receiving end, you can set up a receiver using the :mod:`SocketServer`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001456module. Here is a basic working example::
1457
1458 import cPickle
1459 import logging
1460 import logging.handlers
Georg Brandle152a772008-05-24 18:31:28 +00001461 import SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001462 import struct
1463
1464
Georg Brandle152a772008-05-24 18:31:28 +00001465 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001466 """Handler for a streaming logging request.
1467
1468 This basically logs the record using whatever logging policy is
1469 configured locally.
1470 """
1471
1472 def handle(self):
1473 """
1474 Handle multiple requests - each expected to be a 4-byte length,
1475 followed by the LogRecord in pickle format. Logs the record
1476 according to whatever policy is configured locally.
1477 """
1478 while 1:
1479 chunk = self.connection.recv(4)
1480 if len(chunk) < 4:
1481 break
1482 slen = struct.unpack(">L", chunk)[0]
1483 chunk = self.connection.recv(slen)
1484 while len(chunk) < slen:
1485 chunk = chunk + self.connection.recv(slen - len(chunk))
1486 obj = self.unPickle(chunk)
1487 record = logging.makeLogRecord(obj)
1488 self.handleLogRecord(record)
1489
1490 def unPickle(self, data):
1491 return cPickle.loads(data)
1492
1493 def handleLogRecord(self, record):
1494 # if a name is specified, we use the named logger rather than the one
1495 # implied by the record.
1496 if self.server.logname is not None:
1497 name = self.server.logname
1498 else:
1499 name = record.name
1500 logger = logging.getLogger(name)
1501 # N.B. EVERY record gets logged. This is because Logger.handle
1502 # is normally called AFTER logger-level filtering. If you want
1503 # to do filtering, do it at the client end to save wasting
1504 # cycles and network bandwidth!
1505 logger.handle(record)
1506
Georg Brandle152a772008-05-24 18:31:28 +00001507 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001508 """simple TCP socket-based logging receiver suitable for testing.
1509 """
1510
1511 allow_reuse_address = 1
1512
1513 def __init__(self, host='localhost',
1514 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1515 handler=LogRecordStreamHandler):
Georg Brandle152a772008-05-24 18:31:28 +00001516 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001517 self.abort = 0
1518 self.timeout = 1
1519 self.logname = None
1520
1521 def serve_until_stopped(self):
1522 import select
1523 abort = 0
1524 while not abort:
1525 rd, wr, ex = select.select([self.socket.fileno()],
1526 [], [],
1527 self.timeout)
1528 if rd:
1529 self.handle_request()
1530 abort = self.abort
1531
1532 def main():
1533 logging.basicConfig(
1534 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1535 tcpserver = LogRecordSocketReceiver()
1536 print "About to start TCP server..."
1537 tcpserver.serve_until_stopped()
1538
1539 if __name__ == "__main__":
1540 main()
1541
1542First run the server, and then the client. On the client side, nothing is
1543printed on the console; on the server side, you should see something like::
1544
1545 About to start TCP server...
1546 59 root INFO Jackdaws love my big sphinx of quartz.
1547 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1548 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1549 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1550 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1551
Vinay Sajipf778bec2009-09-22 17:23:41 +00001552Using arbitrary objects as messages
1553-----------------------------------
1554
1555In the preceding sections and examples, it has been assumed that the message
1556passed when logging the event is a string. However, this is not the only
1557possibility. You can pass an arbitrary object as a message, and its
1558:meth:`__str__` method will be called when the logging system needs to convert
1559it to a string representation. In fact, if you want to, you can avoid
1560computing a string representation altogether - for example, the
1561:class:`SocketHandler` emits an event by pickling it and sending it over the
1562wire.
1563
1564Optimization
1565------------
1566
1567Formatting of message arguments is deferred until it cannot be avoided.
1568However, computing the arguments passed to the logging method can also be
1569expensive, and you may want to avoid doing it if the logger will just throw
1570away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1571method which takes a level argument and returns true if the event would be
1572created by the Logger for that level of call. You can write code like this::
1573
1574 if logger.isEnabledFor(logging.DEBUG):
1575 logger.debug("Message with %s, %s", expensive_func1(),
1576 expensive_func2())
1577
1578so that if the logger's threshold is set above ``DEBUG``, the calls to
1579:func:`expensive_func1` and :func:`expensive_func2` are never made.
1580
1581There are other optimizations which can be made for specific applications which
1582need more precise control over what logging information is collected. Here's a
1583list of things you can do to avoid processing during logging which you don't
1584need:
1585
1586+-----------------------------------------------+----------------------------------------+
1587| What you don't want to collect | How to avoid collecting it |
1588+===============================================+========================================+
1589| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1590+-----------------------------------------------+----------------------------------------+
1591| Threading information. | Set ``logging.logThreads`` to ``0``. |
1592+-----------------------------------------------+----------------------------------------+
1593| Process information. | Set ``logging.logProcesses`` to ``0``. |
1594+-----------------------------------------------+----------------------------------------+
1595
1596Also note that the core logging module only includes the basic handlers. If
1597you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1598take up any memory.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001599
Vinay Sajip4b782332009-01-19 06:49:19 +00001600.. _handler:
1601
Georg Brandl8ec7f652007-08-15 14:28:01 +00001602Handler Objects
1603---------------
1604
1605Handlers have the following attributes and methods. Note that :class:`Handler`
1606is never instantiated directly; this class acts as a base for more useful
1607subclasses. However, the :meth:`__init__` method in subclasses needs to call
1608:meth:`Handler.__init__`.
1609
1610
1611.. method:: Handler.__init__(level=NOTSET)
1612
1613 Initializes the :class:`Handler` instance by setting its level, setting the list
1614 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1615 serializing access to an I/O mechanism.
1616
1617
1618.. method:: Handler.createLock()
1619
1620 Initializes a thread lock which can be used to serialize access to underlying
1621 I/O functionality which may not be threadsafe.
1622
1623
1624.. method:: Handler.acquire()
1625
1626 Acquires the thread lock created with :meth:`createLock`.
1627
1628
1629.. method:: Handler.release()
1630
1631 Releases the thread lock acquired with :meth:`acquire`.
1632
1633
1634.. method:: Handler.setLevel(lvl)
1635
1636 Sets the threshold for this handler to *lvl*. Logging messages which are less
1637 severe than *lvl* will be ignored. When a handler is created, the level is set
1638 to :const:`NOTSET` (which causes all messages to be processed).
1639
1640
1641.. method:: Handler.setFormatter(form)
1642
1643 Sets the :class:`Formatter` for this handler to *form*.
1644
1645
1646.. method:: Handler.addFilter(filt)
1647
1648 Adds the specified filter *filt* to this handler.
1649
1650
1651.. method:: Handler.removeFilter(filt)
1652
1653 Removes the specified filter *filt* from this handler.
1654
1655
1656.. method:: Handler.filter(record)
1657
1658 Applies this handler's filters to the record and returns a true value if the
1659 record is to be processed.
1660
1661
1662.. method:: Handler.flush()
1663
1664 Ensure all logging output has been flushed. This version does nothing and is
1665 intended to be implemented by subclasses.
1666
1667
1668.. method:: Handler.close()
1669
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001670 Tidy up any resources used by the handler. This version does no output but
1671 removes the handler from an internal list of handlers which is closed when
1672 :func:`shutdown` is called. Subclasses should ensure that this gets called
1673 from overridden :meth:`close` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001674
1675
1676.. method:: Handler.handle(record)
1677
1678 Conditionally emits the specified logging record, depending on filters which may
1679 have been added to the handler. Wraps the actual emission of the record with
1680 acquisition/release of the I/O thread lock.
1681
1682
1683.. method:: Handler.handleError(record)
1684
1685 This method should be called from handlers when an exception is encountered
1686 during an :meth:`emit` call. By default it does nothing, which means that
1687 exceptions get silently ignored. This is what is mostly wanted for a logging
1688 system - most users will not care about errors in the logging system, they are
1689 more interested in application errors. You could, however, replace this with a
1690 custom handler if you wish. The specified record is the one which was being
1691 processed when the exception occurred.
1692
1693
1694.. method:: Handler.format(record)
1695
1696 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
1697 default formatter for the module.
1698
1699
1700.. method:: Handler.emit(record)
1701
1702 Do whatever it takes to actually log the specified logging record. This version
1703 is intended to be implemented by subclasses and so raises a
1704 :exc:`NotImplementedError`.
1705
1706
Vinay Sajip4b782332009-01-19 06:49:19 +00001707.. _stream-handler:
1708
Georg Brandl8ec7f652007-08-15 14:28:01 +00001709StreamHandler
1710^^^^^^^^^^^^^
1711
1712The :class:`StreamHandler` class, located in the core :mod:`logging` package,
1713sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
1714file-like object (or, more precisely, any object which supports :meth:`write`
1715and :meth:`flush` methods).
1716
1717
Vinay Sajip0c6a0e32009-12-17 14:52:00 +00001718.. currentmodule:: logging
1719
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001720.. class:: StreamHandler([stream])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001721
Vinay Sajip4780c9a2009-09-26 14:53:32 +00001722 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001723 specified, the instance will use it for logging output; otherwise, *sys.stderr*
1724 will be used.
1725
1726
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001727 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001728
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001729 If a formatter is specified, it is used to format the record. The record
1730 is then written to the stream with a trailing newline. If exception
1731 information is present, it is formatted using
1732 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001733
1734
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001735 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001736
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001737 Flushes the stream by calling its :meth:`flush` method. Note that the
1738 :meth:`close` method is inherited from :class:`Handler` and so does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00001739 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001740
1741
Vinay Sajip4b782332009-01-19 06:49:19 +00001742.. _file-handler:
1743
Georg Brandl8ec7f652007-08-15 14:28:01 +00001744FileHandler
1745^^^^^^^^^^^
1746
1747The :class:`FileHandler` class, located in the core :mod:`logging` package,
1748sends logging output to a disk file. It inherits the output functionality from
1749:class:`StreamHandler`.
1750
1751
Vinay Sajipf38ba782008-01-24 12:38:30 +00001752.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001753
1754 Returns a new instance of the :class:`FileHandler` class. The specified file is
1755 opened and used as the stream for logging. If *mode* is not specified,
1756 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001757 with that encoding. If *delay* is true, then file opening is deferred until the
1758 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001759
Vinay Sajip59584c42009-08-14 11:33:54 +00001760 .. versionchanged:: 2.6
1761 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001762
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001763 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001764
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001765 Closes the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001766
1767
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001768 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001769
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001770 Outputs the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001771
Vinay Sajip4b782332009-01-19 06:49:19 +00001772.. _null-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001773
Vinay Sajip51104862009-01-02 18:53:04 +00001774NullHandler
1775^^^^^^^^^^^
1776
1777.. versionadded:: 2.7
1778
1779The :class:`NullHandler` class, located in the core :mod:`logging` package,
1780does not do any formatting or output. It is essentially a "no-op" handler
1781for use by library developers.
1782
1783
1784.. class:: NullHandler()
1785
1786 Returns a new instance of the :class:`NullHandler` class.
1787
1788
1789 .. method:: emit(record)
1790
1791 This method does nothing.
1792
Vinay Sajip99505c82009-01-10 13:38:04 +00001793See :ref:`library-config` for more information on how to use
1794:class:`NullHandler`.
1795
Vinay Sajip4b782332009-01-19 06:49:19 +00001796.. _watched-file-handler:
1797
Georg Brandl8ec7f652007-08-15 14:28:01 +00001798WatchedFileHandler
1799^^^^^^^^^^^^^^^^^^
1800
1801.. versionadded:: 2.6
1802
Vinay Sajipb1a15e42009-01-15 23:04:47 +00001803.. currentmodule:: logging.handlers
Vinay Sajip51104862009-01-02 18:53:04 +00001804
Georg Brandl8ec7f652007-08-15 14:28:01 +00001805The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1806module, is a :class:`FileHandler` which watches the file it is logging to. If
1807the file changes, it is closed and reopened using the file name.
1808
1809A file change can happen because of usage of programs such as *newsyslog* and
1810*logrotate* which perform log file rotation. This handler, intended for use
1811under Unix/Linux, watches the file to see if it has changed since the last emit.
1812(A file is deemed to have changed if its device or inode have changed.) If the
1813file has changed, the old file stream is closed, and the file opened to get a
1814new stream.
1815
1816This handler is not appropriate for use under Windows, because under Windows
1817open log files cannot be moved or renamed - logging opens the files with
1818exclusive locks - and so there is no need for such a handler. Furthermore,
1819*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1820this value.
1821
1822
Vinay Sajipf38ba782008-01-24 12:38:30 +00001823.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001824
1825 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1826 file is opened and used as the stream for logging. If *mode* is not specified,
1827 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Vinay Sajipf38ba782008-01-24 12:38:30 +00001828 with that encoding. If *delay* is true, then file opening is deferred until the
1829 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001830
Vinay Sajip59584c42009-08-14 11:33:54 +00001831 .. versionchanged:: 2.6
1832 *delay* was added.
1833
Georg Brandl8ec7f652007-08-15 14:28:01 +00001834
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001835 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001836
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001837 Outputs the record to the file, but first checks to see if the file has
1838 changed. If it has, the existing stream is flushed and closed and the
1839 file opened again, before outputting the record to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001840
Vinay Sajip4b782332009-01-19 06:49:19 +00001841.. _rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001842
1843RotatingFileHandler
1844^^^^^^^^^^^^^^^^^^^
1845
1846The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1847module, supports rotation of disk log files.
1848
1849
Vinay Sajipf38ba782008-01-24 12:38:30 +00001850.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001851
1852 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1853 file is opened and used as the stream for logging. If *mode* is not specified,
Vinay Sajipf38ba782008-01-24 12:38:30 +00001854 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
1855 with that encoding. If *delay* is true, then file opening is deferred until the
1856 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001857
1858 You can use the *maxBytes* and *backupCount* values to allow the file to
1859 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1860 the file is closed and a new file is silently opened for output. Rollover occurs
1861 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1862 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1863 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1864 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1865 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1866 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1867 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1868 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1869 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1870
Vinay Sajip59584c42009-08-14 11:33:54 +00001871 .. versionchanged:: 2.6
1872 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001873
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001874 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001875
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001876 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001877
1878
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001879 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001880
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001881 Outputs the record to the file, catering for rollover as described
1882 previously.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001883
Vinay Sajip4b782332009-01-19 06:49:19 +00001884.. _timed-rotating-file-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001885
1886TimedRotatingFileHandler
1887^^^^^^^^^^^^^^^^^^^^^^^^
1888
1889The :class:`TimedRotatingFileHandler` class, located in the
1890:mod:`logging.handlers` module, supports rotation of disk log files at certain
1891timed intervals.
1892
1893
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001894.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001895
1896 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1897 specified file is opened and used as the stream for logging. On rotating it also
1898 sets the filename suffix. Rotating happens based on the product of *when* and
1899 *interval*.
1900
1901 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandld77554f2008-06-06 07:34:50 +00001902 values is below. Note that they are not case sensitive.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001903
Georg Brandl72780a42008-03-02 13:41:39 +00001904 +----------------+-----------------------+
1905 | Value | Type of interval |
1906 +================+=======================+
1907 | ``'S'`` | Seconds |
1908 +----------------+-----------------------+
1909 | ``'M'`` | Minutes |
1910 +----------------+-----------------------+
1911 | ``'H'`` | Hours |
1912 +----------------+-----------------------+
1913 | ``'D'`` | Days |
1914 +----------------+-----------------------+
1915 | ``'W'`` | Week day (0=Monday) |
1916 +----------------+-----------------------+
1917 | ``'midnight'`` | Roll over at midnight |
1918 +----------------+-----------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001919
Georg Brandle6dab2a2008-03-02 14:15:04 +00001920 The system will save old log files by appending extensions to the filename.
1921 The extensions are date-and-time based, using the strftime format
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001922 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Vinay Sajip2a649f92008-07-18 09:00:35 +00001923 rollover interval.
Vinay Sajipecfa08f2010-03-12 09:16:10 +00001924
1925 When computing the next rollover time for the first time (when the handler
1926 is created), the last modification time of an existing log file, or else
1927 the current time, is used to compute when the next rotation will occur.
1928
Georg Brandld77554f2008-06-06 07:34:50 +00001929 If the *utc* argument is true, times in UTC will be used; otherwise
Andrew M. Kuchling6dd8cca2008-06-05 23:33:54 +00001930 local time is used.
1931
1932 If *backupCount* is nonzero, at most *backupCount* files
Vinay Sajip89a01cd2008-04-02 21:17:25 +00001933 will be kept, and if more would be created when rollover occurs, the oldest
1934 one is deleted. The deletion logic uses the interval to determine which
1935 files to delete, so changing the interval may leave old files lying around.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001936
Vinay Sajip59584c42009-08-14 11:33:54 +00001937 If *delay* is true, then file opening is deferred until the first call to
1938 :meth:`emit`.
1939
1940 .. versionchanged:: 2.6
1941 *delay* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001942
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001943 .. method:: doRollover()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001944
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001945 Does a rollover, as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001946
1947
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001948 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001949
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001950 Outputs the record to the file, catering for rollover as described above.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001951
1952
Vinay Sajip4b782332009-01-19 06:49:19 +00001953.. _socket-handler:
1954
Georg Brandl8ec7f652007-08-15 14:28:01 +00001955SocketHandler
1956^^^^^^^^^^^^^
1957
1958The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
1959sends logging output to a network socket. The base class uses a TCP socket.
1960
1961
1962.. class:: SocketHandler(host, port)
1963
1964 Returns a new instance of the :class:`SocketHandler` class intended to
1965 communicate with a remote machine whose address is given by *host* and *port*.
1966
1967
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001968 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001969
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001970 Closes the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001971
1972
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001973 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001974
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001975 Pickles the record's attribute dictionary and writes it to the socket in
1976 binary format. If there is an error with the socket, silently drops the
1977 packet. If the connection was previously lost, re-establishes the
1978 connection. To unpickle the record at the receiving end into a
1979 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001980
1981
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001982 .. method:: handleError()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001983
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001984 Handles an error which has occurred during :meth:`emit`. The most likely
1985 cause is a lost connection. Closes the socket so that we can retry on the
1986 next event.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001987
1988
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001989 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001990
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001991 This is a factory method which allows subclasses to define the precise
1992 type of socket they want. The default implementation creates a TCP socket
1993 (:const:`socket.SOCK_STREAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001994
1995
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001996 .. method:: makePickle(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001997
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001998 Pickles the record's attribute dictionary in binary format with a length
1999 prefix, and returns it ready for transmission across the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002000
2001
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002002 .. method:: send(packet)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002003
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002004 Send a pickled string *packet* to the socket. This function allows for
2005 partial sends which can happen when the network is busy.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002006
2007
Vinay Sajip4b782332009-01-19 06:49:19 +00002008.. _datagram-handler:
2009
Georg Brandl8ec7f652007-08-15 14:28:01 +00002010DatagramHandler
2011^^^^^^^^^^^^^^^
2012
2013The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2014module, inherits from :class:`SocketHandler` to support sending logging messages
2015over UDP sockets.
2016
2017
2018.. class:: DatagramHandler(host, port)
2019
2020 Returns a new instance of the :class:`DatagramHandler` class intended to
2021 communicate with a remote machine whose address is given by *host* and *port*.
2022
2023
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002024 .. method:: emit()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002025
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002026 Pickles the record's attribute dictionary and writes it to the socket in
2027 binary format. If there is an error with the socket, silently drops the
2028 packet. To unpickle the record at the receiving end into a
2029 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002030
2031
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002032 .. method:: makeSocket()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002033
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002034 The factory method of :class:`SocketHandler` is here overridden to create
2035 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036
2037
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002038 .. method:: send(s)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002039
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002040 Send a pickled string to a socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002041
2042
Vinay Sajip4b782332009-01-19 06:49:19 +00002043.. _syslog-handler:
2044
Georg Brandl8ec7f652007-08-15 14:28:01 +00002045SysLogHandler
2046^^^^^^^^^^^^^
2047
2048The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2049supports sending logging messages to a remote or local Unix syslog.
2050
2051
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002052.. class:: SysLogHandler([address[, facility[, socktype]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002053
2054 Returns a new instance of the :class:`SysLogHandler` class intended to
2055 communicate with a remote Unix machine whose address is given by *address* in
2056 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002057 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl8ec7f652007-08-15 14:28:01 +00002058 alternative to providing a ``(host, port)`` tuple is providing an address as a
2059 string, for example "/dev/log". In this case, a Unix domain socket is used to
2060 send the message to the syslog. If *facility* is not specified,
Vinay Sajip1c77b7f2009-10-10 20:32:36 +00002061 :const:`LOG_USER` is used. The type of socket opened depends on the
2062 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2063 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2064 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2065
2066 .. versionchanged:: 2.7
2067 *socktype* was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002068
2069
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002070 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002071
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002072 Closes the socket to the remote host.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002073
2074
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002075 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002076
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002077 The record is formatted, and then sent to the syslog server. If exception
2078 information is present, it is *not* sent to the server.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002079
2080
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002081 .. method:: encodePriority(facility, priority)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002082
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002083 Encodes the facility and priority into an integer. You can pass in strings
2084 or integers - if strings are passed, internal mapping dictionaries are
2085 used to convert them to integers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002086
Vinay Sajipa3c39c02010-03-24 15:10:40 +00002087 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2088 mirror the values defined in the ``sys/syslog.h`` header file.
Vinay Sajipb0623d62010-03-24 14:31:21 +00002089
Georg Brandld3bab6a2010-04-02 09:03:18 +00002090 **Priorities**
2091
Vinay Sajipb0623d62010-03-24 14:31:21 +00002092 +--------------------------+---------------+
2093 | Name (string) | Symbolic value|
2094 +==========================+===============+
2095 | ``alert`` | LOG_ALERT |
2096 +--------------------------+---------------+
2097 | ``crit`` or ``critical`` | LOG_CRIT |
2098 +--------------------------+---------------+
2099 | ``debug`` | LOG_DEBUG |
2100 +--------------------------+---------------+
2101 | ``emerg`` or ``panic`` | LOG_EMERG |
2102 +--------------------------+---------------+
2103 | ``err`` or ``error`` | LOG_ERR |
2104 +--------------------------+---------------+
2105 | ``info`` | LOG_INFO |
2106 +--------------------------+---------------+
2107 | ``notice`` | LOG_NOTICE |
2108 +--------------------------+---------------+
2109 | ``warn`` or ``warning`` | LOG_WARNING |
2110 +--------------------------+---------------+
2111
Georg Brandld3bab6a2010-04-02 09:03:18 +00002112 **Facilities**
2113
Vinay Sajipb0623d62010-03-24 14:31:21 +00002114 +---------------+---------------+
2115 | Name (string) | Symbolic value|
2116 +===============+===============+
2117 | ``auth`` | LOG_AUTH |
2118 +---------------+---------------+
2119 | ``authpriv`` | LOG_AUTHPRIV |
2120 +---------------+---------------+
2121 | ``cron`` | LOG_CRON |
2122 +---------------+---------------+
2123 | ``daemon`` | LOG_DAEMON |
2124 +---------------+---------------+
2125 | ``ftp`` | LOG_FTP |
2126 +---------------+---------------+
2127 | ``kern`` | LOG_KERN |
2128 +---------------+---------------+
2129 | ``lpr`` | LOG_LPR |
2130 +---------------+---------------+
2131 | ``mail`` | LOG_MAIL |
2132 +---------------+---------------+
2133 | ``news`` | LOG_NEWS |
2134 +---------------+---------------+
2135 | ``syslog`` | LOG_SYSLOG |
2136 +---------------+---------------+
2137 | ``user`` | LOG_USER |
2138 +---------------+---------------+
2139 | ``uucp`` | LOG_UUCP |
2140 +---------------+---------------+
2141 | ``local0`` | LOG_LOCAL0 |
2142 +---------------+---------------+
2143 | ``local1`` | LOG_LOCAL1 |
2144 +---------------+---------------+
2145 | ``local2`` | LOG_LOCAL2 |
2146 +---------------+---------------+
2147 | ``local3`` | LOG_LOCAL3 |
2148 +---------------+---------------+
2149 | ``local4`` | LOG_LOCAL4 |
2150 +---------------+---------------+
2151 | ``local5`` | LOG_LOCAL5 |
2152 +---------------+---------------+
2153 | ``local6`` | LOG_LOCAL6 |
2154 +---------------+---------------+
2155 | ``local7`` | LOG_LOCAL7 |
2156 +---------------+---------------+
2157
Vinay Sajip66d19e22010-03-24 17:36:35 +00002158 .. method:: mapPriority(levelname)
2159
2160 Maps a logging level name to a syslog priority name.
2161 You may need to override this if you are using custom levels, or
2162 if the default algorithm is not suitable for your needs. The
2163 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2164 ``CRITICAL`` to the equivalent syslog names, and all other level
2165 names to "warning".
Georg Brandl8ec7f652007-08-15 14:28:01 +00002166
Vinay Sajip4b782332009-01-19 06:49:19 +00002167.. _nt-eventlog-handler:
2168
Georg Brandl8ec7f652007-08-15 14:28:01 +00002169NTEventLogHandler
2170^^^^^^^^^^^^^^^^^
2171
2172The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2173module, supports sending logging messages to a local Windows NT, Windows 2000 or
2174Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2175extensions for Python installed.
2176
2177
2178.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
2179
2180 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2181 used to define the application name as it appears in the event log. An
2182 appropriate registry entry is created using this name. The *dllname* should give
2183 the fully qualified pathname of a .dll or .exe which contains message
2184 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2185 - this is installed with the Win32 extensions and contains some basic
2186 placeholder message definitions. Note that use of these placeholders will make
2187 your event logs big, as the entire message source is held in the log. If you
2188 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2189 contains the message definitions you want to use in the event log). The
2190 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2191 defaults to ``'Application'``.
2192
2193
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002194 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002195
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002196 At this point, you can remove the application name from the registry as a
2197 source of event log entries. However, if you do this, you will not be able
2198 to see the events as you intended in the Event Log Viewer - it needs to be
2199 able to access the registry to get the .dll name. The current version does
Vinay Sajipaa5f8732008-09-01 17:44:14 +00002200 not do this.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002201
2202
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002203 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002204
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002205 Determines the message ID, event category and event type, and then logs
2206 the message in the NT event log.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002207
2208
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002209 .. method:: getEventCategory(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002210
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002211 Returns the event category for the record. Override this if you want to
2212 specify your own categories. This version returns 0.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002213
2214
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002215 .. method:: getEventType(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002216
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002217 Returns the event type for the record. Override this if you want to
2218 specify your own types. This version does a mapping using the handler's
2219 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2220 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2221 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2222 your own levels, you will either need to override this method or place a
2223 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002224
2225
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002226 .. method:: getMessageID(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002227
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002228 Returns the message ID for the record. If you are using your own messages,
2229 you could do this by having the *msg* passed to the logger being an ID
2230 rather than a format string. Then, in here, you could use a dictionary
2231 lookup to get the message ID. This version returns 1, which is the base
2232 message ID in :file:`win32service.pyd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002233
Vinay Sajip4b782332009-01-19 06:49:19 +00002234.. _smtp-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002235
2236SMTPHandler
2237^^^^^^^^^^^
2238
2239The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2240supports sending logging messages to an email address via SMTP.
2241
2242
2243.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
2244
2245 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2246 initialized with the from and to addresses and subject line of the email. The
2247 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2248 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2249 the standard SMTP port is used. If your SMTP server requires authentication, you
2250 can specify a (username, password) tuple for the *credentials* argument.
2251
2252 .. versionchanged:: 2.6
2253 *credentials* was added.
2254
2255
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002256 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002257
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002258 Formats the record and sends it to the specified addressees.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002259
2260
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002261 .. method:: getSubject(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002262
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002263 If you want to specify a subject line which is record-dependent, override
2264 this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002265
Vinay Sajip4b782332009-01-19 06:49:19 +00002266.. _memory-handler:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002267
2268MemoryHandler
2269^^^^^^^^^^^^^
2270
2271The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2272supports buffering of logging records in memory, periodically flushing them to a
2273:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2274event of a certain severity or greater is seen.
2275
2276:class:`MemoryHandler` is a subclass of the more general
2277:class:`BufferingHandler`, which is an abstract class. This buffers logging
2278records in memory. Whenever each record is added to the buffer, a check is made
2279by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2280should, then :meth:`flush` is expected to do the needful.
2281
2282
2283.. class:: BufferingHandler(capacity)
2284
2285 Initializes the handler with a buffer of the specified capacity.
2286
2287
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002288 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002289
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002290 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2291 calls :meth:`flush` to process the buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002292
2293
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002294 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002295
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002296 You can override this to implement custom flushing behavior. This version
2297 just zaps the buffer to empty.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002298
2299
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002300 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002301
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002302 Returns true if the buffer is up to capacity. This method can be
2303 overridden to implement custom flushing strategies.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002304
2305
2306.. class:: MemoryHandler(capacity[, flushLevel [, target]])
2307
2308 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2309 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2310 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2311 set using :meth:`setTarget` before this handler does anything useful.
2312
2313
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002314 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002315
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002316 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2317 buffer.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002318
2319
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002320 .. method:: flush()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002321
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002322 For a :class:`MemoryHandler`, flushing means just sending the buffered
2323 records to the target, if there is one. Override if you want different
2324 behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002325
2326
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002327 .. method:: setTarget(target)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002328
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002329 Sets the target handler for this handler.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002330
2331
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002332 .. method:: shouldFlush(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002333
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002334 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002335
2336
Vinay Sajip4b782332009-01-19 06:49:19 +00002337.. _http-handler:
2338
Georg Brandl8ec7f652007-08-15 14:28:01 +00002339HTTPHandler
2340^^^^^^^^^^^
2341
2342The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2343supports sending logging messages to a Web server, using either ``GET`` or
2344``POST`` semantics.
2345
2346
2347.. class:: HTTPHandler(host, url[, method])
2348
2349 Returns a new instance of the :class:`HTTPHandler` class. The instance is
2350 initialized with a host address, url and HTTP method. The *host* can be of the
2351 form ``host:port``, should you need to use a specific port number. If no
2352 *method* is specified, ``GET`` is used.
2353
2354
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002355 .. method:: emit(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002356
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002357 Sends the record to the Web server as an URL-encoded dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002358
2359
Vinay Sajip4b782332009-01-19 06:49:19 +00002360.. _formatter:
Georg Brandlc37f2882007-12-04 17:46:27 +00002361
Georg Brandl8ec7f652007-08-15 14:28:01 +00002362Formatter Objects
2363-----------------
2364
Georg Brandl430effb2009-01-01 13:05:13 +00002365.. currentmodule:: logging
2366
Georg Brandl8ec7f652007-08-15 14:28:01 +00002367:class:`Formatter`\ s have the following attributes and methods. They are
2368responsible for converting a :class:`LogRecord` to (usually) a string which can
2369be interpreted by either a human or an external system. The base
2370:class:`Formatter` allows a formatting string to be specified. If none is
2371supplied, the default value of ``'%(message)s'`` is used.
2372
2373A Formatter can be initialized with a format string which makes use of knowledge
2374of the :class:`LogRecord` attributes - such as the default value mentioned above
2375making use of the fact that the user's message and arguments are pre-formatted
2376into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti062d2b52009-12-19 22:41:49 +00002377standard Python %-style mapping keys. See section :ref:`string-formatting`
Georg Brandl8ec7f652007-08-15 14:28:01 +00002378for more information on string formatting.
2379
2380Currently, the useful mapping keys in a :class:`LogRecord` are:
2381
2382+-------------------------+-----------------------------------------------+
2383| Format | Description |
2384+=========================+===============================================+
2385| ``%(name)s`` | Name of the logger (logging channel). |
2386+-------------------------+-----------------------------------------------+
2387| ``%(levelno)s`` | Numeric logging level for the message |
2388| | (:const:`DEBUG`, :const:`INFO`, |
2389| | :const:`WARNING`, :const:`ERROR`, |
2390| | :const:`CRITICAL`). |
2391+-------------------------+-----------------------------------------------+
2392| ``%(levelname)s`` | Text logging level for the message |
2393| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2394| | ``'ERROR'``, ``'CRITICAL'``). |
2395+-------------------------+-----------------------------------------------+
2396| ``%(pathname)s`` | Full pathname of the source file where the |
2397| | logging call was issued (if available). |
2398+-------------------------+-----------------------------------------------+
2399| ``%(filename)s`` | Filename portion of pathname. |
2400+-------------------------+-----------------------------------------------+
2401| ``%(module)s`` | Module (name portion of filename). |
2402+-------------------------+-----------------------------------------------+
2403| ``%(funcName)s`` | Name of function containing the logging call. |
2404+-------------------------+-----------------------------------------------+
2405| ``%(lineno)d`` | Source line number where the logging call was |
2406| | issued (if available). |
2407+-------------------------+-----------------------------------------------+
2408| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2409| | (as returned by :func:`time.time`). |
2410+-------------------------+-----------------------------------------------+
2411| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2412| | created, relative to the time the logging |
2413| | module was loaded. |
2414+-------------------------+-----------------------------------------------+
2415| ``%(asctime)s`` | Human-readable time when the |
2416| | :class:`LogRecord` was created. By default |
2417| | this is of the form "2003-07-08 16:49:45,896" |
2418| | (the numbers after the comma are millisecond |
2419| | portion of the time). |
2420+-------------------------+-----------------------------------------------+
2421| ``%(msecs)d`` | Millisecond portion of the time when the |
2422| | :class:`LogRecord` was created. |
2423+-------------------------+-----------------------------------------------+
2424| ``%(thread)d`` | Thread ID (if available). |
2425+-------------------------+-----------------------------------------------+
2426| ``%(threadName)s`` | Thread name (if available). |
2427+-------------------------+-----------------------------------------------+
2428| ``%(process)d`` | Process ID (if available). |
2429+-------------------------+-----------------------------------------------+
2430| ``%(message)s`` | The logged message, computed as ``msg % |
2431| | args``. |
2432+-------------------------+-----------------------------------------------+
2433
2434.. versionchanged:: 2.5
2435 *funcName* was added.
2436
2437
2438.. class:: Formatter([fmt[, datefmt]])
2439
2440 Returns a new instance of the :class:`Formatter` class. The instance is
2441 initialized with a format string for the message as a whole, as well as a format
2442 string for the date/time portion of a message. If no *fmt* is specified,
2443 ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
2444 is used.
2445
2446
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002447 .. method:: format(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002448
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002449 The record's attribute dictionary is used as the operand to a string
2450 formatting operation. Returns the resulting string. Before formatting the
2451 dictionary, a couple of preparatory steps are carried out. The *message*
2452 attribute of the record is computed using *msg* % *args*. If the
2453 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
2454 to format the event time. If there is exception information, it is
2455 formatted using :meth:`formatException` and appended to the message. Note
2456 that the formatted exception information is cached in attribute
2457 *exc_text*. This is useful because the exception information can be
2458 pickled and sent across the wire, but you should be careful if you have
2459 more than one :class:`Formatter` subclass which customizes the formatting
2460 of exception information. In this case, you will have to clear the cached
2461 value after a formatter has done its formatting, so that the next
2462 formatter to handle the event doesn't use the cached value but
2463 recalculates it afresh.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002464
2465
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002466 .. method:: formatTime(record[, datefmt])
Georg Brandl8ec7f652007-08-15 14:28:01 +00002467
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002468 This method should be called from :meth:`format` by a formatter which
2469 wants to make use of a formatted time. This method can be overridden in
2470 formatters to provide for any specific requirement, but the basic behavior
2471 is as follows: if *datefmt* (a string) is specified, it is used with
2472 :func:`time.strftime` to format the creation time of the
2473 record. Otherwise, the ISO8601 format is used. The resulting string is
2474 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002475
2476
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002477 .. method:: formatException(exc_info)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002478
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002479 Formats the specified exception information (a standard exception tuple as
2480 returned by :func:`sys.exc_info`) as a string. This default implementation
2481 just uses :func:`traceback.print_exception`. The resulting string is
2482 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002483
Vinay Sajip4b782332009-01-19 06:49:19 +00002484.. _filter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002485
2486Filter Objects
2487--------------
2488
Vinay Sajip4b782332009-01-19 06:49:19 +00002489Filters can be used by :class:`Handler`\ s and :class:`Logger`\ s for
Georg Brandl8ec7f652007-08-15 14:28:01 +00002490more sophisticated filtering than is provided by levels. The base filter class
2491only allows events which are below a certain point in the logger hierarchy. For
2492example, a filter initialized with "A.B" will allow events logged by loggers
2493"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
2494initialized with the empty string, all events are passed.
2495
2496
2497.. class:: Filter([name])
2498
2499 Returns an instance of the :class:`Filter` class. If *name* is specified, it
2500 names a logger which, together with its children, will have its events allowed
2501 through the filter. If no name is specified, allows every event.
2502
2503
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002504 .. method:: filter(record)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002505
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002506 Is the specified record to be logged? Returns zero for no, nonzero for
2507 yes. If deemed appropriate, the record may be modified in-place by this
2508 method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002509
Vinay Sajip4b782332009-01-19 06:49:19 +00002510.. _log-record:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002511
2512LogRecord Objects
2513-----------------
2514
2515:class:`LogRecord` instances are created every time something is logged. They
2516contain all the information pertinent to the event being logged. The main
2517information passed in is in msg and args, which are combined using msg % args to
2518create the message field of the record. The record also includes information
2519such as when the record was created, the source line where the logging call was
2520made, and any exception information to be logged.
2521
2522
2523.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
2524
2525 Returns an instance of :class:`LogRecord` initialized with interesting
2526 information. The *name* is the logger name; *lvl* is the numeric level;
2527 *pathname* is the absolute pathname of the source file in which the logging
2528 call was made; *lineno* is the line number in that file where the logging
2529 call is found; *msg* is the user-supplied message (a format string); *args*
2530 is the tuple which, together with *msg*, makes up the user message; and
2531 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
2532 (or :const:`None`, if no exception information is available). The *func* is
2533 the name of the function from which the logging call was made. If not
2534 specified, it defaults to ``None``.
2535
2536 .. versionchanged:: 2.5
2537 *func* was added.
2538
2539
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002540 .. method:: getMessage()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002541
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002542 Returns the message for this :class:`LogRecord` instance after merging any
2543 user-supplied arguments with the message.
2544
Vinay Sajip4b782332009-01-19 06:49:19 +00002545.. _logger-adapter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002546
Vinay Sajipc7403352008-01-18 15:54:14 +00002547LoggerAdapter Objects
2548---------------------
2549
2550.. versionadded:: 2.6
2551
2552:class:`LoggerAdapter` instances are used to conveniently pass contextual
Vinay Sajip733024a2008-01-21 17:39:22 +00002553information into logging calls. For a usage example , see the section on
2554`adding contextual information to your logging output`__.
2555
2556__ context-info_
Vinay Sajipc7403352008-01-18 15:54:14 +00002557
2558.. class:: LoggerAdapter(logger, extra)
2559
2560 Returns an instance of :class:`LoggerAdapter` initialized with an
2561 underlying :class:`Logger` instance and a dict-like object.
2562
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002563 .. method:: process(msg, kwargs)
Vinay Sajipc7403352008-01-18 15:54:14 +00002564
Benjamin Petersonc7b05922008-04-25 01:29:10 +00002565 Modifies the message and/or keyword arguments passed to a logging call in
2566 order to insert contextual information. This implementation takes the object
2567 passed as *extra* to the constructor and adds it to *kwargs* using key
2568 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2569 (possibly modified) versions of the arguments passed in.
Vinay Sajipc7403352008-01-18 15:54:14 +00002570
2571In addition to the above, :class:`LoggerAdapter` supports all the logging
2572methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2573:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2574methods have the same signatures as their counterparts in :class:`Logger`, so
2575you can use the two types of instances interchangeably.
2576
Vinay Sajip804899b2010-03-22 15:29:01 +00002577.. versionchanged:: 2.7
2578
2579The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method
2580delegates to the underlying logger.
2581
Georg Brandl8ec7f652007-08-15 14:28:01 +00002582
2583Thread Safety
2584-------------
2585
2586The logging module is intended to be thread-safe without any special work
2587needing to be done by its clients. It achieves this though using threading
2588locks; there is one lock to serialize access to the module's shared data, and
2589each handler also creates a lock to serialize access to its underlying I/O.
2590
Vinay Sajip353a85f2009-04-03 21:58:16 +00002591If you are implementing asynchronous signal handlers using the :mod:`signal`
2592module, you may not be able to use logging from within such handlers. This is
2593because lock implementations in the :mod:`threading` module are not always
2594re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002595
Vinay Sajip61afd262010-02-19 23:53:17 +00002596
2597Integration with the warnings module
2598------------------------------------
2599
2600The :func:`captureWarnings` function can be used to integrate :mod:`logging`
2601with the :mod:`warnings` module.
2602
2603.. function:: captureWarnings(capture)
2604
2605 This function is used to turn the capture of warnings by logging on and
2606 off.
2607
Georg Brandlf6d367452010-03-12 10:02:03 +00002608 If *capture* is ``True``, warnings issued by the :mod:`warnings` module
Vinay Sajip61afd262010-02-19 23:53:17 +00002609 will be redirected to the logging system. Specifically, a warning will be
2610 formatted using :func:`warnings.formatwarning` and the resulting string
Georg Brandlf6d367452010-03-12 10:02:03 +00002611 logged to a logger named "py.warnings" with a severity of ``WARNING``.
Vinay Sajip61afd262010-02-19 23:53:17 +00002612
Georg Brandlf6d367452010-03-12 10:02:03 +00002613 If *capture* is ``False``, the redirection of warnings to the logging system
Vinay Sajip61afd262010-02-19 23:53:17 +00002614 will stop, and warnings will be redirected to their original destinations
Georg Brandlf6d367452010-03-12 10:02:03 +00002615 (i.e. those in effect before ``captureWarnings(True)`` was called).
Vinay Sajip61afd262010-02-19 23:53:17 +00002616
2617
Georg Brandl8ec7f652007-08-15 14:28:01 +00002618Configuration
2619-------------
2620
2621
2622.. _logging-config-api:
2623
2624Configuration functions
2625^^^^^^^^^^^^^^^^^^^^^^^
2626
Georg Brandl8ec7f652007-08-15 14:28:01 +00002627The following functions configure the logging module. They are located in the
2628:mod:`logging.config` module. Their use is optional --- you can configure the
2629logging module using these functions or by making calls to the main API (defined
2630in :mod:`logging` itself) and defining handlers which are declared either in
2631:mod:`logging` or :mod:`logging.handlers`.
2632
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002633.. function:: dictConfig(config)
2634
2635 Takes the logging configuration from a dictionary. The contents of
2636 this dictionary are described in :ref:`logging-config-dictschema`
2637 below.
2638
2639 If an error is encountered during configuration, this function will
2640 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
2641 or :exc:`ImportError` with a suitably descriptive message. The
2642 following is a (possibly incomplete) list of conditions which will
2643 raise an error:
2644
2645 * A ``level`` which is not a string or which is a string not
2646 corresponding to an actual logging level.
2647 * A ``propagate`` value which is not a boolean.
2648 * An id which does not have a corresponding destination.
2649 * A non-existent handler id found during an incremental call.
2650 * An invalid logger name.
2651 * Inability to resolve to an internal or external object.
2652
2653 Parsing is performed by the :class:`DictConfigurator` class, whose
2654 constructor is passed the dictionary used for configuration, and
2655 has a :meth:`configure` method. The :mod:`logging.config` module
2656 has a callable attribute :attr:`dictConfigClass`
2657 which is initially set to :class:`DictConfigurator`.
2658 You can replace the value of :attr:`dictConfigClass` with a
2659 suitable implementation of your own.
2660
2661 :func:`dictConfig` calls :attr:`dictConfigClass` passing
2662 the specified dictionary, and then calls the :meth:`configure` method on
2663 the returned object to put the configuration into effect::
2664
2665 def dictConfig(config):
2666 dictConfigClass(config).configure()
2667
2668 For example, a subclass of :class:`DictConfigurator` could call
2669 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
2670 set up custom prefixes which would be usable in the subsequent
2671 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
2672 this new subclass, and then :func:`dictConfig` could be called exactly as
2673 in the default, uncustomized state.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002674
2675.. function:: fileConfig(fname[, defaults])
2676
Vinay Sajip51104862009-01-02 18:53:04 +00002677 Reads the logging configuration from a :mod:`ConfigParser`\-format file named
2678 *fname*. This function can be called several times from an application,
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002679 allowing an end user to select from various pre-canned
Vinay Sajip51104862009-01-02 18:53:04 +00002680 configurations (if the developer provides a mechanism to present the choices
2681 and load the chosen configuration). Defaults to be passed to the ConfigParser
2682 can be specified in the *defaults* argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002683
Georg Brandl8ec7f652007-08-15 14:28:01 +00002684.. function:: listen([port])
2685
2686 Starts up a socket server on the specified port, and listens for new
2687 configurations. If no port is specified, the module's default
2688 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
2689 sent as a file suitable for processing by :func:`fileConfig`. Returns a
2690 :class:`Thread` instance on which you can call :meth:`start` to start the
2691 server, and which you can :meth:`join` when appropriate. To stop the server,
Georg Brandlc37f2882007-12-04 17:46:27 +00002692 call :func:`stopListening`.
2693
2694 To send a configuration to the socket, read in the configuration file and
2695 send it to the socket as a string of bytes preceded by a four-byte length
2696 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002697
2698
2699.. function:: stopListening()
2700
Georg Brandlc37f2882007-12-04 17:46:27 +00002701 Stops the listening server which was created with a call to :func:`listen`.
2702 This is typically called before calling :meth:`join` on the return value from
Georg Brandl8ec7f652007-08-15 14:28:01 +00002703 :func:`listen`.
2704
2705
Andrew M. Kuchlingf09bc662010-05-12 18:56:48 +00002706.. _logging-config-dictschema:
2707
2708Configuration dictionary schema
2709^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2710
2711Describing a logging configuration requires listing the various
2712objects to create and the connections between them; for example, you
2713may create a handler named "console" and then say that the logger
2714named "startup" will send its messages to the "console" handler.
2715These objects aren't limited to those provided by the :mod:`logging`
2716module because you might write your own formatter or handler class.
2717The parameters to these classes may also need to include external
2718objects such as ``sys.stderr``. The syntax for describing these
2719objects and connections is defined in :ref:`logging-config-dict-connections`
2720below.
2721
2722Dictionary Schema Details
2723"""""""""""""""""""""""""
2724
2725The dictionary passed to :func:`dictConfig` must contain the following
2726keys:
2727
2728* `version` - to be set to an integer value representing the schema
2729 version. The only valid value at present is 1, but having this key
2730 allows the schema to evolve while still preserving backwards
2731 compatibility.
2732
2733All other keys are optional, but if present they will be interpreted
2734as described below. In all cases below where a 'configuring dict' is
2735mentioned, it will be checked for the special ``'()'`` key to see if a
2736custom instantiation is required. If so, the mechanism described
2737above is used to instantiate; otherwise, the context is used to
2738determine how to instantiate.
2739
2740* `formatters` - the corresponding value will be a dict in which each
2741 key is a formatter id and each value is a dict describing how to
2742 configure the corresponding Formatter instance.
2743
2744 The configuring dict is searched for keys ``format`` and ``datefmt``
2745 (with defaults of ``None``) and these are used to construct a
2746 :class:`logging.Formatter` instance.
2747
2748* `filters` - the corresponding value will be a dict in which each key
2749 is a filter id and each value is a dict describing how to configure
2750 the corresponding Filter instance.
2751
2752 The configuring dict is searched for the key ``name`` (defaulting to the
2753 empty string) and this is used to construct a :class:`logging.Filter`
2754 instance.
2755
2756* `handlers` - the corresponding value will be a dict in which each
2757 key is a handler id and each value is a dict describing how to
2758 configure the corresponding Handler instance.
2759
2760 The configuring dict is searched for the following keys:
2761
2762 * ``class`` (mandatory). This is the fully qualified name of the
2763 handler class.
2764
2765 * ``level`` (optional). The level of the handler.
2766
2767 * ``formatter`` (optional). The id of the formatter for this
2768 handler.
2769
2770 * ``filters`` (optional). A list of ids of the filters for this
2771 handler.
2772
2773 All *other* keys are passed through as keyword arguments to the
2774 handler's constructor. For example, given the snippet::
2775
2776 handlers:
2777 console:
2778 class : logging.StreamHandler
2779 formatter: brief
2780 level : INFO
2781 filters: [allow_foo]
2782 stream : ext://sys.stdout
2783 file:
2784 class : logging.handlers.RotatingFileHandler
2785 formatter: precise
2786 filename: logconfig.log
2787 maxBytes: 1024
2788 backupCount: 3
2789
2790 the handler with id ``console`` is instantiated as a
2791 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
2792 stream. The handler with id ``file`` is instantiated as a
2793 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
2794 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
2795
2796* `loggers` - the corresponding value will be a dict in which each key
2797 is a logger name and each value is a dict describing how to
2798 configure the corresponding Logger instance.
2799
2800 The configuring dict is searched for the following keys:
2801
2802 * ``level`` (optional). The level of the logger.
2803
2804 * ``propagate`` (optional). The propagation setting of the logger.
2805
2806 * ``filters`` (optional). A list of ids of the filters for this
2807 logger.
2808
2809 * ``handlers`` (optional). A list of ids of the handlers for this
2810 logger.
2811
2812 The specified loggers will be configured according to the level,
2813 propagation, filters and handlers specified.
2814
2815* `root` - this will be the configuration for the root logger.
2816 Processing of the configuration will be as for any logger, except
2817 that the ``propagate`` setting will not be applicable.
2818
2819* `incremental` - whether the configuration is to be interpreted as
2820 incremental to the existing configuration. This value defaults to
2821 ``False``, which means that the specified configuration replaces the
2822 existing configuration with the same semantics as used by the
2823 existing :func:`fileConfig` API.
2824
2825 If the specified value is ``True``, the configuration is processed
2826 as described in the section on :ref:`logging-config-dict-incremental`.
2827
2828* `disable_existing_loggers` - whether any existing loggers are to be
2829 disabled. This setting mirrors the parameter of the same name in
2830 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
2831 This value is ignored if `incremental` is ``True``.
2832
2833.. _logging-config-dict-incremental:
2834
2835Incremental Configuration
2836"""""""""""""""""""""""""
2837
2838It is difficult to provide complete flexibility for incremental
2839configuration. For example, because objects such as filters
2840and formatters are anonymous, once a configuration is set up, it is
2841not possible to refer to such anonymous objects when augmenting a
2842configuration.
2843
2844Furthermore, there is not a compelling case for arbitrarily altering
2845the object graph of loggers, handlers, filters, formatters at
2846run-time, once a configuration is set up; the verbosity of loggers and
2847handlers can be controlled just by setting levels (and, in the case of
2848loggers, propagation flags). Changing the object graph arbitrarily in
2849a safe way is problematic in a multi-threaded environment; while not
2850impossible, the benefits are not worth the complexity it adds to the
2851implementation.
2852
2853Thus, when the ``incremental`` key of a configuration dict is present
2854and is ``True``, the system will completely ignore any ``formatters`` and
2855``filters`` entries, and process only the ``level``
2856settings in the ``handlers`` entries, and the ``level`` and
2857``propagate`` settings in the ``loggers`` and ``root`` entries.
2858
2859Using a value in the configuration dict lets configurations to be sent
2860over the wire as pickled dicts to a socket listener. Thus, the logging
2861verbosity of a long-running application can be altered over time with
2862no need to stop and restart the application.
2863
2864.. _logging-config-dict-connections:
2865
2866Object connections
2867""""""""""""""""""
2868
2869The schema describes a set of logging objects - loggers,
2870handlers, formatters, filters - which are connected to each other in
2871an object graph. Thus, the schema needs to represent connections
2872between the objects. For example, say that, once configured, a
2873particular logger has attached to it a particular handler. For the
2874purposes of this discussion, we can say that the logger represents the
2875source, and the handler the destination, of a connection between the
2876two. Of course in the configured objects this is represented by the
2877logger holding a reference to the handler. In the configuration dict,
2878this is done by giving each destination object an id which identifies
2879it unambiguously, and then using the id in the source object's
2880configuration to indicate that a connection exists between the source
2881and the destination object with that id.
2882
2883So, for example, consider the following YAML snippet::
2884
2885 formatters:
2886 brief:
2887 # configuration for formatter with id 'brief' goes here
2888 precise:
2889 # configuration for formatter with id 'precise' goes here
2890 handlers:
2891 h1: #This is an id
2892 # configuration of handler with id 'h1' goes here
2893 formatter: brief
2894 h2: #This is another id
2895 # configuration of handler with id 'h2' goes here
2896 formatter: precise
2897 loggers:
2898 foo.bar.baz:
2899 # other configuration for logger 'foo.bar.baz'
2900 handlers: [h1, h2]
2901
2902(Note: YAML used here because it's a little more readable than the
2903equivalent Python source form for the dictionary.)
2904
2905The ids for loggers are the logger names which would be used
2906programmatically to obtain a reference to those loggers, e.g.
2907``foo.bar.baz``. The ids for Formatters and Filters can be any string
2908value (such as ``brief``, ``precise`` above) and they are transient,
2909in that they are only meaningful for processing the configuration
2910dictionary and used to determine connections between objects, and are
2911not persisted anywhere when the configuration call is complete.
2912
2913The above snippet indicates that logger named ``foo.bar.baz`` should
2914have two handlers attached to it, which are described by the handler
2915ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
2916``brief``, and the formatter for ``h2`` is that described by id
2917``precise``.
2918
2919
2920.. _logging-config-dict-userdef:
2921
2922User-defined objects
2923""""""""""""""""""""
2924
2925The schema supports user-defined objects for handlers, filters and
2926formatters. (Loggers do not need to have different types for
2927different instances, so there is no support in this configuration
2928schema for user-defined logger classes.)
2929
2930Objects to be configured are described by dictionaries
2931which detail their configuration. In some places, the logging system
2932will be able to infer from the context how an object is to be
2933instantiated, but when a user-defined object is to be instantiated,
2934the system will not know how to do this. In order to provide complete
2935flexibility for user-defined object instantiation, the user needs
2936to provide a 'factory' - a callable which is called with a
2937configuration dictionary and which returns the instantiated object.
2938This is signalled by an absolute import path to the factory being
2939made available under the special key ``'()'``. Here's a concrete
2940example::
2941
2942 formatters:
2943 brief:
2944 format: '%(message)s'
2945 default:
2946 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
2947 datefmt: '%Y-%m-%d %H:%M:%S'
2948 custom:
2949 (): my.package.customFormatterFactory
2950 bar: baz
2951 spam: 99.9
2952 answer: 42
2953
2954The above YAML snippet defines three formatters. The first, with id
2955``brief``, is a standard :class:`logging.Formatter` instance with the
2956specified format string. The second, with id ``default``, has a
2957longer format and also defines the time format explicitly, and will
2958result in a :class:`logging.Formatter` initialized with those two format
2959strings. Shown in Python source form, the ``brief`` and ``default``
2960formatters have configuration sub-dictionaries::
2961
2962 {
2963 'format' : '%(message)s'
2964 }
2965
2966and::
2967
2968 {
2969 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
2970 'datefmt' : '%Y-%m-%d %H:%M:%S'
2971 }
2972
2973respectively, and as these dictionaries do not contain the special key
2974``'()'``, the instantiation is inferred from the context: as a result,
2975standard :class:`logging.Formatter` instances are created. The
2976configuration sub-dictionary for the third formatter, with id
2977``custom``, is::
2978
2979 {
2980 '()' : 'my.package.customFormatterFactory',
2981 'bar' : 'baz',
2982 'spam' : 99.9,
2983 'answer' : 42
2984 }
2985
2986and this contains the special key ``'()'``, which means that
2987user-defined instantiation is wanted. In this case, the specified
2988factory callable will be used. If it is an actual callable it will be
2989used directly - otherwise, if you specify a string (as in the example)
2990the actual callable will be located using normal import mechanisms.
2991The callable will be called with the **remaining** items in the
2992configuration sub-dictionary as keyword arguments. In the above
2993example, the formatter with id ``custom`` will be assumed to be
2994returned by the call::
2995
2996 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
2997
2998The key ``'()'`` has been used as the special key because it is not a
2999valid keyword parameter name, and so will not clash with the names of
3000the keyword arguments used in the call. The ``'()'`` also serves as a
3001mnemonic that the corresponding value is a callable.
3002
3003
3004.. _logging-config-dict-externalobj:
3005
3006Access to external objects
3007""""""""""""""""""""""""""
3008
3009There are times where a configuration needs to refer to objects
3010external to the configuration, for example ``sys.stderr``. If the
3011configuration dict is constructed using Python code, this is
3012straightforward, but a problem arises when the configuration is
3013provided via a text file (e.g. JSON, YAML). In a text file, there is
3014no standard way to distinguish ``sys.stderr`` from the literal string
3015``'sys.stderr'``. To facilitate this distinction, the configuration
3016system looks for certain special prefixes in string values and
3017treat them specially. For example, if the literal string
3018``'ext://sys.stderr'`` is provided as a value in the configuration,
3019then the ``ext://`` will be stripped off and the remainder of the
3020value processed using normal import mechanisms.
3021
3022The handling of such prefixes is done in a way analogous to protocol
3023handling: there is a generic mechanism to look for prefixes which
3024match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3025whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3026in a prefix-dependent manner and the result of the processing replaces
3027the string value. If the prefix is not recognised, then the string
3028value will be left as-is.
3029
3030
3031.. _logging-config-dict-internalobj:
3032
3033Access to internal objects
3034""""""""""""""""""""""""""
3035
3036As well as external objects, there is sometimes also a need to refer
3037to objects in the configuration. This will be done implicitly by the
3038configuration system for things that it knows about. For example, the
3039string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3040automatically be converted to the value ``logging.DEBUG``, and the
3041``handlers``, ``filters`` and ``formatter`` entries will take an
3042object id and resolve to the appropriate destination object.
3043
3044However, a more generic mechanism is needed for user-defined
3045objects which are not known to the :mod:`logging` module. For
3046example, consider :class:`logging.handlers.MemoryHandler`, which takes
3047a ``target`` argument which is another handler to delegate to. Since
3048the system already knows about this class, then in the configuration,
3049the given ``target`` just needs to be the object id of the relevant
3050target handler, and the system will resolve to the handler from the
3051id. If, however, a user defines a ``my.package.MyHandler`` which has
3052an ``alternate`` handler, the configuration system would not know that
3053the ``alternate`` referred to a handler. To cater for this, a generic
3054resolution system allows the user to specify::
3055
3056 handlers:
3057 file:
3058 # configuration of file handler goes here
3059
3060 custom:
3061 (): my.package.MyHandler
3062 alternate: cfg://handlers.file
3063
3064The literal string ``'cfg://handlers.file'`` will be resolved in an
3065analogous way to strings with the ``ext://`` prefix, but looking
3066in the configuration itself rather than the import namespace. The
3067mechanism allows access by dot or by index, in a similar way to
3068that provided by ``str.format``. Thus, given the following snippet::
3069
3070 handlers:
3071 email:
3072 class: logging.handlers.SMTPHandler
3073 mailhost: localhost
3074 fromaddr: my_app@domain.tld
3075 toaddrs:
3076 - support_team@domain.tld
3077 - dev_team@domain.tld
3078 subject: Houston, we have a problem.
3079
3080in the configuration, the string ``'cfg://handlers'`` would resolve to
3081the dict with key ``handlers``, the string ``'cfg://handlers.email``
3082would resolve to the dict with key ``email`` in the ``handlers`` dict,
3083and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3084resolve to ``'dev_team.domain.tld'`` and the string
3085``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3086``'support_team@domain.tld'``. The ``subject`` value could be accessed
3087using either ``'cfg://handlers.email.subject'`` or, equivalently,
3088``'cfg://handlers.email[subject]'``. The latter form only needs to be
3089used if the key contains spaces or non-alphanumeric characters. If an
3090index value consists only of decimal digits, access will be attempted
3091using the corresponding integer value, falling back to the string
3092value if needed.
3093
3094Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3095resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3096If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3097the system will attempt to retrieve the value from
3098``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3099to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3100fails.
3101
Georg Brandl8ec7f652007-08-15 14:28:01 +00003102.. _logging-config-fileformat:
3103
3104Configuration file format
3105^^^^^^^^^^^^^^^^^^^^^^^^^
3106
Georg Brandl392c6fc2008-05-25 07:25:25 +00003107The configuration file format understood by :func:`fileConfig` is based on
Vinay Sajip51104862009-01-02 18:53:04 +00003108:mod:`ConfigParser` functionality. The file must contain sections called
3109``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3110entities of each type which are defined in the file. For each such entity,
3111there is a separate section which identifies how that entity is configured.
3112Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant
3113configuration details are held in a section ``[logger_log01]``. Similarly, a
3114handler called ``hand01`` in the ``[handlers]`` section will have its
3115configuration held in a section called ``[handler_hand01]``, while a formatter
3116called ``form01`` in the ``[formatters]`` section will have its configuration
3117specified in a section called ``[formatter_form01]``. The root logger
3118configuration must be specified in a section called ``[logger_root]``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003119
3120Examples of these sections in the file are given below. ::
3121
3122 [loggers]
3123 keys=root,log02,log03,log04,log05,log06,log07
3124
3125 [handlers]
3126 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3127
3128 [formatters]
3129 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3130
3131The root logger must specify a level and a list of handlers. An example of a
3132root logger section is given below. ::
3133
3134 [logger_root]
3135 level=NOTSET
3136 handlers=hand01
3137
3138The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3139``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3140logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3141package's namespace.
3142
3143The ``handlers`` entry is a comma-separated list of handler names, which must
3144appear in the ``[handlers]`` section. These names must appear in the
3145``[handlers]`` section and have corresponding sections in the configuration
3146file.
3147
3148For loggers other than the root logger, some additional information is required.
3149This is illustrated by the following example. ::
3150
3151 [logger_parser]
3152 level=DEBUG
3153 handlers=hand01
3154 propagate=1
3155 qualname=compiler.parser
3156
3157The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3158except that if a non-root logger's level is specified as ``NOTSET``, the system
3159consults loggers higher up the hierarchy to determine the effective level of the
3160logger. The ``propagate`` entry is set to 1 to indicate that messages must
3161propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3162indicate that messages are **not** propagated to handlers up the hierarchy. The
3163``qualname`` entry is the hierarchical channel name of the logger, that is to
3164say the name used by the application to get the logger.
3165
3166Sections which specify handler configuration are exemplified by the following.
3167::
3168
3169 [handler_hand01]
3170 class=StreamHandler
3171 level=NOTSET
3172 formatter=form01
3173 args=(sys.stdout,)
3174
3175The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3176in the ``logging`` package's namespace). The ``level`` is interpreted as for
3177loggers, and ``NOTSET`` is taken to mean "log everything".
3178
Vinay Sajip2a649f92008-07-18 09:00:35 +00003179.. versionchanged:: 2.6
3180 Added support for resolving the handler's class as a dotted module and class
3181 name.
3182
Georg Brandl8ec7f652007-08-15 14:28:01 +00003183The ``formatter`` entry indicates the key name of the formatter for this
3184handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3185If a name is specified, it must appear in the ``[formatters]`` section and have
3186a corresponding section in the configuration file.
3187
3188The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3189package's namespace, is the list of arguments to the constructor for the handler
3190class. Refer to the constructors for the relevant handlers, or to the examples
3191below, to see how typical entries are constructed. ::
3192
3193 [handler_hand02]
3194 class=FileHandler
3195 level=DEBUG
3196 formatter=form02
3197 args=('python.log', 'w')
3198
3199 [handler_hand03]
3200 class=handlers.SocketHandler
3201 level=INFO
3202 formatter=form03
3203 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3204
3205 [handler_hand04]
3206 class=handlers.DatagramHandler
3207 level=WARN
3208 formatter=form04
3209 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3210
3211 [handler_hand05]
3212 class=handlers.SysLogHandler
3213 level=ERROR
3214 formatter=form05
3215 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3216
3217 [handler_hand06]
3218 class=handlers.NTEventLogHandler
3219 level=CRITICAL
3220 formatter=form06
3221 args=('Python Application', '', 'Application')
3222
3223 [handler_hand07]
3224 class=handlers.SMTPHandler
3225 level=WARN
3226 formatter=form07
3227 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3228
3229 [handler_hand08]
3230 class=handlers.MemoryHandler
3231 level=NOTSET
3232 formatter=form08
3233 target=
3234 args=(10, ERROR)
3235
3236 [handler_hand09]
3237 class=handlers.HTTPHandler
3238 level=NOTSET
3239 formatter=form09
3240 args=('localhost:9022', '/log', 'GET')
3241
3242Sections which specify formatter configuration are typified by the following. ::
3243
3244 [formatter_form01]
3245 format=F1 %(asctime)s %(levelname)s %(message)s
3246 datefmt=
3247 class=logging.Formatter
3248
3249The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Georg Brandlb19be572007-12-29 10:57:00 +00003250the :func:`strftime`\ -compatible date/time format string. If empty, the
3251package substitutes ISO8601 format date/times, which is almost equivalent to
3252specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3253also specifies milliseconds, which are appended to the result of using the above
3254format string, with a comma separator. An example time in ISO8601 format is
3255``2003-01-23 00:29:50,411``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003256
3257The ``class`` entry is optional. It indicates the name of the formatter's class
3258(as a dotted module and class name.) This option is useful for instantiating a
3259:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3260exception tracebacks in an expanded or condensed format.
3261
Georg Brandlc37f2882007-12-04 17:46:27 +00003262
3263Configuration server example
3264^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3265
3266Here is an example of a module using the logging configuration server::
3267
3268 import logging
3269 import logging.config
3270 import time
3271 import os
3272
3273 # read initial config file
3274 logging.config.fileConfig("logging.conf")
3275
3276 # create and start listener on port 9999
3277 t = logging.config.listen(9999)
3278 t.start()
3279
3280 logger = logging.getLogger("simpleExample")
3281
3282 try:
3283 # loop through logging calls to see the difference
3284 # new configurations make, until Ctrl+C is pressed
3285 while True:
3286 logger.debug("debug message")
3287 logger.info("info message")
3288 logger.warn("warn message")
3289 logger.error("error message")
3290 logger.critical("critical message")
3291 time.sleep(5)
3292 except KeyboardInterrupt:
3293 # cleanup
3294 logging.config.stopListening()
3295 t.join()
3296
3297And here is a script that takes a filename and sends that file to the server,
3298properly preceded with the binary-encoded length, as the new logging
3299configuration::
3300
3301 #!/usr/bin/env python
Benjamin Petersona7b55a32009-02-20 03:31:23 +00003302 import socket, sys, struct
Georg Brandlc37f2882007-12-04 17:46:27 +00003303
3304 data_to_send = open(sys.argv[1], "r").read()
3305
3306 HOST = 'localhost'
3307 PORT = 9999
3308 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3309 print "connecting..."
3310 s.connect((HOST, PORT))
3311 print "sending config..."
3312 s.send(struct.pack(">L", len(data_to_send)))
3313 s.send(data_to_send)
3314 s.close()
3315 print "complete"
3316
3317
3318More examples
3319-------------
3320
3321Multiple handlers and formatters
3322^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3323
3324Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3325or maximum quota for the number of handlers you may add. Sometimes it will be
3326beneficial for an application to log all messages of all severities to a text
3327file while simultaneously logging errors or above to the console. To set this
3328up, simply configure the appropriate handlers. The logging calls in the
3329application code will remain unchanged. Here is a slight modification to the
3330previous simple module-based configuration example::
3331
3332 import logging
3333
3334 logger = logging.getLogger("simple_example")
3335 logger.setLevel(logging.DEBUG)
3336 # create file handler which logs even debug messages
3337 fh = logging.FileHandler("spam.log")
3338 fh.setLevel(logging.DEBUG)
3339 # create console handler with a higher log level
3340 ch = logging.StreamHandler()
3341 ch.setLevel(logging.ERROR)
3342 # create formatter and add it to the handlers
3343 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3344 ch.setFormatter(formatter)
3345 fh.setFormatter(formatter)
3346 # add the handlers to logger
3347 logger.addHandler(ch)
3348 logger.addHandler(fh)
3349
3350 # "application" code
3351 logger.debug("debug message")
3352 logger.info("info message")
3353 logger.warn("warn message")
3354 logger.error("error message")
3355 logger.critical("critical message")
3356
3357Notice that the "application" code does not care about multiple handlers. All
3358that changed was the addition and configuration of a new handler named *fh*.
3359
3360The ability to create new handlers with higher- or lower-severity filters can be
3361very helpful when writing and testing an application. Instead of using many
3362``print`` statements for debugging, use ``logger.debug``: Unlike the print
3363statements, which you will have to delete or comment out later, the logger.debug
3364statements can remain intact in the source code and remain dormant until you
3365need them again. At that time, the only change that needs to happen is to
3366modify the severity level of the logger and/or handler to debug.
3367
3368
3369Using logging in multiple modules
3370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3371
3372It was mentioned above that multiple calls to
3373``logging.getLogger('someLogger')`` return a reference to the same logger
3374object. This is true not only within the same module, but also across modules
3375as long as it is in the same Python interpreter process. It is true for
3376references to the same object; additionally, application code can define and
3377configure a parent logger in one module and create (but not configure) a child
3378logger in a separate module, and all logger calls to the child will pass up to
3379the parent. Here is a main module::
3380
3381 import logging
3382 import auxiliary_module
3383
3384 # create logger with "spam_application"
3385 logger = logging.getLogger("spam_application")
3386 logger.setLevel(logging.DEBUG)
3387 # create file handler which logs even debug messages
3388 fh = logging.FileHandler("spam.log")
3389 fh.setLevel(logging.DEBUG)
3390 # create console handler with a higher log level
3391 ch = logging.StreamHandler()
3392 ch.setLevel(logging.ERROR)
3393 # create formatter and add it to the handlers
3394 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3395 fh.setFormatter(formatter)
3396 ch.setFormatter(formatter)
3397 # add the handlers to the logger
3398 logger.addHandler(fh)
3399 logger.addHandler(ch)
3400
3401 logger.info("creating an instance of auxiliary_module.Auxiliary")
3402 a = auxiliary_module.Auxiliary()
3403 logger.info("created an instance of auxiliary_module.Auxiliary")
3404 logger.info("calling auxiliary_module.Auxiliary.do_something")
3405 a.do_something()
3406 logger.info("finished auxiliary_module.Auxiliary.do_something")
3407 logger.info("calling auxiliary_module.some_function()")
3408 auxiliary_module.some_function()
3409 logger.info("done with auxiliary_module.some_function()")
3410
3411Here is the auxiliary module::
3412
3413 import logging
3414
3415 # create logger
3416 module_logger = logging.getLogger("spam_application.auxiliary")
3417
3418 class Auxiliary:
3419 def __init__(self):
3420 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
3421 self.logger.info("creating an instance of Auxiliary")
3422 def do_something(self):
3423 self.logger.info("doing something")
3424 a = 1 + 1
3425 self.logger.info("done doing something")
3426
3427 def some_function():
3428 module_logger.info("received a call to \"some_function\"")
3429
3430The output looks like this::
3431
Vinay Sajipe28fa292008-01-07 15:30:36 +00003432 2005-03-23 23:47:11,663 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003433 creating an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003434 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003435 creating an instance of Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003436 2005-03-23 23:47:11,665 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003437 created an instance of auxiliary_module.Auxiliary
Vinay Sajipe28fa292008-01-07 15:30:36 +00003438 2005-03-23 23:47:11,668 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003439 calling auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003440 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003441 doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003442 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003443 done doing something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003444 2005-03-23 23:47:11,670 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003445 finished auxiliary_module.Auxiliary.do_something
Vinay Sajipe28fa292008-01-07 15:30:36 +00003446 2005-03-23 23:47:11,671 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003447 calling auxiliary_module.some_function()
Vinay Sajipe28fa292008-01-07 15:30:36 +00003448 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003449 received a call to "some_function"
Vinay Sajipe28fa292008-01-07 15:30:36 +00003450 2005-03-23 23:47:11,673 - spam_application - INFO -
Georg Brandlc37f2882007-12-04 17:46:27 +00003451 done with auxiliary_module.some_function()
3452