blob: 98c6bbf0957c2c130772d76a3ffd608aca72d700 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
17Logging is performed by calling methods on instances of the :class:`Logger`
18class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +000019conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +000020separators. For example, a logger named "scan" is the parent of loggers
21"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
22and indicate the area of an application in which a logged message originates.
23
24Logged messages also have levels of importance associated with them. The default
25levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
26:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
27importance of a logged message by calling an appropriate method of
28:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
29:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
30constrained to use these levels: you can specify your own and use a more general
31:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
32
Christian Heimes8b0facf2007-12-04 19:30:01 +000033
34Logging tutorial
35----------------
36
37The key benefit of having the logging API provided by a standard library module
38is that all Python modules can participate in logging, so your application log
39can include messages from third-party modules.
40
41It is, of course, possible to log messages with different verbosity levels or to
42different destinations. Support for writing log messages to files, HTTP
43GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
Christian Heimesc3f30c42008-02-22 16:37:40 +000044mechanisms are all supported by the standard module. You can also create your
Christian Heimes8b0facf2007-12-04 19:30:01 +000045own log destination class if you have special requirements not met by any of the
46built-in classes.
47
48Simple examples
49^^^^^^^^^^^^^^^
50
51.. sectionauthor:: Doug Hellmann
52.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
53
54Most applications are probably going to want to log to a file, so let's start
55with that case. Using the :func:`basicConfig` function, we can set up the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056default handler so that debug messages are written to a file (in the example,
57we assume that you have the appropriate permissions to create a file called
58*example.log* in the current directory)::
Christian Heimes8b0facf2007-12-04 19:30:01 +000059
60 import logging
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000061 LOG_FILENAME = 'example.log'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000062 logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
Christian Heimes8b0facf2007-12-04 19:30:01 +000063
64 logging.debug('This message should go to the log file')
65
66And now if we open the file and look at what we have, we should find the log
67message::
68
69 DEBUG:root:This message should go to the log file
70
71If you run the script repeatedly, the additional log messages are appended to
Eric Smith5c01a8d2009-06-04 18:20:51 +000072the file. To create a new file each time, you can pass a *filemode* argument to
Christian Heimes8b0facf2007-12-04 19:30:01 +000073:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
74yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75
76 import glob
77 import logging
78 import logging.handlers
79
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000080 LOG_FILENAME = 'logging_rotatingfile_example.out'
Christian Heimes8b0facf2007-12-04 19:30:01 +000081
82 # Set up a specific logger with our desired output level
83 my_logger = logging.getLogger('MyLogger')
84 my_logger.setLevel(logging.DEBUG)
85
86 # Add the log message handler to the logger
87 handler = logging.handlers.RotatingFileHandler(
88 LOG_FILENAME, maxBytes=20, backupCount=5)
89
90 my_logger.addHandler(handler)
91
92 # Log some messages
93 for i in range(20):
94 my_logger.debug('i = %d' % i)
95
96 # See what files are created
97 logfiles = glob.glob('%s*' % LOG_FILENAME)
98
99 for filename in logfiles:
Georg Brandlf6945182008-02-01 11:56:49 +0000100 print(filename)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000101
102The result should be 6 separate files, each with part of the log history for the
103application::
104
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000105 logging_rotatingfile_example.out
106 logging_rotatingfile_example.out.1
107 logging_rotatingfile_example.out.2
108 logging_rotatingfile_example.out.3
109 logging_rotatingfile_example.out.4
110 logging_rotatingfile_example.out.5
Christian Heimes8b0facf2007-12-04 19:30:01 +0000111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112The most current file is always :file:`logging_rotatingfile_example.out`,
Christian Heimes8b0facf2007-12-04 19:30:01 +0000113and each time it reaches the size limit it is renamed with the suffix
114``.1``. Each of the existing backup files is renamed to increment the suffix
Eric Smith5c01a8d2009-06-04 18:20:51 +0000115(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000116
117Obviously this example sets the log length much much too small as an extreme
118example. You would want to set *maxBytes* to an appropriate value.
119
120Another useful feature of the logging API is the ability to produce different
121messages at different log levels. This allows you to instrument your code with
122debug messages, for example, but turning the log level down so that those debug
123messages are not written for your production system. The default levels are
Vinay Sajipb6d065f2009-10-28 23:28:16 +0000124``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000125
126The logger, handler, and log message call each specify a level. The log message
127is only emitted if the handler and logger are configured to emit messages of
128that level or lower. For example, if a message is ``CRITICAL``, and the logger
129is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
130the logger is set to produce only ``ERROR``\s, the message is not emitted::
131
132 import logging
133 import sys
134
135 LEVELS = {'debug': logging.DEBUG,
136 'info': logging.INFO,
137 'warning': logging.WARNING,
138 'error': logging.ERROR,
139 'critical': logging.CRITICAL}
140
141 if len(sys.argv) > 1:
142 level_name = sys.argv[1]
143 level = LEVELS.get(level_name, logging.NOTSET)
144 logging.basicConfig(level=level)
145
146 logging.debug('This is a debug message')
147 logging.info('This is an info message')
148 logging.warning('This is a warning message')
149 logging.error('This is an error message')
150 logging.critical('This is a critical error message')
151
152Run the script with an argument like 'debug' or 'warning' to see which messages
153show up at different levels::
154
155 $ python logging_level_example.py debug
156 DEBUG:root:This is a debug message
157 INFO:root:This is an info message
158 WARNING:root:This is a warning message
159 ERROR:root:This is an error message
160 CRITICAL:root:This is a critical error message
161
162 $ python logging_level_example.py info
163 INFO:root:This is an info message
164 WARNING:root:This is a warning message
165 ERROR:root:This is an error message
166 CRITICAL:root:This is a critical error message
167
168You will notice that these log messages all have ``root`` embedded in them. The
169logging module supports a hierarchy of loggers with different names. An easy
170way to tell where a specific log message comes from is to use a separate logger
171object for each of your modules. Each new logger "inherits" the configuration
172of its parent, and log messages sent to a logger include the name of that
173logger. Optionally, each logger can be configured differently, so that messages
174from different modules are handled in different ways. Let's look at a simple
175example of how to log from different modules so it is easy to trace the source
176of the message::
177
178 import logging
179
180 logging.basicConfig(level=logging.WARNING)
181
182 logger1 = logging.getLogger('package1.module1')
183 logger2 = logging.getLogger('package2.module2')
184
185 logger1.warning('This message comes from one module')
186 logger2.warning('And this message comes from another module')
187
188And the output::
189
190 $ python logging_modules_example.py
191 WARNING:package1.module1:This message comes from one module
192 WARNING:package2.module2:And this message comes from another module
193
194There are many more options for configuring logging, including different log
195message formatting options, having messages delivered to multiple destinations,
196and changing the configuration of a long-running application on the fly using a
197socket interface. All of these options are covered in depth in the library
198module documentation.
199
200Loggers
201^^^^^^^
202
203The logging library takes a modular approach and offers the several categories
204of components: loggers, handlers, filters, and formatters. Loggers expose the
205interface that application code directly uses. Handlers send the log records to
206the appropriate destination. Filters provide a finer grained facility for
207determining which log records to send on to a handler. Formatters specify the
208layout of the resultant log record.
209
210:class:`Logger` objects have a threefold job. First, they expose several
211methods to application code so that applications can log messages at runtime.
212Second, logger objects determine which log messages to act upon based upon
213severity (the default filtering facility) or filter objects. Third, logger
214objects pass along relevant log messages to all interested log handlers.
215
216The most widely used methods on logger objects fall into two categories:
217configuration and message sending.
218
219* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220 will handle, where debug is the lowest built-in severity level and critical is
221 the highest built-in severity. For example, if the severity level is info,
222 the logger will handle only info, warning, error, and critical messages and
223 will ignore debug messages.
224
225* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226 objects from the logger object. This tutorial does not address filters.
227
228With the logger object configured, the following methods create log messages:
229
230* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232 a message and a level that corresponds to their respective method names. The
233 message is actually a format string, which may contain the standard string
234 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
235 rest of their arguments is a list of objects that correspond with the
236 substitution fields in the message. With regard to :const:`**kwargs`, the
237 logging methods care only about a keyword of :const:`exc_info` and use it to
238 determine whether to log exception information.
239
240* :meth:`Logger.exception` creates a log message similar to
241 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
242 stack trace along with it. Call this method only from an exception handler.
243
244* :meth:`Logger.log` takes a log level as an explicit argument. This is a
245 little more verbose for logging messages than using the log level convenience
246 methods listed above, but this is how to log at custom log levels.
247
Christian Heimesdcca98d2008-02-25 13:19:43 +0000248:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000249name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000250hierarchical structures. Multiple calls to :func:`getLogger` with the same name
251will return a reference to the same logger object. Loggers that are further
252down in the hierarchical list are children of loggers higher up in the list.
253For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000254``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
255Child loggers propagate messages up to the handlers associated with their
256ancestor loggers. Because of this, it is unnecessary to define and configure
257handlers for all the loggers an application uses. It is sufficient to
258configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000259
260
261Handlers
262^^^^^^^^
263
264:class:`Handler` objects are responsible for dispatching the appropriate log
265messages (based on the log messages' severity) to the handler's specified
266destination. Logger objects can add zero or more handler objects to themselves
267with an :func:`addHandler` method. As an example scenario, an application may
268want to send all log messages to a log file, all log messages of error or higher
269to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000270requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000271messages of a specific severity to a specific location.
272
273The standard library includes quite a few handler types; this tutorial uses only
274:class:`StreamHandler` and :class:`FileHandler` in its examples.
275
276There are very few methods in a handler for application developers to concern
277themselves with. The only handler methods that seem relevant for application
278developers who are using the built-in handler objects (that is, not creating
279custom handlers) are the following configuration methods:
280
281* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282 lowest severity that will be dispatched to the appropriate destination. Why
283 are there two :func:`setLevel` methods? The level set in the logger
284 determines which severity of messages it will pass to its handlers. The level
285 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000286
287* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000288
289* :func:`addFilter` and :func:`removeFilter` respectively configure and
290 deconfigure filter objects on handlers.
291
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292Application code should not directly instantiate and use instances of
293:class:`Handler`. Instead, the :class:`Handler` class is a base class that
294defines the interface that all handlers should have and establishes some
295default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000296
297
298Formatters
299^^^^^^^^^^
300
301Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000302message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000303instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000304if your application needs special behavior. The constructor takes three
305optional arguments -- a message format string, a date format string and a style
306indicator.
307
308.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
309
310If there is no message format string, the default is to use the
311raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000312
313 %Y-%m-%d %H:%M:%S
314
Vinay Sajipa39c5712010-10-25 13:57:39 +0000315with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
316or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000317
Vinay Sajipa39c5712010-10-25 13:57:39 +0000318If the ``style`` is '%', the message format string uses
319``%(<dictionary key>)s`` styled string substitution; the possible keys are
320documented in :ref:`formatter-objects`. If the style is '{', the message format
321string is assumed to be compatible with :meth:`str.format` (using keyword
322arguments), while if the style is '$' then the message format string should
323conform to what is expected by :meth:`string.Template.substitute`.
324
325.. versionchanged:: 3.2
326 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000327
328The following message format string will log the time in a human-readable
329format, the severity of the message, and the contents of the message, in that
330order::
331
332 "%(asctime)s - %(levelname)s - %(message)s"
333
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000334Formatters use a user-configurable function to convert the creation time of a
335record to a tuple. By default, :func:`time.localtime` is used; to change this
336for a particular formatter instance, set the ``converter`` attribute of the
337instance to a function with the same signature as :func:`time.localtime` or
338:func:`time.gmtime`. To change it for all formatters, for example if you want
339all logging times to be shown in GMT, set the ``converter`` attribute in the
340Formatter class (to ``time.gmtime`` for GMT display).
341
Christian Heimes8b0facf2007-12-04 19:30:01 +0000342
343Configuring Logging
344^^^^^^^^^^^^^^^^^^^
345
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000346Programmers can configure logging in three ways:
347
3481. Creating loggers, handlers, and formatters explicitly using Python
349 code that calls the configuration methods listed above.
3502. Creating a logging config file and reading it using the :func:`fileConfig`
351 function.
3523. Creating a dictionary of configuration information and passing it
353 to the :func:`dictConfig` function.
354
355The following example configures a very simple logger, a console
356handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000357
358 import logging
359
360 # create logger
361 logger = logging.getLogger("simple_example")
362 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000363
Christian Heimes8b0facf2007-12-04 19:30:01 +0000364 # create console handler and set level to debug
365 ch = logging.StreamHandler()
366 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000367
Christian Heimes8b0facf2007-12-04 19:30:01 +0000368 # create formatter
369 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000370
Christian Heimes8b0facf2007-12-04 19:30:01 +0000371 # add formatter to ch
372 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000373
Christian Heimes8b0facf2007-12-04 19:30:01 +0000374 # add ch to logger
375 logger.addHandler(ch)
376
377 # "application" code
378 logger.debug("debug message")
379 logger.info("info message")
380 logger.warn("warn message")
381 logger.error("error message")
382 logger.critical("critical message")
383
384Running this module from the command line produces the following output::
385
386 $ python simple_logging_module.py
387 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
388 2005-03-19 15:10:26,620 - simple_example - INFO - info message
389 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
390 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
391 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
392
393The following Python module creates a logger, handler, and formatter nearly
394identical to those in the example listed above, with the only difference being
395the names of the objects::
396
397 import logging
398 import logging.config
399
400 logging.config.fileConfig("logging.conf")
401
402 # create logger
403 logger = logging.getLogger("simpleExample")
404
405 # "application" code
406 logger.debug("debug message")
407 logger.info("info message")
408 logger.warn("warn message")
409 logger.error("error message")
410 logger.critical("critical message")
411
412Here is the logging.conf file::
413
414 [loggers]
415 keys=root,simpleExample
416
417 [handlers]
418 keys=consoleHandler
419
420 [formatters]
421 keys=simpleFormatter
422
423 [logger_root]
424 level=DEBUG
425 handlers=consoleHandler
426
427 [logger_simpleExample]
428 level=DEBUG
429 handlers=consoleHandler
430 qualname=simpleExample
431 propagate=0
432
433 [handler_consoleHandler]
434 class=StreamHandler
435 level=DEBUG
436 formatter=simpleFormatter
437 args=(sys.stdout,)
438
439 [formatter_simpleFormatter]
440 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
441 datefmt=
442
443The output is nearly identical to that of the non-config-file-based example::
444
445 $ python simple_logging_config.py
446 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
447 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
448 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
449 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
450 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
451
452You can see that the config file approach has a few advantages over the Python
453code approach, mainly separation of configuration and code and the ability of
454noncoders to easily modify the logging properties.
455
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000456Note that the class names referenced in config files need to be either relative
457to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000458import mechanisms. Thus, you could use either
459:class:`handlers.WatchedFileHandler` (relative to the logging module) or
460``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
461and module ``mymodule``, where ``mypackage`` is available on the Python import
462path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000463
Benjamin Peterson56894b52010-06-28 00:16:12 +0000464In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000465dictionaries to hold configuration information. This provides a superset of the
466functionality of the config-file-based approach outlined above, and is the
467recommended configuration method for new applications and deployments. Because
468a Python dictionary is used to hold configuration information, and since you
469can populate that dictionary using different means, you have more options for
470configuration. For example, you can use a configuration file in JSON format,
471or, if you have access to YAML processing functionality, a file in YAML
472format, to populate the configuration dictionary. Or, of course, you can
473construct the dictionary in Python code, receive it in pickled form over a
474socket, or use whatever approach makes sense for your application.
475
476Here's an example of the same configuration as above, in YAML format for
477the new dictionary-based approach::
478
479 version: 1
480 formatters:
481 simple:
482 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
483 handlers:
484 console:
485 class: logging.StreamHandler
486 level: DEBUG
487 formatter: simple
488 stream: ext://sys.stdout
489 loggers:
490 simpleExample:
491 level: DEBUG
492 handlers: [console]
493 propagate: no
494 root:
495 level: DEBUG
496 handlers: [console]
497
498For more information about logging using a dictionary, see
499:ref:`logging-config-api`.
500
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000501.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000502
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000503Configuring Logging for a Library
504^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
505
506When developing a library which uses logging, some consideration needs to be
507given to its configuration. If the using application does not use logging, and
508library code makes logging calls, then a one-off message "No handlers could be
509found for logger X.Y.Z" is printed to the console. This message is intended
510to catch mistakes in logging configuration, but will confuse an application
511developer who is not aware of logging by the library.
512
513In addition to documenting how a library uses logging, a good way to configure
514library logging so that it does not cause a spurious message is to add a
515handler which does nothing. This avoids the message being printed, since a
516handler will be found: it just doesn't produce any output. If the library user
517configures logging for application use, presumably that configuration will add
518some handlers, and if levels are suitably configured then logging calls made
519in library code will send output to those handlers, as normal.
520
521A do-nothing handler can be simply defined as follows::
522
523 import logging
524
525 class NullHandler(logging.Handler):
526 def emit(self, record):
527 pass
528
529An instance of this handler should be added to the top-level logger of the
530logging namespace used by the library. If all logging by a library *foo* is
531done using loggers with names matching "foo.x.y", then the code::
532
533 import logging
534
535 h = NullHandler()
536 logging.getLogger("foo").addHandler(h)
537
538should have the desired effect. If an organisation produces a number of
539libraries, then the logger name specified can be "orgname.foo" rather than
540just "foo".
541
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000542**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
543than* :class:`NullHandler` *to your library's loggers*. This is because the
544configuration of handlers is the prerogative of the application developer who
545uses your library. The application developer knows their target audience and
546what handlers are most appropriate for their application: if you add handlers
547"under the hood", you might well interfere with their ability to carry out
548unit tests and deliver logs which suit their requirements.
549
Georg Brandlf9734072008-12-07 15:30:06 +0000550.. versionadded:: 3.1
Vinay Sajip4039aff2010-09-11 10:25:28 +0000551
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000552The :class:`NullHandler` class was not present in previous versions, but is
553now included, so that it need not be defined in library code.
Georg Brandlf9734072008-12-07 15:30:06 +0000554
555
Christian Heimes8b0facf2007-12-04 19:30:01 +0000556
557Logging Levels
558--------------
559
Georg Brandl116aa622007-08-15 14:28:22 +0000560The numeric values of logging levels are given in the following table. These are
561primarily of interest if you want to define your own levels, and need them to
562have specific values relative to the predefined levels. If you define a level
563with the same numeric value, it overwrites the predefined value; the predefined
564name is lost.
565
566+--------------+---------------+
567| Level | Numeric value |
568+==============+===============+
569| ``CRITICAL`` | 50 |
570+--------------+---------------+
571| ``ERROR`` | 40 |
572+--------------+---------------+
573| ``WARNING`` | 30 |
574+--------------+---------------+
575| ``INFO`` | 20 |
576+--------------+---------------+
577| ``DEBUG`` | 10 |
578+--------------+---------------+
579| ``NOTSET`` | 0 |
580+--------------+---------------+
581
582Levels can also be associated with loggers, being set either by the developer or
583through loading a saved logging configuration. When a logging method is called
584on a logger, the logger compares its own level with the level associated with
585the method call. If the logger's level is higher than the method call's, no
586logging message is actually generated. This is the basic mechanism controlling
587the verbosity of logging output.
588
589Logging messages are encoded as instances of the :class:`LogRecord` class. When
590a logger decides to actually log an event, a :class:`LogRecord` instance is
591created from the logging message.
592
593Logging messages are subjected to a dispatch mechanism through the use of
594:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
595class. Handlers are responsible for ensuring that a logged message (in the form
596of a :class:`LogRecord`) ends up in a particular location (or set of locations)
597which is useful for the target audience for that message (such as end users,
598support desk staff, system administrators, developers). Handlers are passed
599:class:`LogRecord` instances intended for particular destinations. Each logger
600can have zero, one or more handlers associated with it (via the
601:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
602directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000603of the logger* are called to dispatch the message (unless the *propagate* flag
604for a logger is set to a false value, at which point the passing to ancestor
605handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607Just as for loggers, handlers can have levels associated with them. A handler's
608level acts as a filter in the same way as a logger's level does. If a handler
609decides to actually dispatch an event, the :meth:`emit` method is used to send
610the message to its destination. Most user-defined subclasses of :class:`Handler`
611will need to override this :meth:`emit`.
612
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000613.. _custom-levels:
614
615Custom Levels
616^^^^^^^^^^^^^
617
618Defining your own levels is possible, but should not be necessary, as the
619existing levels have been chosen on the basis of practical experience.
620However, if you are convinced that you need custom levels, great care should
621be exercised when doing this, and it is possibly *a very bad idea to define
622custom levels if you are developing a library*. That's because if multiple
623library authors all define their own custom levels, there is a chance that
624the logging output from such multiple libraries used together will be
625difficult for the using developer to control and/or interpret, because a
626given numeric value might mean different things for different libraries.
627
628
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000629Useful Handlers
630---------------
631
Georg Brandl116aa622007-08-15 14:28:22 +0000632In addition to the base :class:`Handler` class, many useful subclasses are
633provided:
634
Vinay Sajip121a1c42010-09-08 10:46:15 +0000635#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000636 objects).
637
Vinay Sajip121a1c42010-09-08 10:46:15 +0000638#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000640.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000641
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000642#. :class:`BaseRotatingHandler` is the base class for handlers that
643 rotate log files at a certain point. It is not meant to be instantiated
644 directly. Instead, use :class:`RotatingFileHandler` or
645 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Vinay Sajip121a1c42010-09-08 10:46:15 +0000647#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000648 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Vinay Sajip121a1c42010-09-08 10:46:15 +0000650#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000651 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Vinay Sajip121a1c42010-09-08 10:46:15 +0000653#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000654 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Vinay Sajip121a1c42010-09-08 10:46:15 +0000656#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000657 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Vinay Sajip121a1c42010-09-08 10:46:15 +0000659#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000660 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Vinay Sajip121a1c42010-09-08 10:46:15 +0000662#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000663 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Vinay Sajip121a1c42010-09-08 10:46:15 +0000665#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000666 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Vinay Sajip121a1c42010-09-08 10:46:15 +0000668#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000669 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Vinay Sajip121a1c42010-09-08 10:46:15 +0000671#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000672 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000674#. :class:`WatchedFileHandler` instances watch the file they are
675 logging to. If the file changes, it is closed and reopened using the file
676 name. This handler is only useful on Unix-like systems; Windows does not
677 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000678
Vinay Sajip121a1c42010-09-08 10:46:15 +0000679#. :class:`QueueHandler` instances send messages to a queue, such as
680 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
681
Vinay Sajip30bf1222009-01-10 19:23:34 +0000682.. currentmodule:: logging
683
Georg Brandlf9734072008-12-07 15:30:06 +0000684#. :class:`NullHandler` instances do nothing with error messages. They are used
685 by library developers who want to use logging, but want to avoid the "No
686 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000687 the library user has not configured logging. See :ref:`library-config` for
688 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000689
690.. versionadded:: 3.1
691
692The :class:`NullHandler` class was not present in previous versions.
693
Vinay Sajip121a1c42010-09-08 10:46:15 +0000694.. versionadded:: 3.2
695
696The :class:`QueueHandler` class was not present in previous versions.
697
Vinay Sajipa17775f2008-12-30 07:32:59 +0000698The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
699classes are defined in the core logging package. The other handlers are
700defined in a sub- module, :mod:`logging.handlers`. (There is also another
701sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703Logged messages are formatted for presentation through instances of the
704:class:`Formatter` class. They are initialized with a format string suitable for
705use with the % operator and a dictionary.
706
707For formatting multiple messages in a batch, instances of
708:class:`BufferingFormatter` can be used. In addition to the format string (which
709is applied to each message in the batch), there is provision for header and
710trailer format strings.
711
712When filtering based on logger level and/or handler level is not enough,
713instances of :class:`Filter` can be added to both :class:`Logger` and
714:class:`Handler` instances (through their :meth:`addFilter` method). Before
715deciding to process a message further, both loggers and handlers consult all
716their filters for permission. If any filter returns a false value, the message
717is not processed further.
718
719The basic :class:`Filter` functionality allows filtering by specific logger
720name. If this feature is used, messages sent to the named logger and its
721children are allowed through the filter, and all others dropped.
722
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000723Module-Level Functions
724----------------------
725
Georg Brandl116aa622007-08-15 14:28:22 +0000726In addition to the classes described above, there are a number of module- level
727functions.
728
729
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000730.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000732 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000733 logger which is the root logger of the hierarchy. If specified, the name is
734 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
735 Choice of these names is entirely up to the developer who is using logging.
736
737 All calls to this function with a given name return the same logger instance.
738 This means that logger instances never need to be passed between different parts
739 of an application.
740
741
742.. function:: getLoggerClass()
743
744 Return either the standard :class:`Logger` class, or the last class passed to
745 :func:`setLoggerClass`. This function may be called from within a new class
746 definition, to ensure that installing a customised :class:`Logger` class will
747 not undo customisations already applied by other code. For example::
748
749 class MyLogger(logging.getLoggerClass()):
750 # ... override behaviour here
751
752
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000753.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
756 message format string, and the *args* are the arguments which are merged into
757 *msg* using the string formatting operator. (Note that this means that you can
758 use keywords in the format string, together with a single dictionary argument.)
759
760 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
761 which, if it does not evaluate as false, causes exception information to be
762 added to the logging message. If an exception tuple (in the format returned by
763 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
764 is called to get the exception information.
765
766 The other optional keyword argument is *extra* which can be used to pass a
767 dictionary which is used to populate the __dict__ of the LogRecord created for
768 the logging event with user-defined attributes. These custom attributes can then
769 be used as you like. For example, they could be incorporated into logged
770 messages. For example::
771
772 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
773 logging.basicConfig(format=FORMAT)
774 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
775 logging.warning("Protocol problem: %s", "connection reset", extra=d)
776
Vinay Sajip4039aff2010-09-11 10:25:28 +0000777 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000778
779 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
780
781 The keys in the dictionary passed in *extra* should not clash with the keys used
782 by the logging system. (See the :class:`Formatter` documentation for more
783 information on which keys are used by the logging system.)
784
785 If you choose to use these attributes in logged messages, you need to exercise
786 some care. In the above example, for instance, the :class:`Formatter` has been
787 set up with a format string which expects 'clientip' and 'user' in the attribute
788 dictionary of the LogRecord. If these are missing, the message will not be
789 logged because a string formatting exception will occur. So in this case, you
790 always need to pass the *extra* dictionary with these keys.
791
792 While this might be annoying, this feature is intended for use in specialized
793 circumstances, such as multi-threaded servers where the same code executes in
794 many contexts, and interesting conditions which arise are dependent on this
795 context (such as remote client IP address and authenticated user name, in the
796 above example). In such circumstances, it is likely that specialized
797 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
798
Georg Brandl116aa622007-08-15 14:28:22 +0000799
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000800.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000801
802 Logs a message with level :const:`INFO` on the root logger. The arguments are
803 interpreted as for :func:`debug`.
804
805
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000806.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808 Logs a message with level :const:`WARNING` on the root logger. The arguments are
809 interpreted as for :func:`debug`.
810
811
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000812.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000813
814 Logs a message with level :const:`ERROR` on the root logger. The arguments are
815 interpreted as for :func:`debug`.
816
817
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000818.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
821 are interpreted as for :func:`debug`.
822
823
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000824.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826 Logs a message with level :const:`ERROR` on the root logger. The arguments are
827 interpreted as for :func:`debug`. Exception info is added to the logging
828 message. This function should only be called from an exception handler.
829
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000830.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832 Logs a message with level *level* on the root logger. The other arguments are
833 interpreted as for :func:`debug`.
834
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000835 PLEASE NOTE: The above module-level functions which delegate to the root
836 logger should *not* be used in threads, in versions of Python earlier than
837 2.7.1 and 3.2, unless at least one handler has been added to the root
838 logger *before* the threads are started. These convenience functions call
839 :func:`basicConfig` to ensure that at least one handler is available; in
840 earlier versions of Python, this can (under rare circumstances) lead to
841 handlers being added multiple times to the root logger, which can in turn
842 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844.. function:: disable(lvl)
845
846 Provides an overriding level *lvl* for all loggers which takes precedence over
847 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +0000848 output down across the whole application, this function can be useful. Its
849 effect is to disable all logging calls of severity *lvl* and below, so that
850 if you call it with a value of INFO, then all INFO and DEBUG events would be
851 discarded, whereas those of severity WARNING and above would be processed
852 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +0000853
854
855.. function:: addLevelName(lvl, levelName)
856
857 Associates level *lvl* with text *levelName* in an internal dictionary, which is
858 used to map numeric levels to a textual representation, for example when a
859 :class:`Formatter` formats a message. This function can also be used to define
860 your own levels. The only constraints are that all levels used must be
861 registered using this function, levels should be positive integers and they
862 should increase in increasing order of severity.
863
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000864 NOTE: If you are thinking of defining your own levels, please see the section
865 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867.. function:: getLevelName(lvl)
868
869 Returns the textual representation of logging level *lvl*. If the level is one
870 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
871 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
872 have associated levels with names using :func:`addLevelName` then the name you
873 have associated with *lvl* is returned. If a numeric value corresponding to one
874 of the defined levels is passed in, the corresponding string representation is
875 returned. Otherwise, the string "Level %s" % lvl is returned.
876
877
878.. function:: makeLogRecord(attrdict)
879
880 Creates and returns a new :class:`LogRecord` instance whose attributes are
881 defined by *attrdict*. This function is useful for taking a pickled
882 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
883 it as a :class:`LogRecord` instance at the receiving end.
884
885
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000886.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000887
888 Does basic configuration for the logging system by creating a
889 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000890 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +0000891 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
892 if no handlers are defined for the root logger.
893
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000894 This function does nothing if the root logger already has handlers
895 configured for it.
896
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000897 PLEASE NOTE: This function should be called from the main thread
898 before other threads are started. In versions of Python prior to
899 2.7.1 and 3.2, if this function is called from multiple threads,
900 it is possible (in rare circumstances) that a handler will be added
901 to the root logger more than once, leading to unexpected results
902 such as messages being duplicated in the log.
903
Georg Brandl116aa622007-08-15 14:28:22 +0000904 The following keyword arguments are supported.
905
906 +--------------+---------------------------------------------+
907 | Format | Description |
908 +==============+=============================================+
909 | ``filename`` | Specifies that a FileHandler be created, |
910 | | using the specified filename, rather than a |
911 | | StreamHandler. |
912 +--------------+---------------------------------------------+
913 | ``filemode`` | Specifies the mode to open the file, if |
914 | | filename is specified (if filemode is |
915 | | unspecified, it defaults to 'a'). |
916 +--------------+---------------------------------------------+
917 | ``format`` | Use the specified format string for the |
918 | | handler. |
919 +--------------+---------------------------------------------+
920 | ``datefmt`` | Use the specified date/time format. |
921 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +0000922 | ``style`` | If ``format`` is specified, use this style |
923 | | for the format string. One of '%', '{' or |
924 | | '$' for %-formatting, :meth:`str.format` or |
925 | | :class:`string.Template` respectively, and |
926 | | defaulting to '%' if not specified. |
927 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000928 | ``level`` | Set the root logger level to the specified |
929 | | level. |
930 +--------------+---------------------------------------------+
931 | ``stream`` | Use the specified stream to initialize the |
932 | | StreamHandler. Note that this argument is |
933 | | incompatible with 'filename' - if both are |
934 | | present, 'stream' is ignored. |
935 +--------------+---------------------------------------------+
936
Vinay Sajipc5b27302010-10-31 14:59:16 +0000937 .. versionchanged:: 3.2
938 The ``style`` argument was added.
939
940
Georg Brandl116aa622007-08-15 14:28:22 +0000941.. function:: shutdown()
942
943 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +0000944 closing all handlers. This should be called at application exit and no
945 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947
948.. function:: setLoggerClass(klass)
949
950 Tells the logging system to use the class *klass* when instantiating a logger.
951 The class should define :meth:`__init__` such that only a name argument is
952 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
953 function is typically called before any loggers are instantiated by applications
954 which need to use custom logger behavior.
955
956
957.. seealso::
958
959 :pep:`282` - A Logging System
960 The proposal which described this feature for inclusion in the Python standard
961 library.
962
Christian Heimes255f53b2007-12-08 15:33:56 +0000963 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000964 This is the original source for the :mod:`logging` package. The version of the
965 package available from this site is suitable for use with Python 1.5.2, 2.1.x
966 and 2.2.x, which do not include the :mod:`logging` package in the standard
967 library.
968
Vinay Sajip4039aff2010-09-11 10:25:28 +0000969.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +0000970
971Logger Objects
972--------------
973
974Loggers have the following attributes and methods. Note that Loggers are never
975instantiated directly, but always through the module-level function
976``logging.getLogger(name)``.
977
Vinay Sajip0258ce82010-09-22 20:34:53 +0000978.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980.. attribute:: Logger.propagate
981
982 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000983 its child loggers to the handlers of higher level (ancestor) loggers. The
984 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986
987.. method:: Logger.setLevel(lvl)
988
989 Sets the threshold for this logger to *lvl*. Logging messages which are less
990 severe than *lvl* will be ignored. When a logger is created, the level is set to
991 :const:`NOTSET` (which causes all messages to be processed when the logger is
992 the root logger, or delegation to the parent when the logger is a non-root
993 logger). Note that the root logger is created with level :const:`WARNING`.
994
995 The term "delegation to the parent" means that if a logger has a level of
996 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
997 a level other than NOTSET is found, or the root is reached.
998
999 If an ancestor is found with a level other than NOTSET, then that ancestor's
1000 level is treated as the effective level of the logger where the ancestor search
1001 began, and is used to determine how a logging event is handled.
1002
1003 If the root is reached, and it has a level of NOTSET, then all messages will be
1004 processed. Otherwise, the root's level will be used as the effective level.
1005
1006
1007.. method:: Logger.isEnabledFor(lvl)
1008
1009 Indicates if a message of severity *lvl* would be processed by this logger.
1010 This method checks first the module-level level set by
1011 ``logging.disable(lvl)`` and then the logger's effective level as determined
1012 by :meth:`getEffectiveLevel`.
1013
1014
1015.. method:: Logger.getEffectiveLevel()
1016
1017 Indicates the effective level for this logger. If a value other than
1018 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1019 the hierarchy is traversed towards the root until a value other than
1020 :const:`NOTSET` is found, and that value is returned.
1021
1022
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001023.. method:: Logger.getChild(suffix)
1024
1025 Returns a logger which is a descendant to this logger, as determined by the suffix.
1026 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1027 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1028 convenience method, useful when the parent logger is named using e.g. ``__name__``
1029 rather than a literal string.
1030
1031 .. versionadded:: 3.2
1032
Georg Brandl67b21b72010-08-17 15:07:14 +00001033
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001034.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001035
1036 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1037 message format string, and the *args* are the arguments which are merged into
1038 *msg* using the string formatting operator. (Note that this means that you can
1039 use keywords in the format string, together with a single dictionary argument.)
1040
1041 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
1042 which, if it does not evaluate as false, causes exception information to be
1043 added to the logging message. If an exception tuple (in the format returned by
1044 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1045 is called to get the exception information.
1046
1047 The other optional keyword argument is *extra* which can be used to pass a
1048 dictionary which is used to populate the __dict__ of the LogRecord created for
1049 the logging event with user-defined attributes. These custom attributes can then
1050 be used as you like. For example, they could be incorporated into logged
1051 messages. For example::
1052
1053 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1054 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001055 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001056 logger = logging.getLogger("tcpserver")
1057 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1058
1059 would print something like ::
1060
1061 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1062
1063 The keys in the dictionary passed in *extra* should not clash with the keys used
1064 by the logging system. (See the :class:`Formatter` documentation for more
1065 information on which keys are used by the logging system.)
1066
1067 If you choose to use these attributes in logged messages, you need to exercise
1068 some care. In the above example, for instance, the :class:`Formatter` has been
1069 set up with a format string which expects 'clientip' and 'user' in the attribute
1070 dictionary of the LogRecord. If these are missing, the message will not be
1071 logged because a string formatting exception will occur. So in this case, you
1072 always need to pass the *extra* dictionary with these keys.
1073
1074 While this might be annoying, this feature is intended for use in specialized
1075 circumstances, such as multi-threaded servers where the same code executes in
1076 many contexts, and interesting conditions which arise are dependent on this
1077 context (such as remote client IP address and authenticated user name, in the
1078 above example). In such circumstances, it is likely that specialized
1079 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1080
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001082.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084 Logs a message with level :const:`INFO` on this logger. The arguments are
1085 interpreted as for :meth:`debug`.
1086
1087
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001088.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001089
1090 Logs a message with level :const:`WARNING` on this logger. The arguments are
1091 interpreted as for :meth:`debug`.
1092
1093
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001094.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096 Logs a message with level :const:`ERROR` on this logger. The arguments are
1097 interpreted as for :meth:`debug`.
1098
1099
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001100.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1103 interpreted as for :meth:`debug`.
1104
1105
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001106.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001107
1108 Logs a message with integer level *lvl* on this logger. The other arguments are
1109 interpreted as for :meth:`debug`.
1110
1111
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001112.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001113
1114 Logs a message with level :const:`ERROR` on this logger. The arguments are
1115 interpreted as for :meth:`debug`. Exception info is added to the logging
1116 message. This method should only be called from an exception handler.
1117
1118
1119.. method:: Logger.addFilter(filt)
1120
1121 Adds the specified filter *filt* to this logger.
1122
1123
1124.. method:: Logger.removeFilter(filt)
1125
1126 Removes the specified filter *filt* from this logger.
1127
1128
1129.. method:: Logger.filter(record)
1130
1131 Applies this logger's filters to the record and returns a true value if the
1132 record is to be processed.
1133
1134
1135.. method:: Logger.addHandler(hdlr)
1136
1137 Adds the specified handler *hdlr* to this logger.
1138
1139
1140.. method:: Logger.removeHandler(hdlr)
1141
1142 Removes the specified handler *hdlr* from this logger.
1143
1144
1145.. method:: Logger.findCaller()
1146
1147 Finds the caller's source filename and line number. Returns the filename, line
1148 number and function name as a 3-element tuple.
1149
Georg Brandl116aa622007-08-15 14:28:22 +00001150
1151.. method:: Logger.handle(record)
1152
1153 Handles a record by passing it to all handlers associated with this logger and
1154 its ancestors (until a false value of *propagate* is found). This method is used
1155 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001156 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001157
1158
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001159.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001160
1161 This is a factory method which can be overridden in subclasses to create
1162 specialized :class:`LogRecord` instances.
1163
Vinay Sajip83eadd12010-09-20 10:31:18 +00001164.. method:: Logger.hasHandlers()
1165
1166 Checks to see if this logger has any handlers configured. This is done by
1167 looking for handlers in this logger and its parents in the logger hierarchy.
1168 Returns True if a handler was found, else False. The method stops searching
1169 up the hierarchy whenever a logger with the "propagate" attribute set to
1170 False is found - that will be the last logger which is checked for the
1171 existence of handlers.
1172
1173.. versionadded:: 3.2
1174
1175The :meth:`hasHandlers` method was not present in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001176
1177.. _minimal-example:
1178
1179Basic example
1180-------------
1181
Georg Brandl116aa622007-08-15 14:28:22 +00001182The :mod:`logging` package provides a lot of flexibility, and its configuration
1183can appear daunting. This section demonstrates that simple use of the logging
1184package is possible.
1185
1186The simplest example shows logging to the console::
1187
1188 import logging
1189
1190 logging.debug('A debug message')
1191 logging.info('Some information')
1192 logging.warning('A shot across the bows')
1193
1194If you run the above script, you'll see this::
1195
1196 WARNING:root:A shot across the bows
1197
1198Because no particular logger was specified, the system used the root logger. The
1199debug and info messages didn't appear because by default, the root logger is
1200configured to only handle messages with a severity of WARNING or above. The
1201message format is also a configuration default, as is the output destination of
1202the messages - ``sys.stderr``. The severity level, the message format and
1203destination can be easily changed, as shown in the example below::
1204
1205 import logging
1206
1207 logging.basicConfig(level=logging.DEBUG,
1208 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001209 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001210 filemode='w')
1211 logging.debug('A debug message')
1212 logging.info('Some information')
1213 logging.warning('A shot across the bows')
1214
1215The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001216which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001217something like the following::
1218
1219 2004-07-02 13:00:08,743 DEBUG A debug message
1220 2004-07-02 13:00:08,743 INFO Some information
1221 2004-07-02 13:00:08,743 WARNING A shot across the bows
1222
1223This time, all messages with a severity of DEBUG or above were handled, and the
1224format of the messages was also changed, and output went to the specified file
1225rather than the console.
1226
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001227.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001228
1229Formatting uses the old Python string formatting - see section
1230:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001231specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1232documentation.
1233
1234+-------------------+-----------------------------------------------+
1235| Format | Description |
1236+===================+===============================================+
1237| ``%(name)s`` | Name of the logger (logging channel). |
1238+-------------------+-----------------------------------------------+
1239| ``%(levelname)s`` | Text logging level for the message |
1240| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1241| | ``'ERROR'``, ``'CRITICAL'``). |
1242+-------------------+-----------------------------------------------+
1243| ``%(asctime)s`` | Human-readable time when the |
1244| | :class:`LogRecord` was created. By default |
1245| | this is of the form "2003-07-08 16:49:45,896" |
1246| | (the numbers after the comma are millisecond |
1247| | portion of the time). |
1248+-------------------+-----------------------------------------------+
1249| ``%(message)s`` | The logged message. |
1250+-------------------+-----------------------------------------------+
1251
1252To change the date/time format, you can pass an additional keyword parameter,
1253*datefmt*, as in the following::
1254
1255 import logging
1256
1257 logging.basicConfig(level=logging.DEBUG,
1258 format='%(asctime)s %(levelname)-8s %(message)s',
1259 datefmt='%a, %d %b %Y %H:%M:%S',
1260 filename='/temp/myapp.log',
1261 filemode='w')
1262 logging.debug('A debug message')
1263 logging.info('Some information')
1264 logging.warning('A shot across the bows')
1265
1266which would result in output like ::
1267
1268 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1269 Fri, 02 Jul 2004 13:06:18 INFO Some information
1270 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1271
1272The date format string follows the requirements of :func:`strftime` - see the
1273documentation for the :mod:`time` module.
1274
1275If, instead of sending logging output to the console or a file, you'd rather use
1276a file-like object which you have created separately, you can pass it to
1277:func:`basicConfig` using the *stream* keyword argument. Note that if both
1278*stream* and *filename* keyword arguments are passed, the *stream* argument is
1279ignored.
1280
1281Of course, you can put variable information in your output. To do this, simply
1282have the message be a format string and pass in additional arguments containing
1283the variable information, as in the following example::
1284
1285 import logging
1286
1287 logging.basicConfig(level=logging.DEBUG,
1288 format='%(asctime)s %(levelname)-8s %(message)s',
1289 datefmt='%a, %d %b %Y %H:%M:%S',
1290 filename='/temp/myapp.log',
1291 filemode='w')
1292 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1293
1294which would result in ::
1295
1296 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1297
1298
1299.. _multiple-destinations:
1300
1301Logging to multiple destinations
1302--------------------------------
1303
1304Let's say you want to log to console and file with different message formats and
1305in differing circumstances. Say you want to log messages with levels of DEBUG
1306and higher to file, and those messages at level INFO and higher to the console.
1307Let's also assume that the file should contain timestamps, but the console
1308messages should not. Here's how you can achieve this::
1309
1310 import logging
1311
1312 # set up logging to file - see previous section for more details
1313 logging.basicConfig(level=logging.DEBUG,
1314 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1315 datefmt='%m-%d %H:%M',
1316 filename='/temp/myapp.log',
1317 filemode='w')
1318 # define a Handler which writes INFO messages or higher to the sys.stderr
1319 console = logging.StreamHandler()
1320 console.setLevel(logging.INFO)
1321 # set a format which is simpler for console use
1322 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1323 # tell the handler to use this format
1324 console.setFormatter(formatter)
1325 # add the handler to the root logger
1326 logging.getLogger('').addHandler(console)
1327
1328 # Now, we can log to the root logger, or any other logger. First the root...
1329 logging.info('Jackdaws love my big sphinx of quartz.')
1330
1331 # Now, define a couple of other loggers which might represent areas in your
1332 # application:
1333
1334 logger1 = logging.getLogger('myapp.area1')
1335 logger2 = logging.getLogger('myapp.area2')
1336
1337 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1338 logger1.info('How quickly daft jumping zebras vex.')
1339 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1340 logger2.error('The five boxing wizards jump quickly.')
1341
1342When you run this, on the console you will see ::
1343
1344 root : INFO Jackdaws love my big sphinx of quartz.
1345 myapp.area1 : INFO How quickly daft jumping zebras vex.
1346 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1347 myapp.area2 : ERROR The five boxing wizards jump quickly.
1348
1349and in the file you will see something like ::
1350
1351 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1352 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1353 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1354 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1355 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1356
1357As you can see, the DEBUG message only shows up in the file. The other messages
1358are sent to both destinations.
1359
1360This example uses console and file handlers, but you can use any number and
1361combination of handlers you choose.
1362
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001363.. _logging-exceptions:
1364
1365Exceptions raised during logging
1366--------------------------------
1367
1368The logging package is designed to swallow exceptions which occur while logging
1369in production. This is so that errors which occur while handling logging events
1370- such as logging misconfiguration, network or other similar errors - do not
1371cause the application using logging to terminate prematurely.
1372
1373:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1374swallowed. Other exceptions which occur during the :meth:`emit` method of a
1375:class:`Handler` subclass are passed to its :meth:`handleError` method.
1376
1377The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001378to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1379traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001380
Georg Brandlef871f62010-03-12 10:06:40 +00001381**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001382during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001383occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001384usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001385
Christian Heimes790c8232008-01-07 21:14:23 +00001386.. _context-info:
1387
1388Adding contextual information to your logging output
1389----------------------------------------------------
1390
1391Sometimes you want logging output to contain contextual information in
1392addition to the parameters passed to the logging call. For example, in a
1393networked application, it may be desirable to log client-specific information
1394in the log (e.g. remote client's username, or IP address). Although you could
1395use the *extra* parameter to achieve this, it's not always convenient to pass
1396the information in this way. While it might be tempting to create
1397:class:`Logger` instances on a per-connection basis, this is not a good idea
1398because these instances are not garbage collected. While this is not a problem
1399in practice, when the number of :class:`Logger` instances is dependent on the
1400level of granularity you want to use in logging an application, it could
1401be hard to manage if the number of :class:`Logger` instances becomes
1402effectively unbounded.
1403
Vinay Sajipc31be632010-09-06 22:18:20 +00001404
1405Using LoggerAdapters to impart contextual information
1406^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1407
Christian Heimes04c420f2008-01-18 18:40:46 +00001408An easy way in which you can pass contextual information to be output along
1409with logging event information is to use the :class:`LoggerAdapter` class.
1410This class is designed to look like a :class:`Logger`, so that you can call
1411:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1412:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1413same signatures as their counterparts in :class:`Logger`, so you can use the
1414two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001415
Christian Heimes04c420f2008-01-18 18:40:46 +00001416When you create an instance of :class:`LoggerAdapter`, you pass it a
1417:class:`Logger` instance and a dict-like object which contains your contextual
1418information. When you call one of the logging methods on an instance of
1419:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1420:class:`Logger` passed to its constructor, and arranges to pass the contextual
1421information in the delegated call. Here's a snippet from the code of
1422:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001423
Christian Heimes04c420f2008-01-18 18:40:46 +00001424 def debug(self, msg, *args, **kwargs):
1425 """
1426 Delegate a debug call to the underlying logger, after adding
1427 contextual information from this adapter instance.
1428 """
1429 msg, kwargs = self.process(msg, kwargs)
1430 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001431
Christian Heimes04c420f2008-01-18 18:40:46 +00001432The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1433information is added to the logging output. It's passed the message and
1434keyword arguments of the logging call, and it passes back (potentially)
1435modified versions of these to use in the call to the underlying logger. The
1436default implementation of this method leaves the message alone, but inserts
1437an "extra" key in the keyword argument whose value is the dict-like object
1438passed to the constructor. Of course, if you had passed an "extra" keyword
1439argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001440
Christian Heimes04c420f2008-01-18 18:40:46 +00001441The advantage of using "extra" is that the values in the dict-like object are
1442merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1443customized strings with your :class:`Formatter` instances which know about
1444the keys of the dict-like object. If you need a different method, e.g. if you
1445want to prepend or append the contextual information to the message string,
1446you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1447to do what you need. Here's an example script which uses this class, which
1448also illustrates what dict-like behaviour is needed from an arbitrary
1449"dict-like" object for use in the constructor::
1450
Christian Heimes587c2bf2008-01-19 16:21:02 +00001451 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001452
Christian Heimes587c2bf2008-01-19 16:21:02 +00001453 class ConnInfo:
1454 """
1455 An example class which shows how an arbitrary class can be used as
1456 the 'extra' context information repository passed to a LoggerAdapter.
1457 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001458
Christian Heimes587c2bf2008-01-19 16:21:02 +00001459 def __getitem__(self, name):
1460 """
1461 To allow this instance to look like a dict.
1462 """
1463 from random import choice
1464 if name == "ip":
1465 result = choice(["127.0.0.1", "192.168.0.1"])
1466 elif name == "user":
1467 result = choice(["jim", "fred", "sheila"])
1468 else:
1469 result = self.__dict__.get(name, "?")
1470 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001471
Christian Heimes587c2bf2008-01-19 16:21:02 +00001472 def __iter__(self):
1473 """
1474 To allow iteration over keys, which will be merged into
1475 the LogRecord dict before formatting and output.
1476 """
1477 keys = ["ip", "user"]
1478 keys.extend(self.__dict__.keys())
1479 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001480
Christian Heimes587c2bf2008-01-19 16:21:02 +00001481 if __name__ == "__main__":
1482 from random import choice
1483 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1484 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1485 { "ip" : "123.231.231.123", "user" : "sheila" })
1486 logging.basicConfig(level=logging.DEBUG,
1487 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1488 a1.debug("A debug message")
1489 a1.info("An info message with %s", "some parameters")
1490 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1491 for x in range(10):
1492 lvl = choice(levels)
1493 lvlname = logging.getLevelName(lvl)
1494 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001495
1496When this script is run, the output should look something like this::
1497
Christian Heimes587c2bf2008-01-19 16:21:02 +00001498 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1499 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1500 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
1501 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
1502 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
1503 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
1504 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
1505 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
1506 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
1507 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
1508 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
1509 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Christian Heimes04c420f2008-01-18 18:40:46 +00001510
Christian Heimes790c8232008-01-07 21:14:23 +00001511
Vinay Sajipac007992010-09-17 12:45:26 +00001512.. _filters-contextual:
1513
Vinay Sajipc31be632010-09-06 22:18:20 +00001514Using Filters to impart contextual information
1515^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1516
1517You can also add contextual information to log output using a user-defined
1518:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1519passed to them, including adding additional attributes which can then be output
1520using a suitable format string, or if needed a custom :class:`Formatter`.
1521
1522For example in a web application, the request being processed (or at least,
1523the interesting parts of it) can be stored in a threadlocal
1524(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1525add, say, information from the request - say, the remote IP address and remote
1526user's username - to the ``LogRecord``, using the attribute names 'ip' and
1527'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1528string can be used to get similar output to that shown above. Here's an example
1529script::
1530
1531 import logging
1532 from random import choice
1533
1534 class ContextFilter(logging.Filter):
1535 """
1536 This is a filter which injects contextual information into the log.
1537
1538 Rather than use actual contextual information, we just use random
1539 data in this demo.
1540 """
1541
1542 USERS = ['jim', 'fred', 'sheila']
1543 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1544
1545 def filter(self, record):
1546
1547 record.ip = choice(ContextFilter.IPS)
1548 record.user = choice(ContextFilter.USERS)
1549 return True
1550
1551 if __name__ == "__main__":
1552 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1553 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1554 { "ip" : "123.231.231.123", "user" : "sheila" })
1555 logging.basicConfig(level=logging.DEBUG,
1556 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1557 a1 = logging.getLogger("a.b.c")
1558 a2 = logging.getLogger("d.e.f")
1559
1560 f = ContextFilter()
1561 a1.addFilter(f)
1562 a2.addFilter(f)
1563 a1.debug("A debug message")
1564 a1.info("An info message with %s", "some parameters")
1565 for x in range(10):
1566 lvl = choice(levels)
1567 lvlname = logging.getLevelName(lvl)
1568 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1569
1570which, when run, produces something like::
1571
1572 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1573 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1574 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1575 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters
1576 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters
1577 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters
1578 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
1579 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
1580 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters
1581 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
1582 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters
1583 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters
1584
1585
Vinay Sajipd31f3632010-06-29 15:31:15 +00001586.. _multiple-processes:
1587
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001588Logging to a single file from multiple processes
1589------------------------------------------------
1590
1591Although logging is thread-safe, and logging to a single file from multiple
1592threads in a single process *is* supported, logging to a single file from
1593*multiple processes* is *not* supported, because there is no standard way to
1594serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001595need to log to a single file from multiple processes, one way of doing this is
1596to have all the processes log to a :class:`SocketHandler`, and have a separate
1597process which implements a socket server which reads from the socket and logs
1598to file. (If you prefer, you can dedicate one thread in one of the existing
1599processes to perform this function.) The following section documents this
1600approach in more detail and includes a working socket receiver which can be
1601used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001602
Vinay Sajip5a92b132009-08-15 23:35:08 +00001603If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001604:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001605:class:`Lock` class from this module to serialize access to the file from
1606your processes. The existing :class:`FileHandler` and subclasses do not make
1607use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001608Note that at present, the :mod:`multiprocessing` module does not provide
1609working lock functionality on all platforms (see
1610http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001611
Vinay Sajip121a1c42010-09-08 10:46:15 +00001612.. currentmodule:: logging.handlers
1613
1614Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1615all logging events to one of the processes in your multi-process application.
1616The following example script demonstrates how you can do this; in the example
1617a separate listener process listens for events sent by other processes and logs
1618them according to its own logging configuration. Although the example only
1619demonstrates one way of doing it (for example, you may want to use a listener
1620thread rather than a separate listener process - the implementation would be
1621analogous) it does allow for completely different logging configurations for
1622the listener and the other processes in your application, and can be used as
1623the basis for code meeting your own specific requirements::
1624
1625 # You'll need these imports in your own code
1626 import logging
1627 import logging.handlers
1628 import multiprocessing
1629
1630 # Next two import lines for this demo only
1631 from random import choice, random
1632 import time
1633
1634 #
1635 # Because you'll want to define the logging configurations for listener and workers, the
1636 # listener and worker process functions take a configurer parameter which is a callable
1637 # for configuring logging for that process. These functions are also passed the queue,
1638 # which they use for communication.
1639 #
1640 # In practice, you can configure the listener however you want, but note that in this
1641 # simple example, the listener does not apply level or filter logic to received records.
1642 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1643 # sending events which would be filtered out between processes.
1644 #
1645 # The size of the rotated files is made small so you can see the results easily.
1646 def listener_configurer():
1647 root = logging.getLogger()
1648 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
1649 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
1650 h.setFormatter(f)
1651 root.addHandler(h)
1652
1653 # This is the listener process top-level loop: wait for logging events
1654 # (LogRecords)on the queue and handle them, quit when you get a None for a
1655 # LogRecord.
1656 def listener_process(queue, configurer):
1657 configurer()
1658 while True:
1659 try:
1660 record = queue.get()
1661 if record is None: # We send this as a sentinel to tell the listener to quit.
1662 break
1663 logger = logging.getLogger(record.name)
1664 logger.handle(record) # No level or filter logic applied - just do it!
1665 except (KeyboardInterrupt, SystemExit):
1666 raise
1667 except:
1668 import sys, traceback
1669 print >> sys.stderr, 'Whoops! Problem:'
1670 traceback.print_exc(file=sys.stderr)
1671
1672 # Arrays used for random selections in this demo
1673
1674 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
1675 logging.ERROR, logging.CRITICAL]
1676
1677 LOGGERS = ['a.b.c', 'd.e.f']
1678
1679 MESSAGES = [
1680 'Random message #1',
1681 'Random message #2',
1682 'Random message #3',
1683 ]
1684
1685 # The worker configuration is done at the start of the worker process run.
1686 # Note that on Windows you can't rely on fork semantics, so each process
1687 # will run the logging configuration code when it starts.
1688 def worker_configurer(queue):
1689 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
1690 root = logging.getLogger()
1691 root.addHandler(h)
1692 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
1693
1694 # This is the worker process top-level loop, which just logs ten events with
1695 # random intervening delays before terminating.
1696 # The print messages are just so you know it's doing something!
1697 def worker_process(queue, configurer):
1698 configurer(queue)
1699 name = multiprocessing.current_process().name
1700 print('Worker started: %s' % name)
1701 for i in range(10):
1702 time.sleep(random())
1703 logger = logging.getLogger(choice(LOGGERS))
1704 level = choice(LEVELS)
1705 message = choice(MESSAGES)
1706 logger.log(level, message)
1707 print('Worker finished: %s' % name)
1708
1709 # Here's where the demo gets orchestrated. Create the queue, create and start
1710 # the listener, create ten workers and start them, wait for them to finish,
1711 # then send a None to the queue to tell the listener to finish.
1712 def main():
1713 queue = multiprocessing.Queue(-1)
1714 listener = multiprocessing.Process(target=listener_process,
1715 args=(queue, listener_configurer))
1716 listener.start()
1717 workers = []
1718 for i in range(10):
1719 worker = multiprocessing.Process(target=worker_process,
1720 args=(queue, worker_configurer))
1721 workers.append(worker)
1722 worker.start()
1723 for w in workers:
1724 w.join()
1725 queue.put_nowait(None)
1726 listener.join()
1727
1728 if __name__ == '__main__':
1729 main()
1730
1731
1732.. currentmodule:: logging
1733
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001734
Georg Brandl116aa622007-08-15 14:28:22 +00001735.. _network-logging:
1736
1737Sending and receiving logging events across a network
1738-----------------------------------------------------
1739
1740Let's say you want to send logging events across a network, and handle them at
1741the receiving end. A simple way of doing this is attaching a
1742:class:`SocketHandler` instance to the root logger at the sending end::
1743
1744 import logging, logging.handlers
1745
1746 rootLogger = logging.getLogger('')
1747 rootLogger.setLevel(logging.DEBUG)
1748 socketHandler = logging.handlers.SocketHandler('localhost',
1749 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
1750 # don't bother with a formatter, since a socket handler sends the event as
1751 # an unformatted pickle
1752 rootLogger.addHandler(socketHandler)
1753
1754 # Now, we can log to the root logger, or any other logger. First the root...
1755 logging.info('Jackdaws love my big sphinx of quartz.')
1756
1757 # Now, define a couple of other loggers which might represent areas in your
1758 # application:
1759
1760 logger1 = logging.getLogger('myapp.area1')
1761 logger2 = logging.getLogger('myapp.area2')
1762
1763 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1764 logger1.info('How quickly daft jumping zebras vex.')
1765 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1766 logger2.error('The five boxing wizards jump quickly.')
1767
Alexandre Vassalottice261952008-05-12 02:31:37 +00001768At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00001769module. Here is a basic working example::
1770
Georg Brandla35f4b92009-05-31 16:41:59 +00001771 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00001772 import logging
1773 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00001774 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00001775 import struct
1776
1777
Alexandre Vassalottice261952008-05-12 02:31:37 +00001778 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00001779 """Handler for a streaming logging request.
1780
1781 This basically logs the record using whatever logging policy is
1782 configured locally.
1783 """
1784
1785 def handle(self):
1786 """
1787 Handle multiple requests - each expected to be a 4-byte length,
1788 followed by the LogRecord in pickle format. Logs the record
1789 according to whatever policy is configured locally.
1790 """
Collin Winter46334482007-09-10 00:49:57 +00001791 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00001792 chunk = self.connection.recv(4)
1793 if len(chunk) < 4:
1794 break
1795 slen = struct.unpack(">L", chunk)[0]
1796 chunk = self.connection.recv(slen)
1797 while len(chunk) < slen:
1798 chunk = chunk + self.connection.recv(slen - len(chunk))
1799 obj = self.unPickle(chunk)
1800 record = logging.makeLogRecord(obj)
1801 self.handleLogRecord(record)
1802
1803 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00001804 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00001805
1806 def handleLogRecord(self, record):
1807 # if a name is specified, we use the named logger rather than the one
1808 # implied by the record.
1809 if self.server.logname is not None:
1810 name = self.server.logname
1811 else:
1812 name = record.name
1813 logger = logging.getLogger(name)
1814 # N.B. EVERY record gets logged. This is because Logger.handle
1815 # is normally called AFTER logger-level filtering. If you want
1816 # to do filtering, do it at the client end to save wasting
1817 # cycles and network bandwidth!
1818 logger.handle(record)
1819
Alexandre Vassalottice261952008-05-12 02:31:37 +00001820 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00001821 """simple TCP socket-based logging receiver suitable for testing.
1822 """
1823
1824 allow_reuse_address = 1
1825
1826 def __init__(self, host='localhost',
1827 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
1828 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00001829 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001830 self.abort = 0
1831 self.timeout = 1
1832 self.logname = None
1833
1834 def serve_until_stopped(self):
1835 import select
1836 abort = 0
1837 while not abort:
1838 rd, wr, ex = select.select([self.socket.fileno()],
1839 [], [],
1840 self.timeout)
1841 if rd:
1842 self.handle_request()
1843 abort = self.abort
1844
1845 def main():
1846 logging.basicConfig(
1847 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
1848 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001849 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00001850 tcpserver.serve_until_stopped()
1851
1852 if __name__ == "__main__":
1853 main()
1854
1855First run the server, and then the client. On the client side, nothing is
1856printed on the console; on the server side, you should see something like::
1857
1858 About to start TCP server...
1859 59 root INFO Jackdaws love my big sphinx of quartz.
1860 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1861 69 myapp.area1 INFO How quickly daft jumping zebras vex.
1862 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1863 69 myapp.area2 ERROR The five boxing wizards jump quickly.
1864
Vinay Sajipc15dfd62010-07-06 15:08:55 +00001865Note that there are some security issues with pickle in some scenarios. If
1866these affect you, you can use an alternative serialization scheme by overriding
1867the :meth:`makePickle` method and implementing your alternative there, as
1868well as adapting the above script to use your alternative serialization.
1869
Vinay Sajip4039aff2010-09-11 10:25:28 +00001870.. _arbitrary-object-messages:
1871
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001872Using arbitrary objects as messages
1873-----------------------------------
1874
1875In the preceding sections and examples, it has been assumed that the message
1876passed when logging the event is a string. However, this is not the only
1877possibility. You can pass an arbitrary object as a message, and its
1878:meth:`__str__` method will be called when the logging system needs to convert
1879it to a string representation. In fact, if you want to, you can avoid
1880computing a string representation altogether - for example, the
1881:class:`SocketHandler` emits an event by pickling it and sending it over the
1882wire.
1883
Vinay Sajip55778922010-09-23 09:09:15 +00001884Dealing with handlers that block
1885--------------------------------
1886
1887.. currentmodule:: logging.handlers
1888
1889Sometimes you have to get your logging handlers to do their work without
1890blocking the thread you’re logging from. This is common in Web applications,
1891though of course it also occurs in other scenarios.
1892
1893A common culprit which demonstrates sluggish behaviour is the
1894:class:`SMTPHandler`: sending emails can take a long time, for a
1895number of reasons outside the developer’s control (for example, a poorly
1896performing mail or network infrastructure). But almost any network-based
1897handler can block: Even a :class:`SocketHandler` operation may do a
1898DNS query under the hood which is too slow (and this query can be deep in the
1899socket library code, below the Python layer, and outside your control).
1900
1901One solution is to use a two-part approach. For the first part, attach only a
1902:class:`QueueHandler` to those loggers which are accessed from
1903performance-critical threads. They simply write to their queue, which can be
1904sized to a large enough capacity or initialized with no upper bound to their
1905size. The write to the queue will typically be accepted quickly, though you
1906will probably need to catch the :ref:`queue.Full` exception as a precaution
1907in your code. If you are a library developer who has performance-critical
1908threads in their code, be sure to document this (together with a suggestion to
1909attach only ``QueueHandlers`` to your loggers) for the benefit of other
1910developers who will use your code.
1911
1912The second part of the solution is :class:`QueueListener`, which has been
1913designed as the counterpart to :class:`QueueHandler`. A
1914:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
1915and it fires up an internal thread which listens to its queue for LogRecords
1916sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
1917matter). The ``LogRecords`` are removed from the queue and passed to the
1918handlers for processing.
1919
1920The advantage of having a separate :class:`QueueListener` class is that you
1921can use the same instance to service multiple ``QueueHandlers``. This is more
1922resource-friendly than, say, having threaded versions of the existing handler
1923classes, which would eat up one thread per handler for no particular benefit.
1924
1925An example of using these two classes follows (imports omitted)::
1926
1927 que = queue.Queue(-1) # no limit on size
1928 queue_handler = QueueHandler(que)
1929 handler = logging.StreamHandler()
1930 listener = QueueListener(que, handler)
1931 root = logging.getLogger()
1932 root.addHandler(queue_handler)
1933 formatter = logging.Formatter('%(threadName)s: %(message)s')
1934 handler.setFormatter(formatter)
1935 listener.start()
1936 # The log output will display the thread which generated
1937 # the event (the main thread) rather than the internal
1938 # thread which monitors the internal queue. This is what
1939 # you want to happen.
1940 root.warning('Look out!')
1941 listener.stop()
1942
1943which, when run, will produce::
1944
1945 MainThread: Look out!
1946
1947
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001948Optimization
1949------------
1950
1951Formatting of message arguments is deferred until it cannot be avoided.
1952However, computing the arguments passed to the logging method can also be
1953expensive, and you may want to avoid doing it if the logger will just throw
1954away your event. To decide what to do, you can call the :meth:`isEnabledFor`
1955method which takes a level argument and returns true if the event would be
1956created by the Logger for that level of call. You can write code like this::
1957
1958 if logger.isEnabledFor(logging.DEBUG):
1959 logger.debug("Message with %s, %s", expensive_func1(),
1960 expensive_func2())
1961
1962so that if the logger's threshold is set above ``DEBUG``, the calls to
1963:func:`expensive_func1` and :func:`expensive_func2` are never made.
1964
1965There are other optimizations which can be made for specific applications which
1966need more precise control over what logging information is collected. Here's a
1967list of things you can do to avoid processing during logging which you don't
1968need:
1969
1970+-----------------------------------------------+----------------------------------------+
1971| What you don't want to collect | How to avoid collecting it |
1972+===============================================+========================================+
1973| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
1974+-----------------------------------------------+----------------------------------------+
1975| Threading information. | Set ``logging.logThreads`` to ``0``. |
1976+-----------------------------------------------+----------------------------------------+
1977| Process information. | Set ``logging.logProcesses`` to ``0``. |
1978+-----------------------------------------------+----------------------------------------+
1979
1980Also note that the core logging module only includes the basic handlers. If
1981you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
1982take up any memory.
1983
1984.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00001985
1986Handler Objects
1987---------------
1988
1989Handlers have the following attributes and methods. Note that :class:`Handler`
1990is never instantiated directly; this class acts as a base for more useful
1991subclasses. However, the :meth:`__init__` method in subclasses needs to call
1992:meth:`Handler.__init__`.
1993
1994
1995.. method:: Handler.__init__(level=NOTSET)
1996
1997 Initializes the :class:`Handler` instance by setting its level, setting the list
1998 of filters to the empty list and creating a lock (using :meth:`createLock`) for
1999 serializing access to an I/O mechanism.
2000
2001
2002.. method:: Handler.createLock()
2003
2004 Initializes a thread lock which can be used to serialize access to underlying
2005 I/O functionality which may not be threadsafe.
2006
2007
2008.. method:: Handler.acquire()
2009
2010 Acquires the thread lock created with :meth:`createLock`.
2011
2012
2013.. method:: Handler.release()
2014
2015 Releases the thread lock acquired with :meth:`acquire`.
2016
2017
2018.. method:: Handler.setLevel(lvl)
2019
2020 Sets the threshold for this handler to *lvl*. Logging messages which are less
2021 severe than *lvl* will be ignored. When a handler is created, the level is set
2022 to :const:`NOTSET` (which causes all messages to be processed).
2023
2024
2025.. method:: Handler.setFormatter(form)
2026
2027 Sets the :class:`Formatter` for this handler to *form*.
2028
2029
2030.. method:: Handler.addFilter(filt)
2031
2032 Adds the specified filter *filt* to this handler.
2033
2034
2035.. method:: Handler.removeFilter(filt)
2036
2037 Removes the specified filter *filt* from this handler.
2038
2039
2040.. method:: Handler.filter(record)
2041
2042 Applies this handler's filters to the record and returns a true value if the
2043 record is to be processed.
2044
2045
2046.. method:: Handler.flush()
2047
2048 Ensure all logging output has been flushed. This version does nothing and is
2049 intended to be implemented by subclasses.
2050
2051
2052.. method:: Handler.close()
2053
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002054 Tidy up any resources used by the handler. This version does no output but
2055 removes the handler from an internal list of handlers which is closed when
2056 :func:`shutdown` is called. Subclasses should ensure that this gets called
2057 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002058
2059
2060.. method:: Handler.handle(record)
2061
2062 Conditionally emits the specified logging record, depending on filters which may
2063 have been added to the handler. Wraps the actual emission of the record with
2064 acquisition/release of the I/O thread lock.
2065
2066
2067.. method:: Handler.handleError(record)
2068
2069 This method should be called from handlers when an exception is encountered
2070 during an :meth:`emit` call. By default it does nothing, which means that
2071 exceptions get silently ignored. This is what is mostly wanted for a logging
2072 system - most users will not care about errors in the logging system, they are
2073 more interested in application errors. You could, however, replace this with a
2074 custom handler if you wish. The specified record is the one which was being
2075 processed when the exception occurred.
2076
2077
2078.. method:: Handler.format(record)
2079
2080 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2081 default formatter for the module.
2082
2083
2084.. method:: Handler.emit(record)
2085
2086 Do whatever it takes to actually log the specified logging record. This version
2087 is intended to be implemented by subclasses and so raises a
2088 :exc:`NotImplementedError`.
2089
2090
Vinay Sajipd31f3632010-06-29 15:31:15 +00002091.. _stream-handler:
2092
Georg Brandl116aa622007-08-15 14:28:22 +00002093StreamHandler
2094^^^^^^^^^^^^^
2095
2096The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2097sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2098file-like object (or, more precisely, any object which supports :meth:`write`
2099and :meth:`flush` methods).
2100
2101
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002102.. currentmodule:: logging
2103
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002104.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002105
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002106 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002107 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2108 will be used.
2109
2110
Benjamin Petersone41251e2008-04-25 01:59:09 +00002111 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002112
Benjamin Petersone41251e2008-04-25 01:59:09 +00002113 If a formatter is specified, it is used to format the record. The record
2114 is then written to the stream with a trailing newline. If exception
2115 information is present, it is formatted using
2116 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002117
2118
Benjamin Petersone41251e2008-04-25 01:59:09 +00002119 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002120
Benjamin Petersone41251e2008-04-25 01:59:09 +00002121 Flushes the stream by calling its :meth:`flush` method. Note that the
2122 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002123 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002124
Vinay Sajip05ed6952010-10-20 20:34:09 +00002125.. versionchanged:: 3.2
2126 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2127 value ``"\n"``, which is used as the terminator when writing a formatted
2128 record to a stream. If you don't want this newline termination, you can
2129 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002130
Vinay Sajipd31f3632010-06-29 15:31:15 +00002131.. _file-handler:
2132
Georg Brandl116aa622007-08-15 14:28:22 +00002133FileHandler
2134^^^^^^^^^^^
2135
2136The :class:`FileHandler` class, located in the core :mod:`logging` package,
2137sends logging output to a disk file. It inherits the output functionality from
2138:class:`StreamHandler`.
2139
2140
Vinay Sajipd31f3632010-06-29 15:31:15 +00002141.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002142
2143 Returns a new instance of the :class:`FileHandler` class. The specified file is
2144 opened and used as the stream for logging. If *mode* is not specified,
2145 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002146 with that encoding. If *delay* is true, then file opening is deferred until the
2147 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002148
2149
Benjamin Petersone41251e2008-04-25 01:59:09 +00002150 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002151
Benjamin Petersone41251e2008-04-25 01:59:09 +00002152 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002153
2154
Benjamin Petersone41251e2008-04-25 01:59:09 +00002155 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002156
Benjamin Petersone41251e2008-04-25 01:59:09 +00002157 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002158
Vinay Sajipd31f3632010-06-29 15:31:15 +00002159.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002160
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002161NullHandler
2162^^^^^^^^^^^
2163
2164.. versionadded:: 3.1
2165
2166The :class:`NullHandler` class, located in the core :mod:`logging` package,
2167does not do any formatting or output. It is essentially a "no-op" handler
2168for use by library developers.
2169
2170
2171.. class:: NullHandler()
2172
2173 Returns a new instance of the :class:`NullHandler` class.
2174
2175
2176 .. method:: emit(record)
2177
2178 This method does nothing.
2179
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002180 .. method:: handle(record)
2181
2182 This method does nothing.
2183
2184 .. method:: createLock()
2185
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002186 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002187 underlying I/O to which access needs to be serialized.
2188
2189
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002190See :ref:`library-config` for more information on how to use
2191:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002192
Vinay Sajipd31f3632010-06-29 15:31:15 +00002193.. _watched-file-handler:
2194
Georg Brandl116aa622007-08-15 14:28:22 +00002195WatchedFileHandler
2196^^^^^^^^^^^^^^^^^^
2197
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002198.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002199
Georg Brandl116aa622007-08-15 14:28:22 +00002200The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2201module, is a :class:`FileHandler` which watches the file it is logging to. If
2202the file changes, it is closed and reopened using the file name.
2203
2204A file change can happen because of usage of programs such as *newsyslog* and
2205*logrotate* which perform log file rotation. This handler, intended for use
2206under Unix/Linux, watches the file to see if it has changed since the last emit.
2207(A file is deemed to have changed if its device or inode have changed.) If the
2208file has changed, the old file stream is closed, and the file opened to get a
2209new stream.
2210
2211This handler is not appropriate for use under Windows, because under Windows
2212open log files cannot be moved or renamed - logging opens the files with
2213exclusive locks - and so there is no need for such a handler. Furthermore,
2214*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2215this value.
2216
2217
Christian Heimese7a15bb2008-01-24 16:21:45 +00002218.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002219
2220 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2221 file is opened and used as the stream for logging. If *mode* is not specified,
2222 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002223 with that encoding. If *delay* is true, then file opening is deferred until the
2224 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002225
2226
Benjamin Petersone41251e2008-04-25 01:59:09 +00002227 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002228
Benjamin Petersone41251e2008-04-25 01:59:09 +00002229 Outputs the record to the file, but first checks to see if the file has
2230 changed. If it has, the existing stream is flushed and closed and the
2231 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002232
Vinay Sajipd31f3632010-06-29 15:31:15 +00002233.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002234
2235RotatingFileHandler
2236^^^^^^^^^^^^^^^^^^^
2237
2238The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2239module, supports rotation of disk log files.
2240
2241
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002242.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002243
2244 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2245 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002246 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2247 with that encoding. If *delay* is true, then file opening is deferred until the
2248 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002249
2250 You can use the *maxBytes* and *backupCount* values to allow the file to
2251 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2252 the file is closed and a new file is silently opened for output. Rollover occurs
2253 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2254 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2255 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2256 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2257 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2258 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2259 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2260 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2261 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2262
2263
Benjamin Petersone41251e2008-04-25 01:59:09 +00002264 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002265
Benjamin Petersone41251e2008-04-25 01:59:09 +00002266 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002267
2268
Benjamin Petersone41251e2008-04-25 01:59:09 +00002269 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002270
Benjamin Petersone41251e2008-04-25 01:59:09 +00002271 Outputs the record to the file, catering for rollover as described
2272 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002273
Vinay Sajipd31f3632010-06-29 15:31:15 +00002274.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002275
2276TimedRotatingFileHandler
2277^^^^^^^^^^^^^^^^^^^^^^^^
2278
2279The :class:`TimedRotatingFileHandler` class, located in the
2280:mod:`logging.handlers` module, supports rotation of disk log files at certain
2281timed intervals.
2282
2283
Vinay Sajipd31f3632010-06-29 15:31:15 +00002284.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002285
2286 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2287 specified file is opened and used as the stream for logging. On rotating it also
2288 sets the filename suffix. Rotating happens based on the product of *when* and
2289 *interval*.
2290
2291 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002292 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002293
Christian Heimesb558a2e2008-03-02 22:46:37 +00002294 +----------------+-----------------------+
2295 | Value | Type of interval |
2296 +================+=======================+
2297 | ``'S'`` | Seconds |
2298 +----------------+-----------------------+
2299 | ``'M'`` | Minutes |
2300 +----------------+-----------------------+
2301 | ``'H'`` | Hours |
2302 +----------------+-----------------------+
2303 | ``'D'`` | Days |
2304 +----------------+-----------------------+
2305 | ``'W'`` | Week day (0=Monday) |
2306 +----------------+-----------------------+
2307 | ``'midnight'`` | Roll over at midnight |
2308 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002309
Christian Heimesb558a2e2008-03-02 22:46:37 +00002310 The system will save old log files by appending extensions to the filename.
2311 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002312 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002313 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002314
2315 When computing the next rollover time for the first time (when the handler
2316 is created), the last modification time of an existing log file, or else
2317 the current time, is used to compute when the next rotation will occur.
2318
Georg Brandl0c77a822008-06-10 16:37:50 +00002319 If the *utc* argument is true, times in UTC will be used; otherwise
2320 local time is used.
2321
2322 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002323 will be kept, and if more would be created when rollover occurs, the oldest
2324 one is deleted. The deletion logic uses the interval to determine which
2325 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002326
Vinay Sajipd31f3632010-06-29 15:31:15 +00002327 If *delay* is true, then file opening is deferred until the first call to
2328 :meth:`emit`.
2329
Georg Brandl116aa622007-08-15 14:28:22 +00002330
Benjamin Petersone41251e2008-04-25 01:59:09 +00002331 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002332
Benjamin Petersone41251e2008-04-25 01:59:09 +00002333 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002334
2335
Benjamin Petersone41251e2008-04-25 01:59:09 +00002336 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002337
Benjamin Petersone41251e2008-04-25 01:59:09 +00002338 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002339
2340
Vinay Sajipd31f3632010-06-29 15:31:15 +00002341.. _socket-handler:
2342
Georg Brandl116aa622007-08-15 14:28:22 +00002343SocketHandler
2344^^^^^^^^^^^^^
2345
2346The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2347sends logging output to a network socket. The base class uses a TCP socket.
2348
2349
2350.. class:: SocketHandler(host, port)
2351
2352 Returns a new instance of the :class:`SocketHandler` class intended to
2353 communicate with a remote machine whose address is given by *host* and *port*.
2354
2355
Benjamin Petersone41251e2008-04-25 01:59:09 +00002356 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002357
Benjamin Petersone41251e2008-04-25 01:59:09 +00002358 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002359
2360
Benjamin Petersone41251e2008-04-25 01:59:09 +00002361 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002362
Benjamin Petersone41251e2008-04-25 01:59:09 +00002363 Pickles the record's attribute dictionary and writes it to the socket in
2364 binary format. If there is an error with the socket, silently drops the
2365 packet. If the connection was previously lost, re-establishes the
2366 connection. To unpickle the record at the receiving end into a
2367 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002368
2369
Benjamin Petersone41251e2008-04-25 01:59:09 +00002370 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002371
Benjamin Petersone41251e2008-04-25 01:59:09 +00002372 Handles an error which has occurred during :meth:`emit`. The most likely
2373 cause is a lost connection. Closes the socket so that we can retry on the
2374 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002375
2376
Benjamin Petersone41251e2008-04-25 01:59:09 +00002377 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002378
Benjamin Petersone41251e2008-04-25 01:59:09 +00002379 This is a factory method which allows subclasses to define the precise
2380 type of socket they want. The default implementation creates a TCP socket
2381 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002382
2383
Benjamin Petersone41251e2008-04-25 01:59:09 +00002384 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002385
Benjamin Petersone41251e2008-04-25 01:59:09 +00002386 Pickles the record's attribute dictionary in binary format with a length
2387 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002388
Vinay Sajipd31f3632010-06-29 15:31:15 +00002389 Note that pickles aren't completely secure. If you are concerned about
2390 security, you may want to override this method to implement a more secure
2391 mechanism. For example, you can sign pickles using HMAC and then verify
2392 them on the receiving end, or alternatively you can disable unpickling of
2393 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002394
Benjamin Petersone41251e2008-04-25 01:59:09 +00002395 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002396
Benjamin Petersone41251e2008-04-25 01:59:09 +00002397 Send a pickled string *packet* to the socket. This function allows for
2398 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002399
2400
Vinay Sajipd31f3632010-06-29 15:31:15 +00002401.. _datagram-handler:
2402
Georg Brandl116aa622007-08-15 14:28:22 +00002403DatagramHandler
2404^^^^^^^^^^^^^^^
2405
2406The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2407module, inherits from :class:`SocketHandler` to support sending logging messages
2408over UDP sockets.
2409
2410
2411.. class:: DatagramHandler(host, port)
2412
2413 Returns a new instance of the :class:`DatagramHandler` class intended to
2414 communicate with a remote machine whose address is given by *host* and *port*.
2415
2416
Benjamin Petersone41251e2008-04-25 01:59:09 +00002417 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002418
Benjamin Petersone41251e2008-04-25 01:59:09 +00002419 Pickles the record's attribute dictionary and writes it to the socket in
2420 binary format. If there is an error with the socket, silently drops the
2421 packet. To unpickle the record at the receiving end into a
2422 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002423
2424
Benjamin Petersone41251e2008-04-25 01:59:09 +00002425 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002426
Benjamin Petersone41251e2008-04-25 01:59:09 +00002427 The factory method of :class:`SocketHandler` is here overridden to create
2428 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002429
2430
Benjamin Petersone41251e2008-04-25 01:59:09 +00002431 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002432
Benjamin Petersone41251e2008-04-25 01:59:09 +00002433 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002434
2435
Vinay Sajipd31f3632010-06-29 15:31:15 +00002436.. _syslog-handler:
2437
Georg Brandl116aa622007-08-15 14:28:22 +00002438SysLogHandler
2439^^^^^^^^^^^^^
2440
2441The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2442supports sending logging messages to a remote or local Unix syslog.
2443
2444
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002445.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002446
2447 Returns a new instance of the :class:`SysLogHandler` class intended to
2448 communicate with a remote Unix machine whose address is given by *address* in
2449 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002450 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002451 alternative to providing a ``(host, port)`` tuple is providing an address as a
2452 string, for example "/dev/log". In this case, a Unix domain socket is used to
2453 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002454 :const:`LOG_USER` is used. The type of socket opened depends on the
2455 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2456 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2457 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2458
Vinay Sajip972412d2010-09-23 20:31:24 +00002459 Note that if your server is not listening on UDP port 514,
2460 :class:`SysLogHandler` may appear not to work. In that case, check what
2461 address you should be using for a domain socket - it's system dependent.
2462 For example, on Linux it's usually "/dev/log" but on OS/X it's
2463 "/var/run/syslog". You'll need to check your platform and use the
2464 appropriate address (you may need to do this check at runtime if your
2465 application needs to run on several platforms). On Windows, you pretty
2466 much have to use the UDP option.
2467
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002468 .. versionchanged:: 3.2
2469 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002470
2471
Benjamin Petersone41251e2008-04-25 01:59:09 +00002472 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002473
Benjamin Petersone41251e2008-04-25 01:59:09 +00002474 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002475
2476
Benjamin Petersone41251e2008-04-25 01:59:09 +00002477 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002478
Benjamin Petersone41251e2008-04-25 01:59:09 +00002479 The record is formatted, and then sent to the syslog server. If exception
2480 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002481
2482
Benjamin Petersone41251e2008-04-25 01:59:09 +00002483 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002484
Benjamin Petersone41251e2008-04-25 01:59:09 +00002485 Encodes the facility and priority into an integer. You can pass in strings
2486 or integers - if strings are passed, internal mapping dictionaries are
2487 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002488
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002489 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2490 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002491
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002492 **Priorities**
2493
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002494 +--------------------------+---------------+
2495 | Name (string) | Symbolic value|
2496 +==========================+===============+
2497 | ``alert`` | LOG_ALERT |
2498 +--------------------------+---------------+
2499 | ``crit`` or ``critical`` | LOG_CRIT |
2500 +--------------------------+---------------+
2501 | ``debug`` | LOG_DEBUG |
2502 +--------------------------+---------------+
2503 | ``emerg`` or ``panic`` | LOG_EMERG |
2504 +--------------------------+---------------+
2505 | ``err`` or ``error`` | LOG_ERR |
2506 +--------------------------+---------------+
2507 | ``info`` | LOG_INFO |
2508 +--------------------------+---------------+
2509 | ``notice`` | LOG_NOTICE |
2510 +--------------------------+---------------+
2511 | ``warn`` or ``warning`` | LOG_WARNING |
2512 +--------------------------+---------------+
2513
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002514 **Facilities**
2515
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002516 +---------------+---------------+
2517 | Name (string) | Symbolic value|
2518 +===============+===============+
2519 | ``auth`` | LOG_AUTH |
2520 +---------------+---------------+
2521 | ``authpriv`` | LOG_AUTHPRIV |
2522 +---------------+---------------+
2523 | ``cron`` | LOG_CRON |
2524 +---------------+---------------+
2525 | ``daemon`` | LOG_DAEMON |
2526 +---------------+---------------+
2527 | ``ftp`` | LOG_FTP |
2528 +---------------+---------------+
2529 | ``kern`` | LOG_KERN |
2530 +---------------+---------------+
2531 | ``lpr`` | LOG_LPR |
2532 +---------------+---------------+
2533 | ``mail`` | LOG_MAIL |
2534 +---------------+---------------+
2535 | ``news`` | LOG_NEWS |
2536 +---------------+---------------+
2537 | ``syslog`` | LOG_SYSLOG |
2538 +---------------+---------------+
2539 | ``user`` | LOG_USER |
2540 +---------------+---------------+
2541 | ``uucp`` | LOG_UUCP |
2542 +---------------+---------------+
2543 | ``local0`` | LOG_LOCAL0 |
2544 +---------------+---------------+
2545 | ``local1`` | LOG_LOCAL1 |
2546 +---------------+---------------+
2547 | ``local2`` | LOG_LOCAL2 |
2548 +---------------+---------------+
2549 | ``local3`` | LOG_LOCAL3 |
2550 +---------------+---------------+
2551 | ``local4`` | LOG_LOCAL4 |
2552 +---------------+---------------+
2553 | ``local5`` | LOG_LOCAL5 |
2554 +---------------+---------------+
2555 | ``local6`` | LOG_LOCAL6 |
2556 +---------------+---------------+
2557 | ``local7`` | LOG_LOCAL7 |
2558 +---------------+---------------+
2559
2560 .. method:: mapPriority(levelname)
2561
2562 Maps a logging level name to a syslog priority name.
2563 You may need to override this if you are using custom levels, or
2564 if the default algorithm is not suitable for your needs. The
2565 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2566 ``CRITICAL`` to the equivalent syslog names, and all other level
2567 names to "warning".
2568
2569.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002570
2571NTEventLogHandler
2572^^^^^^^^^^^^^^^^^
2573
2574The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2575module, supports sending logging messages to a local Windows NT, Windows 2000 or
2576Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2577extensions for Python installed.
2578
2579
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002580.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002581
2582 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2583 used to define the application name as it appears in the event log. An
2584 appropriate registry entry is created using this name. The *dllname* should give
2585 the fully qualified pathname of a .dll or .exe which contains message
2586 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2587 - this is installed with the Win32 extensions and contains some basic
2588 placeholder message definitions. Note that use of these placeholders will make
2589 your event logs big, as the entire message source is held in the log. If you
2590 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2591 contains the message definitions you want to use in the event log). The
2592 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2593 defaults to ``'Application'``.
2594
2595
Benjamin Petersone41251e2008-04-25 01:59:09 +00002596 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002597
Benjamin Petersone41251e2008-04-25 01:59:09 +00002598 At this point, you can remove the application name from the registry as a
2599 source of event log entries. However, if you do this, you will not be able
2600 to see the events as you intended in the Event Log Viewer - it needs to be
2601 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002602 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002603
2604
Benjamin Petersone41251e2008-04-25 01:59:09 +00002605 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002606
Benjamin Petersone41251e2008-04-25 01:59:09 +00002607 Determines the message ID, event category and event type, and then logs
2608 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002609
2610
Benjamin Petersone41251e2008-04-25 01:59:09 +00002611 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002612
Benjamin Petersone41251e2008-04-25 01:59:09 +00002613 Returns the event category for the record. Override this if you want to
2614 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002615
2616
Benjamin Petersone41251e2008-04-25 01:59:09 +00002617 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002618
Benjamin Petersone41251e2008-04-25 01:59:09 +00002619 Returns the event type for the record. Override this if you want to
2620 specify your own types. This version does a mapping using the handler's
2621 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2622 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2623 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2624 your own levels, you will either need to override this method or place a
2625 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002626
2627
Benjamin Petersone41251e2008-04-25 01:59:09 +00002628 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002629
Benjamin Petersone41251e2008-04-25 01:59:09 +00002630 Returns the message ID for the record. If you are using your own messages,
2631 you could do this by having the *msg* passed to the logger being an ID
2632 rather than a format string. Then, in here, you could use a dictionary
2633 lookup to get the message ID. This version returns 1, which is the base
2634 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002635
Vinay Sajipd31f3632010-06-29 15:31:15 +00002636.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002637
2638SMTPHandler
2639^^^^^^^^^^^
2640
2641The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2642supports sending logging messages to an email address via SMTP.
2643
2644
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002645.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002646
2647 Returns a new instance of the :class:`SMTPHandler` class. The instance is
2648 initialized with the from and to addresses and subject line of the email. The
2649 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
2650 the (host, port) tuple format for the *mailhost* argument. If you use a string,
2651 the standard SMTP port is used. If your SMTP server requires authentication, you
2652 can specify a (username, password) tuple for the *credentials* argument.
2653
Georg Brandl116aa622007-08-15 14:28:22 +00002654
Benjamin Petersone41251e2008-04-25 01:59:09 +00002655 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002656
Benjamin Petersone41251e2008-04-25 01:59:09 +00002657 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00002658
2659
Benjamin Petersone41251e2008-04-25 01:59:09 +00002660 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002661
Benjamin Petersone41251e2008-04-25 01:59:09 +00002662 If you want to specify a subject line which is record-dependent, override
2663 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00002664
Vinay Sajipd31f3632010-06-29 15:31:15 +00002665.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002666
2667MemoryHandler
2668^^^^^^^^^^^^^
2669
2670The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
2671supports buffering of logging records in memory, periodically flushing them to a
2672:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
2673event of a certain severity or greater is seen.
2674
2675:class:`MemoryHandler` is a subclass of the more general
2676:class:`BufferingHandler`, which is an abstract class. This buffers logging
2677records in memory. Whenever each record is added to the buffer, a check is made
2678by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
2679should, then :meth:`flush` is expected to do the needful.
2680
2681
2682.. class:: BufferingHandler(capacity)
2683
2684 Initializes the handler with a buffer of the specified capacity.
2685
2686
Benjamin Petersone41251e2008-04-25 01:59:09 +00002687 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002688
Benjamin Petersone41251e2008-04-25 01:59:09 +00002689 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
2690 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002691
2692
Benjamin Petersone41251e2008-04-25 01:59:09 +00002693 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002694
Benjamin Petersone41251e2008-04-25 01:59:09 +00002695 You can override this to implement custom flushing behavior. This version
2696 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002697
2698
Benjamin Petersone41251e2008-04-25 01:59:09 +00002699 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002700
Benjamin Petersone41251e2008-04-25 01:59:09 +00002701 Returns true if the buffer is up to capacity. This method can be
2702 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00002703
2704
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002705.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002706
2707 Returns a new instance of the :class:`MemoryHandler` class. The instance is
2708 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
2709 :const:`ERROR` is used. If no *target* is specified, the target will need to be
2710 set using :meth:`setTarget` before this handler does anything useful.
2711
2712
Benjamin Petersone41251e2008-04-25 01:59:09 +00002713 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002714
Benjamin Petersone41251e2008-04-25 01:59:09 +00002715 Calls :meth:`flush`, sets the target to :const:`None` and clears the
2716 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00002717
2718
Benjamin Petersone41251e2008-04-25 01:59:09 +00002719 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002720
Benjamin Petersone41251e2008-04-25 01:59:09 +00002721 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00002722 records to the target, if there is one. The buffer is also cleared when
2723 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00002724
2725
Benjamin Petersone41251e2008-04-25 01:59:09 +00002726 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00002727
Benjamin Petersone41251e2008-04-25 01:59:09 +00002728 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00002729
2730
Benjamin Petersone41251e2008-04-25 01:59:09 +00002731 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002732
Benjamin Petersone41251e2008-04-25 01:59:09 +00002733 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00002734
2735
Vinay Sajipd31f3632010-06-29 15:31:15 +00002736.. _http-handler:
2737
Georg Brandl116aa622007-08-15 14:28:22 +00002738HTTPHandler
2739^^^^^^^^^^^
2740
2741The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
2742supports sending logging messages to a Web server, using either ``GET`` or
2743``POST`` semantics.
2744
2745
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002746.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002747
Vinay Sajip1b5646a2010-09-13 20:37:50 +00002748 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
2749 of the form ``host:port``, should you need to use a specific port number.
2750 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
2751 connection will be used. If *credentials* is specified, it should be a
2752 2-tuple consisting of userid and password, which will be placed in an HTTP
2753 'Authorization' header using Basic authentication. If you specify
2754 credentials, you should also specify secure=True so that your userid and
2755 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00002756
2757
Benjamin Petersone41251e2008-04-25 01:59:09 +00002758 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002759
Senthil Kumaranf0769e82010-08-09 19:53:52 +00002760 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002761
2762
Vinay Sajip121a1c42010-09-08 10:46:15 +00002763.. _queue-handler:
2764
2765
2766QueueHandler
2767^^^^^^^^^^^^
2768
2769The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
2770supports sending logging messages to a queue, such as those implemented in the
2771:mod:`queue` or :mod:`multiprocessing` modules.
2772
Vinay Sajip0637d492010-09-23 08:15:54 +00002773Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
2774to let handlers do their work on a separate thread from the one which does the
2775logging. This is important in Web applications and also other service
2776applications where threads servicing clients need to respond as quickly as
2777possible, while any potentially slow operations (such as sending an email via
2778:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002779
2780.. class:: QueueHandler(queue)
2781
2782 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00002783 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00002784 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00002785 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002786
2787
2788 .. method:: emit(record)
2789
Vinay Sajip0258ce82010-09-22 20:34:53 +00002790 Enqueues the result of preparing the LogRecord.
2791
2792 .. method:: prepare(record)
2793
2794 Prepares a record for queuing. The object returned by this
2795 method is enqueued.
2796
2797 The base implementation formats the record to merge the message
2798 and arguments, and removes unpickleable items from the record
2799 in-place.
2800
2801 You might want to override this method if you want to convert
2802 the record to a dict or JSON string, or send a modified copy
2803 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00002804
2805 .. method:: enqueue(record)
2806
2807 Enqueues the record on the queue using ``put_nowait()``; you may
2808 want to override this if you want to use blocking behaviour, or a
2809 timeout, or a customised queue implementation.
2810
2811
2812.. versionadded:: 3.2
2813
2814The :class:`QueueHandler` class was not present in previous versions.
2815
Vinay Sajip0637d492010-09-23 08:15:54 +00002816.. queue-listener:
2817
2818QueueListener
2819^^^^^^^^^^^^^
2820
2821The :class:`QueueListener` class, located in the :mod:`logging.handlers`
2822module, supports receiving logging messages from a queue, such as those
2823implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
2824messages are received from a queue in an internal thread and passed, on
2825the same thread, to one or more handlers for processing.
2826
2827Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
2828to let handlers do their work on a separate thread from the one which does the
2829logging. This is important in Web applications and also other service
2830applications where threads servicing clients need to respond as quickly as
2831possible, while any potentially slow operations (such as sending an email via
2832:class:`SMTPHandler`) are done on a separate thread.
2833
2834.. class:: QueueListener(queue, *handlers)
2835
2836 Returns a new instance of the :class:`QueueListener` class. The instance is
2837 initialized with the queue to send messages to and a list of handlers which
2838 will handle entries placed on the queue. The queue can be any queue-
2839 like object; it's passed as-is to the :meth:`dequeue` method, which needs
2840 to know how to get messages from it.
2841
2842 .. method:: dequeue(block)
2843
2844 Dequeues a record and return it, optionally blocking.
2845
2846 The base implementation uses ``get()``. You may want to override this
2847 method if you want to use timeouts or work with custom queue
2848 implementations.
2849
2850 .. method:: prepare(record)
2851
2852 Prepare a record for handling.
2853
2854 This implementation just returns the passed-in record. You may want to
2855 override this method if you need to do any custom marshalling or
2856 manipulation of the record before passing it to the handlers.
2857
2858 .. method:: handle(record)
2859
2860 Handle a record.
2861
2862 This just loops through the handlers offering them the record
2863 to handle. The actual object passed to the handlers is that which
2864 is returned from :meth:`prepare`.
2865
2866 .. method:: start()
2867
2868 Starts the listener.
2869
2870 This starts up a background thread to monitor the queue for
2871 LogRecords to process.
2872
2873 .. method:: stop()
2874
2875 Stops the listener.
2876
2877 This asks the thread to terminate, and then waits for it to do so.
2878 Note that if you don't call this before your application exits, there
2879 may be some records still left on the queue, which won't be processed.
2880
2881.. versionadded:: 3.2
2882
2883The :class:`QueueListener` class was not present in previous versions.
2884
Vinay Sajip63891ed2010-09-13 20:02:39 +00002885.. _zeromq-handlers:
2886
Vinay Sajip0637d492010-09-23 08:15:54 +00002887Subclassing QueueHandler
2888^^^^^^^^^^^^^^^^^^^^^^^^
2889
Vinay Sajip63891ed2010-09-13 20:02:39 +00002890You can use a :class:`QueueHandler` subclass to send messages to other kinds
2891of queues, for example a ZeroMQ "publish" socket. In the example below,the
2892socket is created separately and passed to the handler (as its 'queue')::
2893
2894 import zmq # using pyzmq, the Python binding for ZeroMQ
2895 import json # for serializing records portably
2896
2897 ctx = zmq.Context()
2898 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
2899 sock.bind('tcp://*:5556') # or wherever
2900
2901 class ZeroMQSocketHandler(QueueHandler):
2902 def enqueue(self, record):
2903 data = json.dumps(record.__dict__)
2904 self.queue.send(data)
2905
Vinay Sajip0055c422010-09-14 09:42:39 +00002906 handler = ZeroMQSocketHandler(sock)
2907
2908
Vinay Sajip63891ed2010-09-13 20:02:39 +00002909Of course there are other ways of organizing this, for example passing in the
2910data needed by the handler to create the socket::
2911
2912 class ZeroMQSocketHandler(QueueHandler):
2913 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
2914 self.ctx = ctx or zmq.Context()
2915 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00002916 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00002917 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00002918
2919 def enqueue(self, record):
2920 data = json.dumps(record.__dict__)
2921 self.queue.send(data)
2922
Vinay Sajipde726922010-09-14 06:59:24 +00002923 def close(self):
2924 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00002925
Vinay Sajip0637d492010-09-23 08:15:54 +00002926Subclassing QueueListener
2927^^^^^^^^^^^^^^^^^^^^^^^^^
2928
2929You can also subclass :class:`QueueListener` to get messages from other kinds
2930of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
2931
2932 class ZeroMQSocketListener(QueueListener):
2933 def __init__(self, uri, *handlers, **kwargs):
2934 self.ctx = kwargs.get('ctx') or zmq.Context()
2935 socket = zmq.Socket(self.ctx, zmq.SUB)
2936 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
2937 socket.connect(uri)
2938
2939 def dequeue(self):
2940 msg = self.queue.recv()
2941 return logging.makeLogRecord(json.loads(msg))
2942
Christian Heimes8b0facf2007-12-04 19:30:01 +00002943.. _formatter-objects:
2944
Georg Brandl116aa622007-08-15 14:28:22 +00002945Formatter Objects
2946-----------------
2947
Benjamin Peterson75edad02009-01-01 15:05:06 +00002948.. currentmodule:: logging
2949
Georg Brandl116aa622007-08-15 14:28:22 +00002950:class:`Formatter`\ s have the following attributes and methods. They are
2951responsible for converting a :class:`LogRecord` to (usually) a string which can
2952be interpreted by either a human or an external system. The base
2953:class:`Formatter` allows a formatting string to be specified. If none is
2954supplied, the default value of ``'%(message)s'`` is used.
2955
2956A Formatter can be initialized with a format string which makes use of knowledge
2957of the :class:`LogRecord` attributes - such as the default value mentioned above
2958making use of the fact that the user's message and arguments are pre-formatted
2959into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002960standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00002961for more information on string formatting.
2962
2963Currently, the useful mapping keys in a :class:`LogRecord` are:
2964
2965+-------------------------+-----------------------------------------------+
2966| Format | Description |
2967+=========================+===============================================+
2968| ``%(name)s`` | Name of the logger (logging channel). |
2969+-------------------------+-----------------------------------------------+
2970| ``%(levelno)s`` | Numeric logging level for the message |
2971| | (:const:`DEBUG`, :const:`INFO`, |
2972| | :const:`WARNING`, :const:`ERROR`, |
2973| | :const:`CRITICAL`). |
2974+-------------------------+-----------------------------------------------+
2975| ``%(levelname)s`` | Text logging level for the message |
2976| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
2977| | ``'ERROR'``, ``'CRITICAL'``). |
2978+-------------------------+-----------------------------------------------+
2979| ``%(pathname)s`` | Full pathname of the source file where the |
2980| | logging call was issued (if available). |
2981+-------------------------+-----------------------------------------------+
2982| ``%(filename)s`` | Filename portion of pathname. |
2983+-------------------------+-----------------------------------------------+
2984| ``%(module)s`` | Module (name portion of filename). |
2985+-------------------------+-----------------------------------------------+
2986| ``%(funcName)s`` | Name of function containing the logging call. |
2987+-------------------------+-----------------------------------------------+
2988| ``%(lineno)d`` | Source line number where the logging call was |
2989| | issued (if available). |
2990+-------------------------+-----------------------------------------------+
2991| ``%(created)f`` | Time when the :class:`LogRecord` was created |
2992| | (as returned by :func:`time.time`). |
2993+-------------------------+-----------------------------------------------+
2994| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
2995| | created, relative to the time the logging |
2996| | module was loaded. |
2997+-------------------------+-----------------------------------------------+
2998| ``%(asctime)s`` | Human-readable time when the |
2999| | :class:`LogRecord` was created. By default |
3000| | this is of the form "2003-07-08 16:49:45,896" |
3001| | (the numbers after the comma are millisecond |
3002| | portion of the time). |
3003+-------------------------+-----------------------------------------------+
3004| ``%(msecs)d`` | Millisecond portion of the time when the |
3005| | :class:`LogRecord` was created. |
3006+-------------------------+-----------------------------------------------+
3007| ``%(thread)d`` | Thread ID (if available). |
3008+-------------------------+-----------------------------------------------+
3009| ``%(threadName)s`` | Thread name (if available). |
3010+-------------------------+-----------------------------------------------+
3011| ``%(process)d`` | Process ID (if available). |
3012+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003013| ``%(processName)s`` | Process name (if available). |
3014+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003015| ``%(message)s`` | The logged message, computed as ``msg % |
3016| | args``. |
3017+-------------------------+-----------------------------------------------+
3018
Georg Brandl116aa622007-08-15 14:28:22 +00003019
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003020.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003021
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003022 Returns a new instance of the :class:`Formatter` class. The instance is
3023 initialized with a format string for the message as a whole, as well as a
3024 format string for the date/time portion of a message. If no *fmt* is
3025 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3026 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003027
Benjamin Petersone41251e2008-04-25 01:59:09 +00003028 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003029
Benjamin Petersone41251e2008-04-25 01:59:09 +00003030 The record's attribute dictionary is used as the operand to a string
3031 formatting operation. Returns the resulting string. Before formatting the
3032 dictionary, a couple of preparatory steps are carried out. The *message*
3033 attribute of the record is computed using *msg* % *args*. If the
3034 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3035 to format the event time. If there is exception information, it is
3036 formatted using :meth:`formatException` and appended to the message. Note
3037 that the formatted exception information is cached in attribute
3038 *exc_text*. This is useful because the exception information can be
3039 pickled and sent across the wire, but you should be careful if you have
3040 more than one :class:`Formatter` subclass which customizes the formatting
3041 of exception information. In this case, you will have to clear the cached
3042 value after a formatter has done its formatting, so that the next
3043 formatter to handle the event doesn't use the cached value but
3044 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003045
3046
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003047 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003048
Benjamin Petersone41251e2008-04-25 01:59:09 +00003049 This method should be called from :meth:`format` by a formatter which
3050 wants to make use of a formatted time. This method can be overridden in
3051 formatters to provide for any specific requirement, but the basic behavior
3052 is as follows: if *datefmt* (a string) is specified, it is used with
3053 :func:`time.strftime` to format the creation time of the
3054 record. Otherwise, the ISO8601 format is used. The resulting string is
3055 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003056
3057
Benjamin Petersone41251e2008-04-25 01:59:09 +00003058 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003059
Benjamin Petersone41251e2008-04-25 01:59:09 +00003060 Formats the specified exception information (a standard exception tuple as
3061 returned by :func:`sys.exc_info`) as a string. This default implementation
3062 just uses :func:`traceback.print_exception`. The resulting string is
3063 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003064
Vinay Sajipd31f3632010-06-29 15:31:15 +00003065.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003066
3067Filter Objects
3068--------------
3069
Georg Brandl5c66bca2010-10-29 05:36:28 +00003070``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003071filtering than is provided by levels. The base filter class only allows events
3072which are below a certain point in the logger hierarchy. For example, a filter
3073initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3074"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3075empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003076
3077
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003078.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003079
3080 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3081 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003082 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003083
3084
Benjamin Petersone41251e2008-04-25 01:59:09 +00003085 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003086
Benjamin Petersone41251e2008-04-25 01:59:09 +00003087 Is the specified record to be logged? Returns zero for no, nonzero for
3088 yes. If deemed appropriate, the record may be modified in-place by this
3089 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003090
Vinay Sajip81010212010-08-19 19:17:41 +00003091Note that filters attached to handlers are consulted whenever an event is
3092emitted by the handler, whereas filters attached to loggers are consulted
3093whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3094etc.) This means that events which have been generated by descendant loggers
3095will not be filtered by a logger's filter setting, unless the filter has also
3096been applied to those descendant loggers.
3097
Vinay Sajip22246fd2010-10-20 11:40:02 +00003098You don't actually need to subclass ``Filter``: you can pass any instance
3099which has a ``filter`` method with the same semantics.
3100
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003101.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003102 You don't need to create specialized ``Filter`` classes, or use other
3103 classes with a ``filter`` method: you can use a function (or other
3104 callable) as a filter. The filtering logic will check to see if the filter
3105 object has a ``filter`` attribute: if it does, it's assumed to be a
3106 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3107 assumed to be a callable and called with the record as the single
3108 parameter. The returned value should conform to that returned by
3109 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003110
Vinay Sajipac007992010-09-17 12:45:26 +00003111Other uses for filters
3112^^^^^^^^^^^^^^^^^^^^^^
3113
3114Although filters are used primarily to filter records based on more
3115sophisticated criteria than levels, they get to see every record which is
3116processed by the handler or logger they're attached to: this can be useful if
3117you want to do things like counting how many records were processed by a
3118particular logger or handler, or adding, changing or removing attributes in
3119the LogRecord being processed. Obviously changing the LogRecord needs to be
3120done with some care, but it does allow the injection of contextual information
3121into logs (see :ref:`filters-contextual`).
3122
Vinay Sajipd31f3632010-06-29 15:31:15 +00003123.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003124
3125LogRecord Objects
3126-----------------
3127
Vinay Sajip4039aff2010-09-11 10:25:28 +00003128:class:`LogRecord` instances are created automatically by the :class:`Logger`
3129every time something is logged, and can be created manually via
3130:func:`makeLogRecord` (for example, from a pickled event received over the
3131wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003132
3133
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003134.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003135
Vinay Sajip4039aff2010-09-11 10:25:28 +00003136 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003137
Vinay Sajip4039aff2010-09-11 10:25:28 +00003138 The primary information is passed in :attr:`msg` and :attr:`args`, which
3139 are combined using ``msg % args`` to create the :attr:`message` field of the
3140 record.
3141
3142 .. attribute:: args
3143
3144 Tuple of arguments to be used in formatting :attr:`msg`.
3145
3146 .. attribute:: exc_info
3147
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003148 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003149 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003150
3151 .. attribute:: func
3152
3153 Name of the function of origin (i.e. in which the logging call was made).
3154
3155 .. attribute:: lineno
3156
3157 Line number in the source file of origin.
3158
3159 .. attribute:: lvl
3160
3161 Numeric logging level.
3162
3163 .. attribute:: message
3164
3165 Bound to the result of :meth:`getMessage` when
3166 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3167
3168 .. attribute:: msg
3169
3170 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3171 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3172
3173 .. attribute:: name
3174
3175 Name of the logger that emitted the record.
3176
3177 .. attribute:: pathname
3178
3179 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003180
Benjamin Petersone41251e2008-04-25 01:59:09 +00003181 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003182
Benjamin Petersone41251e2008-04-25 01:59:09 +00003183 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003184 user-supplied arguments with the message. If the user-supplied message
3185 argument to the logging call is not a string, :func:`str` is called on it to
3186 convert it to a string. This allows use of user-defined classes as
3187 messages, whose ``__str__`` method can return the actual format string to
3188 be used.
3189
Vinay Sajipd31f3632010-06-29 15:31:15 +00003190.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003191
Christian Heimes04c420f2008-01-18 18:40:46 +00003192LoggerAdapter Objects
3193---------------------
3194
Christian Heimes04c420f2008-01-18 18:40:46 +00003195:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003196information into logging calls. For a usage example , see the section on
3197`adding contextual information to your logging output`__.
3198
3199__ context-info_
Christian Heimes04c420f2008-01-18 18:40:46 +00003200
3201.. class:: LoggerAdapter(logger, extra)
3202
3203 Returns an instance of :class:`LoggerAdapter` initialized with an
3204 underlying :class:`Logger` instance and a dict-like object.
3205
Benjamin Petersone41251e2008-04-25 01:59:09 +00003206 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003207
Benjamin Petersone41251e2008-04-25 01:59:09 +00003208 Modifies the message and/or keyword arguments passed to a logging call in
3209 order to insert contextual information. This implementation takes the object
3210 passed as *extra* to the constructor and adds it to *kwargs* using key
3211 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3212 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003213
Vinay Sajipc84f0162010-09-21 11:25:39 +00003214In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003215methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003216:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3217:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3218:meth:`hasHandlers`. These methods have the same signatures as their
3219counterparts in :class:`Logger`, so you can use the two types of instances
3220interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003221
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003222.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003223 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3224 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3225 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003226
Georg Brandl116aa622007-08-15 14:28:22 +00003227
3228Thread Safety
3229-------------
3230
3231The logging module is intended to be thread-safe without any special work
3232needing to be done by its clients. It achieves this though using threading
3233locks; there is one lock to serialize access to the module's shared data, and
3234each handler also creates a lock to serialize access to its underlying I/O.
3235
Benjamin Petersond23f8222009-04-05 19:13:16 +00003236If you are implementing asynchronous signal handlers using the :mod:`signal`
3237module, you may not be able to use logging from within such handlers. This is
3238because lock implementations in the :mod:`threading` module are not always
3239re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003240
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003241
3242Integration with the warnings module
3243------------------------------------
3244
3245The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3246with the :mod:`warnings` module.
3247
3248.. function:: captureWarnings(capture)
3249
3250 This function is used to turn the capture of warnings by logging on and
3251 off.
3252
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003253 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3254 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003255 formatted using :func:`warnings.formatwarning` and the resulting string
3256 logged to a logger named "py.warnings" with a severity of `WARNING`.
3257
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003258 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003259 will stop, and warnings will be redirected to their original destinations
3260 (i.e. those in effect before `captureWarnings(True)` was called).
3261
3262
Georg Brandl116aa622007-08-15 14:28:22 +00003263Configuration
3264-------------
3265
3266
3267.. _logging-config-api:
3268
3269Configuration functions
3270^^^^^^^^^^^^^^^^^^^^^^^
3271
Georg Brandl116aa622007-08-15 14:28:22 +00003272The following functions configure the logging module. They are located in the
3273:mod:`logging.config` module. Their use is optional --- you can configure the
3274logging module using these functions or by making calls to the main API (defined
3275in :mod:`logging` itself) and defining handlers which are declared either in
3276:mod:`logging` or :mod:`logging.handlers`.
3277
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003278.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003279
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003280 Takes the logging configuration from a dictionary. The contents of
3281 this dictionary are described in :ref:`logging-config-dictschema`
3282 below.
3283
3284 If an error is encountered during configuration, this function will
3285 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3286 or :exc:`ImportError` with a suitably descriptive message. The
3287 following is a (possibly incomplete) list of conditions which will
3288 raise an error:
3289
3290 * A ``level`` which is not a string or which is a string not
3291 corresponding to an actual logging level.
3292 * A ``propagate`` value which is not a boolean.
3293 * An id which does not have a corresponding destination.
3294 * A non-existent handler id found during an incremental call.
3295 * An invalid logger name.
3296 * Inability to resolve to an internal or external object.
3297
3298 Parsing is performed by the :class:`DictConfigurator` class, whose
3299 constructor is passed the dictionary used for configuration, and
3300 has a :meth:`configure` method. The :mod:`logging.config` module
3301 has a callable attribute :attr:`dictConfigClass`
3302 which is initially set to :class:`DictConfigurator`.
3303 You can replace the value of :attr:`dictConfigClass` with a
3304 suitable implementation of your own.
3305
3306 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3307 the specified dictionary, and then calls the :meth:`configure` method on
3308 the returned object to put the configuration into effect::
3309
3310 def dictConfig(config):
3311 dictConfigClass(config).configure()
3312
3313 For example, a subclass of :class:`DictConfigurator` could call
3314 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3315 set up custom prefixes which would be usable in the subsequent
3316 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3317 this new subclass, and then :func:`dictConfig` could be called exactly as
3318 in the default, uncustomized state.
3319
3320.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003321
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003322 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003323 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003324 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003325 configurations (if the developer provides a mechanism to present the choices
3326 and load the chosen configuration). Defaults to be passed to the ConfigParser
3327 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003328
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003329
3330.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003331
3332 Starts up a socket server on the specified port, and listens for new
3333 configurations. If no port is specified, the module's default
3334 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3335 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3336 :class:`Thread` instance on which you can call :meth:`start` to start the
3337 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003338 call :func:`stopListening`.
3339
3340 To send a configuration to the socket, read in the configuration file and
3341 send it to the socket as a string of bytes preceded by a four-byte length
3342 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003343
3344
3345.. function:: stopListening()
3346
Christian Heimes8b0facf2007-12-04 19:30:01 +00003347 Stops the listening server which was created with a call to :func:`listen`.
3348 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003349 :func:`listen`.
3350
3351
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003352.. _logging-config-dictschema:
3353
3354Configuration dictionary schema
3355^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3356
3357Describing a logging configuration requires listing the various
3358objects to create and the connections between them; for example, you
3359may create a handler named "console" and then say that the logger
3360named "startup" will send its messages to the "console" handler.
3361These objects aren't limited to those provided by the :mod:`logging`
3362module because you might write your own formatter or handler class.
3363The parameters to these classes may also need to include external
3364objects such as ``sys.stderr``. The syntax for describing these
3365objects and connections is defined in :ref:`logging-config-dict-connections`
3366below.
3367
3368Dictionary Schema Details
3369"""""""""""""""""""""""""
3370
3371The dictionary passed to :func:`dictConfig` must contain the following
3372keys:
3373
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003374* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003375 version. The only valid value at present is 1, but having this key
3376 allows the schema to evolve while still preserving backwards
3377 compatibility.
3378
3379All other keys are optional, but if present they will be interpreted
3380as described below. In all cases below where a 'configuring dict' is
3381mentioned, it will be checked for the special ``'()'`` key to see if a
3382custom instantiation is required. If so, the mechanism described in
3383:ref:`logging-config-dict-userdef` below is used to create an instance;
3384otherwise, the context is used to determine what to instantiate.
3385
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003386* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003387 key is a formatter id and each value is a dict describing how to
3388 configure the corresponding Formatter instance.
3389
3390 The configuring dict is searched for keys ``format`` and ``datefmt``
3391 (with defaults of ``None``) and these are used to construct a
3392 :class:`logging.Formatter` instance.
3393
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003394* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003395 is a filter id and each value is a dict describing how to configure
3396 the corresponding Filter instance.
3397
3398 The configuring dict is searched for the key ``name`` (defaulting to the
3399 empty string) and this is used to construct a :class:`logging.Filter`
3400 instance.
3401
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003402* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003403 key is a handler id and each value is a dict describing how to
3404 configure the corresponding Handler instance.
3405
3406 The configuring dict is searched for the following keys:
3407
3408 * ``class`` (mandatory). This is the fully qualified name of the
3409 handler class.
3410
3411 * ``level`` (optional). The level of the handler.
3412
3413 * ``formatter`` (optional). The id of the formatter for this
3414 handler.
3415
3416 * ``filters`` (optional). A list of ids of the filters for this
3417 handler.
3418
3419 All *other* keys are passed through as keyword arguments to the
3420 handler's constructor. For example, given the snippet::
3421
3422 handlers:
3423 console:
3424 class : logging.StreamHandler
3425 formatter: brief
3426 level : INFO
3427 filters: [allow_foo]
3428 stream : ext://sys.stdout
3429 file:
3430 class : logging.handlers.RotatingFileHandler
3431 formatter: precise
3432 filename: logconfig.log
3433 maxBytes: 1024
3434 backupCount: 3
3435
3436 the handler with id ``console`` is instantiated as a
3437 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3438 stream. The handler with id ``file`` is instantiated as a
3439 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3440 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3441
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003442* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003443 is a logger name and each value is a dict describing how to
3444 configure the corresponding Logger instance.
3445
3446 The configuring dict is searched for the following keys:
3447
3448 * ``level`` (optional). The level of the logger.
3449
3450 * ``propagate`` (optional). The propagation setting of the logger.
3451
3452 * ``filters`` (optional). A list of ids of the filters for this
3453 logger.
3454
3455 * ``handlers`` (optional). A list of ids of the handlers for this
3456 logger.
3457
3458 The specified loggers will be configured according to the level,
3459 propagation, filters and handlers specified.
3460
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003461* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003462 Processing of the configuration will be as for any logger, except
3463 that the ``propagate`` setting will not be applicable.
3464
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003465* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003466 incremental to the existing configuration. This value defaults to
3467 ``False``, which means that the specified configuration replaces the
3468 existing configuration with the same semantics as used by the
3469 existing :func:`fileConfig` API.
3470
3471 If the specified value is ``True``, the configuration is processed
3472 as described in the section on :ref:`logging-config-dict-incremental`.
3473
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003474* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003475 disabled. This setting mirrors the parameter of the same name in
3476 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003477 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003478
3479.. _logging-config-dict-incremental:
3480
3481Incremental Configuration
3482"""""""""""""""""""""""""
3483
3484It is difficult to provide complete flexibility for incremental
3485configuration. For example, because objects such as filters
3486and formatters are anonymous, once a configuration is set up, it is
3487not possible to refer to such anonymous objects when augmenting a
3488configuration.
3489
3490Furthermore, there is not a compelling case for arbitrarily altering
3491the object graph of loggers, handlers, filters, formatters at
3492run-time, once a configuration is set up; the verbosity of loggers and
3493handlers can be controlled just by setting levels (and, in the case of
3494loggers, propagation flags). Changing the object graph arbitrarily in
3495a safe way is problematic in a multi-threaded environment; while not
3496impossible, the benefits are not worth the complexity it adds to the
3497implementation.
3498
3499Thus, when the ``incremental`` key of a configuration dict is present
3500and is ``True``, the system will completely ignore any ``formatters`` and
3501``filters`` entries, and process only the ``level``
3502settings in the ``handlers`` entries, and the ``level`` and
3503``propagate`` settings in the ``loggers`` and ``root`` entries.
3504
3505Using a value in the configuration dict lets configurations to be sent
3506over the wire as pickled dicts to a socket listener. Thus, the logging
3507verbosity of a long-running application can be altered over time with
3508no need to stop and restart the application.
3509
3510.. _logging-config-dict-connections:
3511
3512Object connections
3513""""""""""""""""""
3514
3515The schema describes a set of logging objects - loggers,
3516handlers, formatters, filters - which are connected to each other in
3517an object graph. Thus, the schema needs to represent connections
3518between the objects. For example, say that, once configured, a
3519particular logger has attached to it a particular handler. For the
3520purposes of this discussion, we can say that the logger represents the
3521source, and the handler the destination, of a connection between the
3522two. Of course in the configured objects this is represented by the
3523logger holding a reference to the handler. In the configuration dict,
3524this is done by giving each destination object an id which identifies
3525it unambiguously, and then using the id in the source object's
3526configuration to indicate that a connection exists between the source
3527and the destination object with that id.
3528
3529So, for example, consider the following YAML snippet::
3530
3531 formatters:
3532 brief:
3533 # configuration for formatter with id 'brief' goes here
3534 precise:
3535 # configuration for formatter with id 'precise' goes here
3536 handlers:
3537 h1: #This is an id
3538 # configuration of handler with id 'h1' goes here
3539 formatter: brief
3540 h2: #This is another id
3541 # configuration of handler with id 'h2' goes here
3542 formatter: precise
3543 loggers:
3544 foo.bar.baz:
3545 # other configuration for logger 'foo.bar.baz'
3546 handlers: [h1, h2]
3547
3548(Note: YAML used here because it's a little more readable than the
3549equivalent Python source form for the dictionary.)
3550
3551The ids for loggers are the logger names which would be used
3552programmatically to obtain a reference to those loggers, e.g.
3553``foo.bar.baz``. The ids for Formatters and Filters can be any string
3554value (such as ``brief``, ``precise`` above) and they are transient,
3555in that they are only meaningful for processing the configuration
3556dictionary and used to determine connections between objects, and are
3557not persisted anywhere when the configuration call is complete.
3558
3559The above snippet indicates that logger named ``foo.bar.baz`` should
3560have two handlers attached to it, which are described by the handler
3561ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3562``brief``, and the formatter for ``h2`` is that described by id
3563``precise``.
3564
3565
3566.. _logging-config-dict-userdef:
3567
3568User-defined objects
3569""""""""""""""""""""
3570
3571The schema supports user-defined objects for handlers, filters and
3572formatters. (Loggers do not need to have different types for
3573different instances, so there is no support in this configuration
3574schema for user-defined logger classes.)
3575
3576Objects to be configured are described by dictionaries
3577which detail their configuration. In some places, the logging system
3578will be able to infer from the context how an object is to be
3579instantiated, but when a user-defined object is to be instantiated,
3580the system will not know how to do this. In order to provide complete
3581flexibility for user-defined object instantiation, the user needs
3582to provide a 'factory' - a callable which is called with a
3583configuration dictionary and which returns the instantiated object.
3584This is signalled by an absolute import path to the factory being
3585made available under the special key ``'()'``. Here's a concrete
3586example::
3587
3588 formatters:
3589 brief:
3590 format: '%(message)s'
3591 default:
3592 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3593 datefmt: '%Y-%m-%d %H:%M:%S'
3594 custom:
3595 (): my.package.customFormatterFactory
3596 bar: baz
3597 spam: 99.9
3598 answer: 42
3599
3600The above YAML snippet defines three formatters. The first, with id
3601``brief``, is a standard :class:`logging.Formatter` instance with the
3602specified format string. The second, with id ``default``, has a
3603longer format and also defines the time format explicitly, and will
3604result in a :class:`logging.Formatter` initialized with those two format
3605strings. Shown in Python source form, the ``brief`` and ``default``
3606formatters have configuration sub-dictionaries::
3607
3608 {
3609 'format' : '%(message)s'
3610 }
3611
3612and::
3613
3614 {
3615 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
3616 'datefmt' : '%Y-%m-%d %H:%M:%S'
3617 }
3618
3619respectively, and as these dictionaries do not contain the special key
3620``'()'``, the instantiation is inferred from the context: as a result,
3621standard :class:`logging.Formatter` instances are created. The
3622configuration sub-dictionary for the third formatter, with id
3623``custom``, is::
3624
3625 {
3626 '()' : 'my.package.customFormatterFactory',
3627 'bar' : 'baz',
3628 'spam' : 99.9,
3629 'answer' : 42
3630 }
3631
3632and this contains the special key ``'()'``, which means that
3633user-defined instantiation is wanted. In this case, the specified
3634factory callable will be used. If it is an actual callable it will be
3635used directly - otherwise, if you specify a string (as in the example)
3636the actual callable will be located using normal import mechanisms.
3637The callable will be called with the **remaining** items in the
3638configuration sub-dictionary as keyword arguments. In the above
3639example, the formatter with id ``custom`` will be assumed to be
3640returned by the call::
3641
3642 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
3643
3644The key ``'()'`` has been used as the special key because it is not a
3645valid keyword parameter name, and so will not clash with the names of
3646the keyword arguments used in the call. The ``'()'`` also serves as a
3647mnemonic that the corresponding value is a callable.
3648
3649
3650.. _logging-config-dict-externalobj:
3651
3652Access to external objects
3653""""""""""""""""""""""""""
3654
3655There are times where a configuration needs to refer to objects
3656external to the configuration, for example ``sys.stderr``. If the
3657configuration dict is constructed using Python code, this is
3658straightforward, but a problem arises when the configuration is
3659provided via a text file (e.g. JSON, YAML). In a text file, there is
3660no standard way to distinguish ``sys.stderr`` from the literal string
3661``'sys.stderr'``. To facilitate this distinction, the configuration
3662system looks for certain special prefixes in string values and
3663treat them specially. For example, if the literal string
3664``'ext://sys.stderr'`` is provided as a value in the configuration,
3665then the ``ext://`` will be stripped off and the remainder of the
3666value processed using normal import mechanisms.
3667
3668The handling of such prefixes is done in a way analogous to protocol
3669handling: there is a generic mechanism to look for prefixes which
3670match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
3671whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
3672in a prefix-dependent manner and the result of the processing replaces
3673the string value. If the prefix is not recognised, then the string
3674value will be left as-is.
3675
3676
3677.. _logging-config-dict-internalobj:
3678
3679Access to internal objects
3680""""""""""""""""""""""""""
3681
3682As well as external objects, there is sometimes also a need to refer
3683to objects in the configuration. This will be done implicitly by the
3684configuration system for things that it knows about. For example, the
3685string value ``'DEBUG'`` for a ``level`` in a logger or handler will
3686automatically be converted to the value ``logging.DEBUG``, and the
3687``handlers``, ``filters`` and ``formatter`` entries will take an
3688object id and resolve to the appropriate destination object.
3689
3690However, a more generic mechanism is needed for user-defined
3691objects which are not known to the :mod:`logging` module. For
3692example, consider :class:`logging.handlers.MemoryHandler`, which takes
3693a ``target`` argument which is another handler to delegate to. Since
3694the system already knows about this class, then in the configuration,
3695the given ``target`` just needs to be the object id of the relevant
3696target handler, and the system will resolve to the handler from the
3697id. If, however, a user defines a ``my.package.MyHandler`` which has
3698an ``alternate`` handler, the configuration system would not know that
3699the ``alternate`` referred to a handler. To cater for this, a generic
3700resolution system allows the user to specify::
3701
3702 handlers:
3703 file:
3704 # configuration of file handler goes here
3705
3706 custom:
3707 (): my.package.MyHandler
3708 alternate: cfg://handlers.file
3709
3710The literal string ``'cfg://handlers.file'`` will be resolved in an
3711analogous way to strings with the ``ext://`` prefix, but looking
3712in the configuration itself rather than the import namespace. The
3713mechanism allows access by dot or by index, in a similar way to
3714that provided by ``str.format``. Thus, given the following snippet::
3715
3716 handlers:
3717 email:
3718 class: logging.handlers.SMTPHandler
3719 mailhost: localhost
3720 fromaddr: my_app@domain.tld
3721 toaddrs:
3722 - support_team@domain.tld
3723 - dev_team@domain.tld
3724 subject: Houston, we have a problem.
3725
3726in the configuration, the string ``'cfg://handlers'`` would resolve to
3727the dict with key ``handlers``, the string ``'cfg://handlers.email``
3728would resolve to the dict with key ``email`` in the ``handlers`` dict,
3729and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
3730resolve to ``'dev_team.domain.tld'`` and the string
3731``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
3732``'support_team@domain.tld'``. The ``subject`` value could be accessed
3733using either ``'cfg://handlers.email.subject'`` or, equivalently,
3734``'cfg://handlers.email[subject]'``. The latter form only needs to be
3735used if the key contains spaces or non-alphanumeric characters. If an
3736index value consists only of decimal digits, access will be attempted
3737using the corresponding integer value, falling back to the string
3738value if needed.
3739
3740Given a string ``cfg://handlers.myhandler.mykey.123``, this will
3741resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
3742If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
3743the system will attempt to retrieve the value from
3744``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
3745to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
3746fails.
3747
Georg Brandl116aa622007-08-15 14:28:22 +00003748.. _logging-config-fileformat:
3749
3750Configuration file format
3751^^^^^^^^^^^^^^^^^^^^^^^^^
3752
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003753The configuration file format understood by :func:`fileConfig` is based on
3754:mod:`configparser` functionality. The file must contain sections called
3755``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
3756entities of each type which are defined in the file. For each such entity, there
3757is a separate section which identifies how that entity is configured. Thus, for
3758a logger named ``log01`` in the ``[loggers]`` section, the relevant
3759configuration details are held in a section ``[logger_log01]``. Similarly, a
3760handler called ``hand01`` in the ``[handlers]`` section will have its
3761configuration held in a section called ``[handler_hand01]``, while a formatter
3762called ``form01`` in the ``[formatters]`` section will have its configuration
3763specified in a section called ``[formatter_form01]``. The root logger
3764configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00003765
3766Examples of these sections in the file are given below. ::
3767
3768 [loggers]
3769 keys=root,log02,log03,log04,log05,log06,log07
3770
3771 [handlers]
3772 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
3773
3774 [formatters]
3775 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
3776
3777The root logger must specify a level and a list of handlers. An example of a
3778root logger section is given below. ::
3779
3780 [logger_root]
3781 level=NOTSET
3782 handlers=hand01
3783
3784The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
3785``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
3786logged. Level values are :func:`eval`\ uated in the context of the ``logging``
3787package's namespace.
3788
3789The ``handlers`` entry is a comma-separated list of handler names, which must
3790appear in the ``[handlers]`` section. These names must appear in the
3791``[handlers]`` section and have corresponding sections in the configuration
3792file.
3793
3794For loggers other than the root logger, some additional information is required.
3795This is illustrated by the following example. ::
3796
3797 [logger_parser]
3798 level=DEBUG
3799 handlers=hand01
3800 propagate=1
3801 qualname=compiler.parser
3802
3803The ``level`` and ``handlers`` entries are interpreted as for the root logger,
3804except that if a non-root logger's level is specified as ``NOTSET``, the system
3805consults loggers higher up the hierarchy to determine the effective level of the
3806logger. The ``propagate`` entry is set to 1 to indicate that messages must
3807propagate to handlers higher up the logger hierarchy from this logger, or 0 to
3808indicate that messages are **not** propagated to handlers up the hierarchy. The
3809``qualname`` entry is the hierarchical channel name of the logger, that is to
3810say the name used by the application to get the logger.
3811
3812Sections which specify handler configuration are exemplified by the following.
3813::
3814
3815 [handler_hand01]
3816 class=StreamHandler
3817 level=NOTSET
3818 formatter=form01
3819 args=(sys.stdout,)
3820
3821The ``class`` entry indicates the handler's class (as determined by :func:`eval`
3822in the ``logging`` package's namespace). The ``level`` is interpreted as for
3823loggers, and ``NOTSET`` is taken to mean "log everything".
3824
3825The ``formatter`` entry indicates the key name of the formatter for this
3826handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
3827If a name is specified, it must appear in the ``[formatters]`` section and have
3828a corresponding section in the configuration file.
3829
3830The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
3831package's namespace, is the list of arguments to the constructor for the handler
3832class. Refer to the constructors for the relevant handlers, or to the examples
3833below, to see how typical entries are constructed. ::
3834
3835 [handler_hand02]
3836 class=FileHandler
3837 level=DEBUG
3838 formatter=form02
3839 args=('python.log', 'w')
3840
3841 [handler_hand03]
3842 class=handlers.SocketHandler
3843 level=INFO
3844 formatter=form03
3845 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
3846
3847 [handler_hand04]
3848 class=handlers.DatagramHandler
3849 level=WARN
3850 formatter=form04
3851 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
3852
3853 [handler_hand05]
3854 class=handlers.SysLogHandler
3855 level=ERROR
3856 formatter=form05
3857 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
3858
3859 [handler_hand06]
3860 class=handlers.NTEventLogHandler
3861 level=CRITICAL
3862 formatter=form06
3863 args=('Python Application', '', 'Application')
3864
3865 [handler_hand07]
3866 class=handlers.SMTPHandler
3867 level=WARN
3868 formatter=form07
3869 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
3870
3871 [handler_hand08]
3872 class=handlers.MemoryHandler
3873 level=NOTSET
3874 formatter=form08
3875 target=
3876 args=(10, ERROR)
3877
3878 [handler_hand09]
3879 class=handlers.HTTPHandler
3880 level=NOTSET
3881 formatter=form09
3882 args=('localhost:9022', '/log', 'GET')
3883
3884Sections which specify formatter configuration are typified by the following. ::
3885
3886 [formatter_form01]
3887 format=F1 %(asctime)s %(levelname)s %(message)s
3888 datefmt=
3889 class=logging.Formatter
3890
3891The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003892the :func:`strftime`\ -compatible date/time format string. If empty, the
3893package substitutes ISO8601 format date/times, which is almost equivalent to
3894specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
3895also specifies milliseconds, which are appended to the result of using the above
3896format string, with a comma separator. An example time in ISO8601 format is
3897``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00003898
3899The ``class`` entry is optional. It indicates the name of the formatter's class
3900(as a dotted module and class name.) This option is useful for instantiating a
3901:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
3902exception tracebacks in an expanded or condensed format.
3903
Christian Heimes8b0facf2007-12-04 19:30:01 +00003904
3905Configuration server example
3906^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3907
3908Here is an example of a module using the logging configuration server::
3909
3910 import logging
3911 import logging.config
3912 import time
3913 import os
3914
3915 # read initial config file
3916 logging.config.fileConfig("logging.conf")
3917
3918 # create and start listener on port 9999
3919 t = logging.config.listen(9999)
3920 t.start()
3921
3922 logger = logging.getLogger("simpleExample")
3923
3924 try:
3925 # loop through logging calls to see the difference
3926 # new configurations make, until Ctrl+C is pressed
3927 while True:
3928 logger.debug("debug message")
3929 logger.info("info message")
3930 logger.warn("warn message")
3931 logger.error("error message")
3932 logger.critical("critical message")
3933 time.sleep(5)
3934 except KeyboardInterrupt:
3935 # cleanup
3936 logging.config.stopListening()
3937 t.join()
3938
3939And here is a script that takes a filename and sends that file to the server,
3940properly preceded with the binary-encoded length, as the new logging
3941configuration::
3942
3943 #!/usr/bin/env python
3944 import socket, sys, struct
3945
3946 data_to_send = open(sys.argv[1], "r").read()
3947
3948 HOST = 'localhost'
3949 PORT = 9999
3950 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00003951 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003952 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00003953 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003954 s.send(struct.pack(">L", len(data_to_send)))
3955 s.send(data_to_send)
3956 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00003957 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00003958
3959
3960More examples
3961-------------
3962
3963Multiple handlers and formatters
3964^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3965
3966Loggers are plain Python objects. The :func:`addHandler` method has no minimum
3967or maximum quota for the number of handlers you may add. Sometimes it will be
3968beneficial for an application to log all messages of all severities to a text
3969file while simultaneously logging errors or above to the console. To set this
3970up, simply configure the appropriate handlers. The logging calls in the
3971application code will remain unchanged. Here is a slight modification to the
3972previous simple module-based configuration example::
3973
3974 import logging
3975
3976 logger = logging.getLogger("simple_example")
3977 logger.setLevel(logging.DEBUG)
3978 # create file handler which logs even debug messages
3979 fh = logging.FileHandler("spam.log")
3980 fh.setLevel(logging.DEBUG)
3981 # create console handler with a higher log level
3982 ch = logging.StreamHandler()
3983 ch.setLevel(logging.ERROR)
3984 # create formatter and add it to the handlers
3985 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3986 ch.setFormatter(formatter)
3987 fh.setFormatter(formatter)
3988 # add the handlers to logger
3989 logger.addHandler(ch)
3990 logger.addHandler(fh)
3991
3992 # "application" code
3993 logger.debug("debug message")
3994 logger.info("info message")
3995 logger.warn("warn message")
3996 logger.error("error message")
3997 logger.critical("critical message")
3998
3999Notice that the "application" code does not care about multiple handlers. All
4000that changed was the addition and configuration of a new handler named *fh*.
4001
4002The ability to create new handlers with higher- or lower-severity filters can be
4003very helpful when writing and testing an application. Instead of using many
4004``print`` statements for debugging, use ``logger.debug``: Unlike the print
4005statements, which you will have to delete or comment out later, the logger.debug
4006statements can remain intact in the source code and remain dormant until you
4007need them again. At that time, the only change that needs to happen is to
4008modify the severity level of the logger and/or handler to debug.
4009
4010
4011Using logging in multiple modules
4012^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4013
4014It was mentioned above that multiple calls to
4015``logging.getLogger('someLogger')`` return a reference to the same logger
4016object. This is true not only within the same module, but also across modules
4017as long as it is in the same Python interpreter process. It is true for
4018references to the same object; additionally, application code can define and
4019configure a parent logger in one module and create (but not configure) a child
4020logger in a separate module, and all logger calls to the child will pass up to
4021the parent. Here is a main module::
4022
4023 import logging
4024 import auxiliary_module
4025
4026 # create logger with "spam_application"
4027 logger = logging.getLogger("spam_application")
4028 logger.setLevel(logging.DEBUG)
4029 # create file handler which logs even debug messages
4030 fh = logging.FileHandler("spam.log")
4031 fh.setLevel(logging.DEBUG)
4032 # create console handler with a higher log level
4033 ch = logging.StreamHandler()
4034 ch.setLevel(logging.ERROR)
4035 # create formatter and add it to the handlers
4036 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4037 fh.setFormatter(formatter)
4038 ch.setFormatter(formatter)
4039 # add the handlers to the logger
4040 logger.addHandler(fh)
4041 logger.addHandler(ch)
4042
4043 logger.info("creating an instance of auxiliary_module.Auxiliary")
4044 a = auxiliary_module.Auxiliary()
4045 logger.info("created an instance of auxiliary_module.Auxiliary")
4046 logger.info("calling auxiliary_module.Auxiliary.do_something")
4047 a.do_something()
4048 logger.info("finished auxiliary_module.Auxiliary.do_something")
4049 logger.info("calling auxiliary_module.some_function()")
4050 auxiliary_module.some_function()
4051 logger.info("done with auxiliary_module.some_function()")
4052
4053Here is the auxiliary module::
4054
4055 import logging
4056
4057 # create logger
4058 module_logger = logging.getLogger("spam_application.auxiliary")
4059
4060 class Auxiliary:
4061 def __init__(self):
4062 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4063 self.logger.info("creating an instance of Auxiliary")
4064 def do_something(self):
4065 self.logger.info("doing something")
4066 a = 1 + 1
4067 self.logger.info("done doing something")
4068
4069 def some_function():
4070 module_logger.info("received a call to \"some_function\"")
4071
4072The output looks like this::
4073
Christian Heimes043d6f62008-01-07 17:19:16 +00004074 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004075 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004076 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004077 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004078 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004079 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004080 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004081 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004082 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004083 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004084 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004085 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004086 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004087 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004088 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004089 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004090 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004091 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004092 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004093 done with auxiliary_module.some_function()
4094