blob: 8cfb7d51c344eb9380b9514552ae1899167e5b8e [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
Vinay Sajipa18b9592010-12-12 13:20:55 +000017The key benefit of having the logging API provided by a standard library module
18is that all Python modules can participate in logging, so your application log
19can include your own messages integrated with messages from third-party
20modules.
21
22
23Logging tutorial
24----------------
25
26Logging is a means of tracking events that happen when some software runs. The
27software's developer adds logging calls to their code to indicate that certain
28events have occurred. An event is described by a descriptive message which can
29optionally contain variable data (i.e. data that is potentially different for
30each occurrence of the event). Events also have an importance which the
31developer ascribes to the event; the importance can also be called the *level*
32or *severity*.
33
34When to use logging
35^^^^^^^^^^^^^^^^^^^
36
37Logging provides a set of convenience functions for simple logging usage. These
38are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and
39:func:`critical`. To determine when to use logging, see the table below, which
40states, for each of a set of common tasks, the best tool to use for it.
41
42+-------------------------------------+--------------------------------------+
43| Task you want to perform | The best tool for the task |
44+=====================================+======================================+
45| Display console output for ordinary | print() |
46| usage of a command line script or | |
47| program | |
48+-------------------------------------+--------------------------------------+
49| Report events that occur during | logging.info() (or logging.debug() |
50| normal operation of a program (e.g. | for very detailed output for |
51| or status monitoring or fault | diagnostic purposes) |
52| investigation) | |
53+-------------------------------------+--------------------------------------+
54| Issue a warning regarding a | warnings.warn() in library code |
55| particular runtime event | if the issue is avoidable and the |
56| | client application should be |
57| | modified to eliminate the warning |
58| | |
59| | logging.warn() if there is nothing |
60| | the client application can do about |
61| | the situation, but the event should |
62| | still be noted |
63+-------------------------------------+--------------------------------------+
64| Report an error regarding a | Raise an exception |
65| particular runtime event | |
66+-------------------------------------+--------------------------------------+
67| Report suppression of an error | logging.error(), logging.exception(),|
68| without raising an exception (e.g. | or logging.critical() as appropriate |
69| error handler in a long-running | for the specific error and |
70| server process) | application domain |
71+-------------------------------------+--------------------------------------+
72
73The logging functions are named after the level or severity of the events
74they are used to track. The standard levels and their applicability are
75described below (in increasing order of severity):
76
77+--------------+---------------------------------------------+
78| Level | When it's used |
79+==============+=============================================+
80| ``DEBUG`` | Detailed information, typically of interest |
81| | only when diagnosing problems. |
82+--------------+---------------------------------------------+
83| ``INFO`` | Confirmation that things are working as |
84| | expected. |
85+--------------+---------------------------------------------+
86| ``WARNING`` | An indication that something unexpected |
87| | happened, or indicative of some problem in |
88| | the near future (e.g. "disk space low"). |
89| | The software is still working as expected. |
90+--------------+---------------------------------------------+
91| ``ERROR`` | Due to a more serious problem, the software |
92| | has not been able to perform some function. |
93+--------------+---------------------------------------------+
94| ``CRITICAL`` | A serious error, indicating that the program|
95| | itself may be unable to continue running. |
96+--------------+---------------------------------------------+
97
98The default level is ``WARNING``, which means that only events of this level
99and above will be tracked, unless the logging package is configured to do
100otherwise.
101
102Events that are tracked can be handled in different ways. The simplest way of
103handling tracked events is to print them to the console. Another common way
104is to write them to a disk file.
105
106
107.. _minimal-example:
108
109A simple example
110^^^^^^^^^^^^^^^^
111
112A very simple example is::
113
114 import logging
115 logging.warning('Watch out!') # will print a message to the console
116 logging.info('I told you so') # will not print anything
117
118If you type these lines into a script and run it, you'll see::
119
120 WARNING:root:Watch out!
121
122printed out on the console. The ``INFO`` message doesn't appear because the
123default level is ``WARNING``. The printed message includes the indication of
124the level and the description of the event provided in the logging call, i.e.
125'Watch out!'. Don't worry about the 'root' part for now: it will be explained
126later. The actual output can be formatted quite flexibly if you need that;
127formatting options will also be explained later.
128
129
130Logging to a file
131^^^^^^^^^^^^^^^^^
132
133A very common situation is that of recording logging events in a file, so let's
134look at that next::
135
136 import logging
137 logging.basicConfig(filename='example.log',level=logging.DEBUG)
138 logging.debug('This message should go to the log file')
139 logging.info('So should this')
140 logging.warning('And this, too')
141
142And now if we open the file and look at what we have, we should find the log
143messages::
144
145 DEBUG:root:This message should go to the log file
146 INFO:root:So should this
147 WARNING:root:And this, too
148
149This example also shows how you can set the logging level which acts as the
150threshold for tracking. In this case, because we set the threshold to
151``DEBUG``, all of the messages were printed.
152
153If you run the above script several times, the messages from successive runs
154are appended to the file *example.log*. If you want each run to start afresh,
155not remembering the messages from earlier runs, you can specify the *filemode*
156argument, by changing the call in the above example to::
157
158 logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
159
160The output will be the same as before, but the log file is no longer appended
161to, so the messages from earlier runs are lost.
162
163
164Logging from multiple modules
165^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
166
167If your program consists of multiple modules, here's an example of how you
168could organize logging in it::
169
170 # myapp.py
171 import logging
172 import mylib
173
174 def main():
175 logging.basicConfig(filename='myapp.log', level=logging.INFO)
176 logging.info('Started')
177 mylib.do_something()
178 logging.info('Finished')
179
180 if __name__ == '__main__':
181 main()
182
183::
184
185 # mylib.py
186 import logging
187
188 def do_something():
189 logging.info('Doing something')
190
191If you run myapp.py, you should see this in myapp.log::
192
193 INFO:root:Started
194 INFO:root:Doing something
195 INFO:root:Finished
196
197which is hopefully what you were expecting to see. You can generalize this to
198multiple modules, using the pattern in *mylib.py*. Note that for this simple
199usage pattern, you won't know, by looking in the log file, *where* in your
200application your messages came from, apart from looking at the event
201description. If you want to track the location of your messages, you'll need
202to refer to the documentation beyond the tutorial level - see
203:ref:`more-advanced-logging`.
204
205
206Logging variable data
207^^^^^^^^^^^^^^^^^^^^^
208
209To log variable data, use a format string for the event description message and
210append the variable data as arguments. For example::
211
212 import logging
213 logging.warning('%s before you %s', 'Look', 'leap!')
214
215will display::
216
217 WARNING:root:Look before you leap!
218
219As you can see, merging of variable data into the event description message
220uses the old, %-style of string formatting. This is for backwards
221compatibility: the logging package pre-dates newer formatting options such as
222:meth:`str.format` and :class:`string.Template`. These formatting options *are*
223supported, but exploring them is outside the scope of this tutorial.
224
225
226Changing the format of displayed messages
227^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
228
229To change the format which is used to display messages, you need to
230specify the format you want to use::
231
232 import logging
233 logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
234 logging.debug('This message should appear on the console')
235 logging.info('So should this')
236 logging.warning('And this, too')
237
238which would print::
239
240 DEBUG:This message should appear on the console
241 INFO:So should this
242 WARNING:And this, too
243
244Notice that the 'root' which appeared in earlier examples has disappeared. For
245a full set of things that can appear in format strings, you can refer to the
246documentation for :ref:`formatter-objects`, but for simple usage, you just need
247the *levelname* (severity), *message* (event description, including variable
248data) and perhaps to display when the event occurred. This is described in the
249next section.
250
251Displaying the date/time in messages
252^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
253
254To display the date and time of an event, you would place "%(asctime)s" in
255your format string::
256
257 import logging
258 logging.basicConfig(format='%(asctime)s %(message)s')
259 logging.warning('is when this event was logged.')
260
261which should print something like this::
262
263 2010-12-12 11:41:42,612 is when this event was logged.
264
265The default format for date/time display (shown above) is ISO8601. If you need
266more control over the formatting of the date/time, provide a *datefmt*
267argument to ``basicConfig``, as in this example::
268
269 import logging
270 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
271 logging.warning('is when this event was logged.')
272
273which would display something like this::
274
275 12/12/2010 11:46:36 AM is when this event was logged.
276
277The format of the *datefmt* argument is the same as supported by
278:func:`time.strftime`.
279
280
281Er...that's it for the tutorial
282^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
283
284That concludes the tutorial. It should be enough to get you up and running
285with logging. There's a lot more that the logging package offers, but to get
286the best out of it, you'll need to invest a little more of your time in
287reading the following sections. If you're ready for that, grab some of your
288favourite beverage and carry on.
289
290If your logging needs are simple, then use the above examples to incorporate
291logging into your own scripts, and if you run into problems or don't
292understand something, please post a question on the comp.lang.python Usenet
293group (available at http://groups.google.com/group/comp.lang.python) and you
294should receive help before too long.
295
296Still here? There's no need to read this long page in linear fashion, top to
297bottom. Take a look at the topics in the sidebar to see if there's something
298that interests you, and click on a topic to see more detail. Although some of
299the topics do follow on from each other, there are a few that can just stand
300alone.
301
302
303.. _more-advanced-logging:
304
305More advanced logging
306---------------------
307
308The logging library takes a modular approach and offers several categories
309of components: loggers, handlers, filters, and formatters. Loggers expose the
310interface that application code directly uses. Handlers send the log records
311(created by loggers) to the appropriate destination. Filters provide a finer
312grained facility for determining which log records to output. Formatters
313specify the layout of the resultant log record in the final output.
314
Georg Brandl116aa622007-08-15 14:28:22 +0000315Logging is performed by calling methods on instances of the :class:`Logger`
316class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +0000317conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +0000318separators. For example, a logger named "scan" is the parent of loggers
319"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
320and indicate the area of an application in which a logged message originates.
321
Vinay Sajip5286ccf2010-12-12 13:25:29 +0000322A good convention to use when naming loggers is to use a module-level logger,
323in each module which uses logging, named as follows::
324
325 logger = logging.getLogger(__name__)
326
327This means that logger names track the package/module hierarchy, and it's
328intuitively obvious where events are logged just from the logger name.
329
Vinay Sajipa18b9592010-12-12 13:20:55 +0000330The root of the hierarchy of loggers is called the root logger. That's the
331logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
332:func:`error` and :func:`critical`, which just call the same-named method of
333the root logger. The functions and the methods have the same signatures. The
334root logger's name is printed as 'root' in the logged output.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Vinay Sajipa18b9592010-12-12 13:20:55 +0000336It is, of course, possible to log messages to different destinations. Support
337for writing log messages to files, HTTP GET/POST locations, email via SMTP,
338generic sockets, or OS-specific logging mechanisms is included in the package.
339Destinations are served by :dfn:`handler` classes. You can create your own log
Vinay Sajipdfa0a2a2010-12-10 08:17:05 +0000340destination class if you have special requirements not met by any of the
Vinay Sajipa18b9592010-12-12 13:20:55 +0000341built-in handler classes.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000342
Vinay Sajipa18b9592010-12-12 13:20:55 +0000343By default, no destination is set for any logging messages. You can specify
344a destination (such as console or file) by using :func:`basicConfig` as in the
345tutorial examples. If you call the functions :func:`debug`, :func:`info`,
346:func:`warning`, :func:`error` and :func:`critical`, they will check to see
347if no destination is set; and if one is not set, they will set a destination
348of the console (``sys.stderr``) and a default format for the displayed
349message before delegating to the root logger to do the actual message output.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000350
Vinay Sajipa18b9592010-12-12 13:20:55 +0000351The default format set by :func:`basicConfig` for messages is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000352
Vinay Sajipa18b9592010-12-12 13:20:55 +0000353 severity:logger name:message
Christian Heimes8b0facf2007-12-04 19:30:01 +0000354
Vinay Sajipa18b9592010-12-12 13:20:55 +0000355You can change this by passing a format string to :func:`basicConfig` with the
356*format* keyword argument. For all options regarding how a format string is
357constructed, see :ref:`formatter-objects`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000358
Christian Heimes8b0facf2007-12-04 19:30:01 +0000359
360Loggers
361^^^^^^^
362
Christian Heimes8b0facf2007-12-04 19:30:01 +0000363:class:`Logger` objects have a threefold job. First, they expose several
364methods to application code so that applications can log messages at runtime.
365Second, logger objects determine which log messages to act upon based upon
366severity (the default filtering facility) or filter objects. Third, logger
367objects pass along relevant log messages to all interested log handlers.
368
369The most widely used methods on logger objects fall into two categories:
370configuration and message sending.
371
372* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
373 will handle, where debug is the lowest built-in severity level and critical is
374 the highest built-in severity. For example, if the severity level is info,
375 the logger will handle only info, warning, error, and critical messages and
376 will ignore debug messages.
377
378* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
379 objects from the logger object. This tutorial does not address filters.
380
381With the logger object configured, the following methods create log messages:
382
383* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
384 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
385 a message and a level that corresponds to their respective method names. The
386 message is actually a format string, which may contain the standard string
387 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
388 rest of their arguments is a list of objects that correspond with the
389 substitution fields in the message. With regard to :const:`**kwargs`, the
390 logging methods care only about a keyword of :const:`exc_info` and use it to
391 determine whether to log exception information.
392
393* :meth:`Logger.exception` creates a log message similar to
394 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
395 stack trace along with it. Call this method only from an exception handler.
396
397* :meth:`Logger.log` takes a log level as an explicit argument. This is a
398 little more verbose for logging messages than using the log level convenience
399 methods listed above, but this is how to log at custom log levels.
400
Christian Heimesdcca98d2008-02-25 13:19:43 +0000401:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000402name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000403hierarchical structures. Multiple calls to :func:`getLogger` with the same name
404will return a reference to the same logger object. Loggers that are further
405down in the hierarchical list are children of loggers higher up in the list.
406For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000407``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
408Child loggers propagate messages up to the handlers associated with their
409ancestor loggers. Because of this, it is unnecessary to define and configure
410handlers for all the loggers an application uses. It is sufficient to
411configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000412
413
414Handlers
415^^^^^^^^
416
417:class:`Handler` objects are responsible for dispatching the appropriate log
418messages (based on the log messages' severity) to the handler's specified
419destination. Logger objects can add zero or more handler objects to themselves
420with an :func:`addHandler` method. As an example scenario, an application may
421want to send all log messages to a log file, all log messages of error or higher
422to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000423requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000424messages of a specific severity to a specific location.
425
426The standard library includes quite a few handler types; this tutorial uses only
427:class:`StreamHandler` and :class:`FileHandler` in its examples.
428
429There are very few methods in a handler for application developers to concern
430themselves with. The only handler methods that seem relevant for application
431developers who are using the built-in handler objects (that is, not creating
432custom handlers) are the following configuration methods:
433
434* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
435 lowest severity that will be dispatched to the appropriate destination. Why
436 are there two :func:`setLevel` methods? The level set in the logger
437 determines which severity of messages it will pass to its handlers. The level
438 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000439
440* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000441
442* :func:`addFilter` and :func:`removeFilter` respectively configure and
443 deconfigure filter objects on handlers.
444
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000445Application code should not directly instantiate and use instances of
446:class:`Handler`. Instead, the :class:`Handler` class is a base class that
447defines the interface that all handlers should have and establishes some
448default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000449
450
451Formatters
452^^^^^^^^^^
453
454Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000455message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000456instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000457if your application needs special behavior. The constructor takes three
458optional arguments -- a message format string, a date format string and a style
459indicator.
460
461.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
462
463If there is no message format string, the default is to use the
464raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000465
466 %Y-%m-%d %H:%M:%S
467
Vinay Sajipa39c5712010-10-25 13:57:39 +0000468with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
469or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000470
Vinay Sajipa39c5712010-10-25 13:57:39 +0000471If the ``style`` is '%', the message format string uses
472``%(<dictionary key>)s`` styled string substitution; the possible keys are
473documented in :ref:`formatter-objects`. If the style is '{', the message format
474string is assumed to be compatible with :meth:`str.format` (using keyword
475arguments), while if the style is '$' then the message format string should
476conform to what is expected by :meth:`string.Template.substitute`.
477
478.. versionchanged:: 3.2
479 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000480
481The following message format string will log the time in a human-readable
482format, the severity of the message, and the contents of the message, in that
483order::
484
485 "%(asctime)s - %(levelname)s - %(message)s"
486
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000487Formatters use a user-configurable function to convert the creation time of a
488record to a tuple. By default, :func:`time.localtime` is used; to change this
489for a particular formatter instance, set the ``converter`` attribute of the
490instance to a function with the same signature as :func:`time.localtime` or
491:func:`time.gmtime`. To change it for all formatters, for example if you want
492all logging times to be shown in GMT, set the ``converter`` attribute in the
493Formatter class (to ``time.gmtime`` for GMT display).
494
Christian Heimes8b0facf2007-12-04 19:30:01 +0000495
496Configuring Logging
497^^^^^^^^^^^^^^^^^^^
498
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000499Programmers can configure logging in three ways:
500
5011. Creating loggers, handlers, and formatters explicitly using Python
502 code that calls the configuration methods listed above.
5032. Creating a logging config file and reading it using the :func:`fileConfig`
504 function.
5053. Creating a dictionary of configuration information and passing it
506 to the :func:`dictConfig` function.
507
508The following example configures a very simple logger, a console
509handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000510
511 import logging
512
513 # create logger
514 logger = logging.getLogger("simple_example")
515 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000516
Christian Heimes8b0facf2007-12-04 19:30:01 +0000517 # create console handler and set level to debug
518 ch = logging.StreamHandler()
519 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000520
Christian Heimes8b0facf2007-12-04 19:30:01 +0000521 # create formatter
522 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000523
Christian Heimes8b0facf2007-12-04 19:30:01 +0000524 # add formatter to ch
525 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000526
Christian Heimes8b0facf2007-12-04 19:30:01 +0000527 # add ch to logger
528 logger.addHandler(ch)
529
530 # "application" code
531 logger.debug("debug message")
532 logger.info("info message")
533 logger.warn("warn message")
534 logger.error("error message")
535 logger.critical("critical message")
536
537Running this module from the command line produces the following output::
538
539 $ python simple_logging_module.py
540 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
541 2005-03-19 15:10:26,620 - simple_example - INFO - info message
542 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
543 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
544 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
545
546The following Python module creates a logger, handler, and formatter nearly
547identical to those in the example listed above, with the only difference being
548the names of the objects::
549
550 import logging
551 import logging.config
552
553 logging.config.fileConfig("logging.conf")
554
555 # create logger
556 logger = logging.getLogger("simpleExample")
557
558 # "application" code
559 logger.debug("debug message")
560 logger.info("info message")
561 logger.warn("warn message")
562 logger.error("error message")
563 logger.critical("critical message")
564
565Here is the logging.conf file::
566
567 [loggers]
568 keys=root,simpleExample
569
570 [handlers]
571 keys=consoleHandler
572
573 [formatters]
574 keys=simpleFormatter
575
576 [logger_root]
577 level=DEBUG
578 handlers=consoleHandler
579
580 [logger_simpleExample]
581 level=DEBUG
582 handlers=consoleHandler
583 qualname=simpleExample
584 propagate=0
585
586 [handler_consoleHandler]
587 class=StreamHandler
588 level=DEBUG
589 formatter=simpleFormatter
590 args=(sys.stdout,)
591
592 [formatter_simpleFormatter]
593 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
594 datefmt=
595
596The output is nearly identical to that of the non-config-file-based example::
597
598 $ python simple_logging_config.py
599 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
600 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
601 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
602 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
603 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
604
605You can see that the config file approach has a few advantages over the Python
606code approach, mainly separation of configuration and code and the ability of
607noncoders to easily modify the logging properties.
608
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000609Note that the class names referenced in config files need to be either relative
610to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000611import mechanisms. Thus, you could use either
612:class:`handlers.WatchedFileHandler` (relative to the logging module) or
613``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
614and module ``mymodule``, where ``mypackage`` is available on the Python import
615path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000616
Benjamin Peterson56894b52010-06-28 00:16:12 +0000617In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000618dictionaries to hold configuration information. This provides a superset of the
619functionality of the config-file-based approach outlined above, and is the
620recommended configuration method for new applications and deployments. Because
621a Python dictionary is used to hold configuration information, and since you
622can populate that dictionary using different means, you have more options for
623configuration. For example, you can use a configuration file in JSON format,
624or, if you have access to YAML processing functionality, a file in YAML
625format, to populate the configuration dictionary. Or, of course, you can
626construct the dictionary in Python code, receive it in pickled form over a
627socket, or use whatever approach makes sense for your application.
628
629Here's an example of the same configuration as above, in YAML format for
630the new dictionary-based approach::
631
632 version: 1
633 formatters:
634 simple:
635 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
636 handlers:
637 console:
638 class: logging.StreamHandler
639 level: DEBUG
640 formatter: simple
641 stream: ext://sys.stdout
642 loggers:
643 simpleExample:
644 level: DEBUG
645 handlers: [console]
646 propagate: no
647 root:
648 level: DEBUG
649 handlers: [console]
650
651For more information about logging using a dictionary, see
652:ref:`logging-config-api`.
653
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000654.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000655
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000656Configuring Logging for a Library
657^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
658
659When developing a library which uses logging, some consideration needs to be
660given to its configuration. If the using application does not use logging, and
661library code makes logging calls, then a one-off message "No handlers could be
662found for logger X.Y.Z" is printed to the console. This message is intended
663to catch mistakes in logging configuration, but will confuse an application
664developer who is not aware of logging by the library.
665
666In addition to documenting how a library uses logging, a good way to configure
667library logging so that it does not cause a spurious message is to add a
668handler which does nothing. This avoids the message being printed, since a
669handler will be found: it just doesn't produce any output. If the library user
670configures logging for application use, presumably that configuration will add
671some handlers, and if levels are suitably configured then logging calls made
672in library code will send output to those handlers, as normal.
673
674A do-nothing handler can be simply defined as follows::
675
676 import logging
677
678 class NullHandler(logging.Handler):
679 def emit(self, record):
680 pass
681
682An instance of this handler should be added to the top-level logger of the
683logging namespace used by the library. If all logging by a library *foo* is
684done using loggers with names matching "foo.x.y", then the code::
685
686 import logging
687
688 h = NullHandler()
689 logging.getLogger("foo").addHandler(h)
690
691should have the desired effect. If an organisation produces a number of
692libraries, then the logger name specified can be "orgname.foo" rather than
693just "foo".
694
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000695**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
696than* :class:`NullHandler` *to your library's loggers*. This is because the
697configuration of handlers is the prerogative of the application developer who
698uses your library. The application developer knows their target audience and
699what handlers are most appropriate for their application: if you add handlers
700"under the hood", you might well interfere with their ability to carry out
701unit tests and deliver logs which suit their requirements.
702
Georg Brandlf9734072008-12-07 15:30:06 +0000703.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000704 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000705
Christian Heimes8b0facf2007-12-04 19:30:01 +0000706
707Logging Levels
708--------------
709
Georg Brandl116aa622007-08-15 14:28:22 +0000710The numeric values of logging levels are given in the following table. These are
711primarily of interest if you want to define your own levels, and need them to
712have specific values relative to the predefined levels. If you define a level
713with the same numeric value, it overwrites the predefined value; the predefined
714name is lost.
715
716+--------------+---------------+
717| Level | Numeric value |
718+==============+===============+
719| ``CRITICAL`` | 50 |
720+--------------+---------------+
721| ``ERROR`` | 40 |
722+--------------+---------------+
723| ``WARNING`` | 30 |
724+--------------+---------------+
725| ``INFO`` | 20 |
726+--------------+---------------+
727| ``DEBUG`` | 10 |
728+--------------+---------------+
729| ``NOTSET`` | 0 |
730+--------------+---------------+
731
732Levels can also be associated with loggers, being set either by the developer or
733through loading a saved logging configuration. When a logging method is called
734on a logger, the logger compares its own level with the level associated with
735the method call. If the logger's level is higher than the method call's, no
736logging message is actually generated. This is the basic mechanism controlling
737the verbosity of logging output.
738
739Logging messages are encoded as instances of the :class:`LogRecord` class. When
740a logger decides to actually log an event, a :class:`LogRecord` instance is
741created from the logging message.
742
743Logging messages are subjected to a dispatch mechanism through the use of
744:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
745class. Handlers are responsible for ensuring that a logged message (in the form
746of a :class:`LogRecord`) ends up in a particular location (or set of locations)
747which is useful for the target audience for that message (such as end users,
748support desk staff, system administrators, developers). Handlers are passed
749:class:`LogRecord` instances intended for particular destinations. Each logger
750can have zero, one or more handlers associated with it (via the
751:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
752directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000753of the logger* are called to dispatch the message (unless the *propagate* flag
754for a logger is set to a false value, at which point the passing to ancestor
755handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000756
757Just as for loggers, handlers can have levels associated with them. A handler's
758level acts as a filter in the same way as a logger's level does. If a handler
759decides to actually dispatch an event, the :meth:`emit` method is used to send
760the message to its destination. Most user-defined subclasses of :class:`Handler`
761will need to override this :meth:`emit`.
762
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000763.. _custom-levels:
764
765Custom Levels
766^^^^^^^^^^^^^
767
768Defining your own levels is possible, but should not be necessary, as the
769existing levels have been chosen on the basis of practical experience.
770However, if you are convinced that you need custom levels, great care should
771be exercised when doing this, and it is possibly *a very bad idea to define
772custom levels if you are developing a library*. That's because if multiple
773library authors all define their own custom levels, there is a chance that
774the logging output from such multiple libraries used together will be
775difficult for the using developer to control and/or interpret, because a
776given numeric value might mean different things for different libraries.
777
778
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000779Useful Handlers
780---------------
781
Georg Brandl116aa622007-08-15 14:28:22 +0000782In addition to the base :class:`Handler` class, many useful subclasses are
783provided:
784
Vinay Sajip121a1c42010-09-08 10:46:15 +0000785#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000786 objects).
787
Vinay Sajip121a1c42010-09-08 10:46:15 +0000788#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000789
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000790.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000791
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000792#. :class:`BaseRotatingHandler` is the base class for handlers that
793 rotate log files at a certain point. It is not meant to be instantiated
794 directly. Instead, use :class:`RotatingFileHandler` or
795 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000796
Vinay Sajip121a1c42010-09-08 10:46:15 +0000797#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000798 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000799
Vinay Sajip121a1c42010-09-08 10:46:15 +0000800#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000801 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000802
Vinay Sajip121a1c42010-09-08 10:46:15 +0000803#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000804 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000805
Vinay Sajip121a1c42010-09-08 10:46:15 +0000806#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000807 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000808
Vinay Sajip121a1c42010-09-08 10:46:15 +0000809#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000810 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Vinay Sajip121a1c42010-09-08 10:46:15 +0000812#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000813 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000814
Vinay Sajip121a1c42010-09-08 10:46:15 +0000815#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000816 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Vinay Sajip121a1c42010-09-08 10:46:15 +0000818#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000819 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Vinay Sajip121a1c42010-09-08 10:46:15 +0000821#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000822 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000824#. :class:`WatchedFileHandler` instances watch the file they are
825 logging to. If the file changes, it is closed and reopened using the file
826 name. This handler is only useful on Unix-like systems; Windows does not
827 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000828
Vinay Sajip121a1c42010-09-08 10:46:15 +0000829#. :class:`QueueHandler` instances send messages to a queue, such as
830 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
831
Vinay Sajip30bf1222009-01-10 19:23:34 +0000832.. currentmodule:: logging
833
Georg Brandlf9734072008-12-07 15:30:06 +0000834#. :class:`NullHandler` instances do nothing with error messages. They are used
835 by library developers who want to use logging, but want to avoid the "No
836 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000837 the library user has not configured logging. See :ref:`library-config` for
838 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000839
840.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000841 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000842
Vinay Sajip121a1c42010-09-08 10:46:15 +0000843.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000844 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000845
Vinay Sajipa17775f2008-12-30 07:32:59 +0000846The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
847classes are defined in the core logging package. The other handlers are
848defined in a sub- module, :mod:`logging.handlers`. (There is also another
849sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851Logged messages are formatted for presentation through instances of the
852:class:`Formatter` class. They are initialized with a format string suitable for
853use with the % operator and a dictionary.
854
855For formatting multiple messages in a batch, instances of
856:class:`BufferingFormatter` can be used. In addition to the format string (which
857is applied to each message in the batch), there is provision for header and
858trailer format strings.
859
860When filtering based on logger level and/or handler level is not enough,
861instances of :class:`Filter` can be added to both :class:`Logger` and
862:class:`Handler` instances (through their :meth:`addFilter` method). Before
863deciding to process a message further, both loggers and handlers consult all
864their filters for permission. If any filter returns a false value, the message
865is not processed further.
866
867The basic :class:`Filter` functionality allows filtering by specific logger
868name. If this feature is used, messages sent to the named logger and its
869children are allowed through the filter, and all others dropped.
870
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000871Module-Level Functions
872----------------------
873
Georg Brandl116aa622007-08-15 14:28:22 +0000874In addition to the classes described above, there are a number of module- level
875functions.
876
877
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000878.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000879
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000880 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000881 logger which is the root logger of the hierarchy. If specified, the name is
882 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
883 Choice of these names is entirely up to the developer who is using logging.
884
885 All calls to this function with a given name return the same logger instance.
886 This means that logger instances never need to be passed between different parts
887 of an application.
888
889
890.. function:: getLoggerClass()
891
892 Return either the standard :class:`Logger` class, or the last class passed to
893 :func:`setLoggerClass`. This function may be called from within a new class
894 definition, to ensure that installing a customised :class:`Logger` class will
895 not undo customisations already applied by other code. For example::
896
897 class MyLogger(logging.getLoggerClass()):
898 # ... override behaviour here
899
900
Vinay Sajip61561522010-12-03 11:50:38 +0000901.. function:: getLogRecordFactory()
902
903 Return a callable which is used to create a :class:`LogRecord`.
904
905 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000906 This function has been provided, along with :func:`setLogRecordFactory`,
907 to allow developers more control over how the :class:`LogRecord`
908 representing a logging event is constructed.
909
910 See :func:`setLogRecordFactory` for more information about the how the
911 factory is called.
912
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000913.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
916 message format string, and the *args* are the arguments which are merged into
917 *msg* using the string formatting operator. (Note that this means that you can
918 use keywords in the format string, together with a single dictionary argument.)
919
Vinay Sajip8593ae62010-11-14 21:33:04 +0000920 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +0000921 which, if it does not evaluate as false, causes exception information to be
922 added to the logging message. If an exception tuple (in the format returned by
923 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
924 is called to get the exception information.
925
Vinay Sajip8593ae62010-11-14 21:33:04 +0000926 The second optional keyword argument is *stack_info*, which defaults to
927 False. If specified as True, stack information is added to the logging
928 message, including the actual logging call. Note that this is not the same
929 stack information as that displayed through specifying *exc_info*: The
930 former is stack frames from the bottom of the stack up to the logging call
931 in the current thread, whereas the latter is information about stack frames
932 which have been unwound, following an exception, while searching for
933 exception handlers.
934
935 You can specify *stack_info* independently of *exc_info*, e.g. to just show
936 how you got to a certain point in your code, even when no exceptions were
937 raised. The stack frames are printed following a header line which says::
938
939 Stack (most recent call last):
940
941 This mimics the `Traceback (most recent call last):` which is used when
942 displaying exception frames.
943
944 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +0000945 dictionary which is used to populate the __dict__ of the LogRecord created for
946 the logging event with user-defined attributes. These custom attributes can then
947 be used as you like. For example, they could be incorporated into logged
948 messages. For example::
949
950 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
951 logging.basicConfig(format=FORMAT)
952 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
953 logging.warning("Protocol problem: %s", "connection reset", extra=d)
954
Vinay Sajip4039aff2010-09-11 10:25:28 +0000955 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
958
959 The keys in the dictionary passed in *extra* should not clash with the keys used
960 by the logging system. (See the :class:`Formatter` documentation for more
961 information on which keys are used by the logging system.)
962
963 If you choose to use these attributes in logged messages, you need to exercise
964 some care. In the above example, for instance, the :class:`Formatter` has been
965 set up with a format string which expects 'clientip' and 'user' in the attribute
966 dictionary of the LogRecord. If these are missing, the message will not be
967 logged because a string formatting exception will occur. So in this case, you
968 always need to pass the *extra* dictionary with these keys.
969
970 While this might be annoying, this feature is intended for use in specialized
971 circumstances, such as multi-threaded servers where the same code executes in
972 many contexts, and interesting conditions which arise are dependent on this
973 context (such as remote client IP address and authenticated user name, in the
974 above example). In such circumstances, it is likely that specialized
975 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
976
Vinay Sajip8593ae62010-11-14 21:33:04 +0000977 .. versionadded:: 3.2
978 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000980.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000981
982 Logs a message with level :const:`INFO` on the root logger. The arguments are
983 interpreted as for :func:`debug`.
984
985
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000986.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988 Logs a message with level :const:`WARNING` on the root logger. The arguments are
989 interpreted as for :func:`debug`.
990
991
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000992.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000993
994 Logs a message with level :const:`ERROR` on the root logger. The arguments are
995 interpreted as for :func:`debug`.
996
997
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000998.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000999
1000 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1001 are interpreted as for :func:`debug`.
1002
1003
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001004.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001005
1006 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1007 interpreted as for :func:`debug`. Exception info is added to the logging
1008 message. This function should only be called from an exception handler.
1009
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001010.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001011
1012 Logs a message with level *level* on the root logger. The other arguments are
1013 interpreted as for :func:`debug`.
1014
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001015 PLEASE NOTE: The above module-level functions which delegate to the root
1016 logger should *not* be used in threads, in versions of Python earlier than
1017 2.7.1 and 3.2, unless at least one handler has been added to the root
1018 logger *before* the threads are started. These convenience functions call
1019 :func:`basicConfig` to ensure that at least one handler is available; in
1020 earlier versions of Python, this can (under rare circumstances) lead to
1021 handlers being added multiple times to the root logger, which can in turn
1022 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001023
1024.. function:: disable(lvl)
1025
1026 Provides an overriding level *lvl* for all loggers which takes precedence over
1027 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001028 output down across the whole application, this function can be useful. Its
1029 effect is to disable all logging calls of severity *lvl* and below, so that
1030 if you call it with a value of INFO, then all INFO and DEBUG events would be
1031 discarded, whereas those of severity WARNING and above would be processed
1032 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034
1035.. function:: addLevelName(lvl, levelName)
1036
1037 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1038 used to map numeric levels to a textual representation, for example when a
1039 :class:`Formatter` formats a message. This function can also be used to define
1040 your own levels. The only constraints are that all levels used must be
1041 registered using this function, levels should be positive integers and they
1042 should increase in increasing order of severity.
1043
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001044 NOTE: If you are thinking of defining your own levels, please see the section
1045 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047.. function:: getLevelName(lvl)
1048
1049 Returns the textual representation of logging level *lvl*. If the level is one
1050 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1051 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1052 have associated levels with names using :func:`addLevelName` then the name you
1053 have associated with *lvl* is returned. If a numeric value corresponding to one
1054 of the defined levels is passed in, the corresponding string representation is
1055 returned. Otherwise, the string "Level %s" % lvl is returned.
1056
1057
1058.. function:: makeLogRecord(attrdict)
1059
1060 Creates and returns a new :class:`LogRecord` instance whose attributes are
1061 defined by *attrdict*. This function is useful for taking a pickled
1062 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1063 it as a :class:`LogRecord` instance at the receiving end.
1064
1065
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001066.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068 Does basic configuration for the logging system by creating a
1069 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001070 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001071 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1072 if no handlers are defined for the root logger.
1073
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001074 This function does nothing if the root logger already has handlers
1075 configured for it.
1076
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001077 PLEASE NOTE: This function should be called from the main thread
1078 before other threads are started. In versions of Python prior to
1079 2.7.1 and 3.2, if this function is called from multiple threads,
1080 it is possible (in rare circumstances) that a handler will be added
1081 to the root logger more than once, leading to unexpected results
1082 such as messages being duplicated in the log.
1083
Georg Brandl116aa622007-08-15 14:28:22 +00001084 The following keyword arguments are supported.
1085
1086 +--------------+---------------------------------------------+
1087 | Format | Description |
1088 +==============+=============================================+
1089 | ``filename`` | Specifies that a FileHandler be created, |
1090 | | using the specified filename, rather than a |
1091 | | StreamHandler. |
1092 +--------------+---------------------------------------------+
1093 | ``filemode`` | Specifies the mode to open the file, if |
1094 | | filename is specified (if filemode is |
1095 | | unspecified, it defaults to 'a'). |
1096 +--------------+---------------------------------------------+
1097 | ``format`` | Use the specified format string for the |
1098 | | handler. |
1099 +--------------+---------------------------------------------+
1100 | ``datefmt`` | Use the specified date/time format. |
1101 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001102 | ``style`` | If ``format`` is specified, use this style |
1103 | | for the format string. One of '%', '{' or |
1104 | | '$' for %-formatting, :meth:`str.format` or |
1105 | | :class:`string.Template` respectively, and |
1106 | | defaulting to '%' if not specified. |
1107 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001108 | ``level`` | Set the root logger level to the specified |
1109 | | level. |
1110 +--------------+---------------------------------------------+
1111 | ``stream`` | Use the specified stream to initialize the |
1112 | | StreamHandler. Note that this argument is |
1113 | | incompatible with 'filename' - if both are |
1114 | | present, 'stream' is ignored. |
1115 +--------------+---------------------------------------------+
1116
Vinay Sajipc5b27302010-10-31 14:59:16 +00001117 .. versionchanged:: 3.2
1118 The ``style`` argument was added.
1119
1120
Georg Brandl116aa622007-08-15 14:28:22 +00001121.. function:: shutdown()
1122
1123 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001124 closing all handlers. This should be called at application exit and no
1125 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127
1128.. function:: setLoggerClass(klass)
1129
1130 Tells the logging system to use the class *klass* when instantiating a logger.
1131 The class should define :meth:`__init__` such that only a name argument is
1132 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1133 function is typically called before any loggers are instantiated by applications
1134 which need to use custom logger behavior.
1135
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001136
Vinay Sajip61561522010-12-03 11:50:38 +00001137.. function:: setLogRecordFactory(factory)
1138
1139 Set a callable which is used to create a :class:`LogRecord`.
1140
1141 :param factory: The factory callable to be used to instantiate a log record.
1142
1143 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001144 This function has been provided, along with :func:`getLogRecordFactory`, to
1145 allow developers more control over how the :class:`LogRecord` representing
1146 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001147
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001148 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001149
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001150 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, \*\*kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001151
1152 :name: The logger name.
1153 :level: The logging level (numeric).
1154 :fn: The full pathname of the file where the logging call was made.
1155 :lno: The line number in the file where the logging call was made.
1156 :msg: The logging message.
1157 :args: The arguments for the logging message.
1158 :exc_info: An exception tuple, or None.
1159 :func: The name of the function or method which invoked the logging
1160 call.
1161 :sinfo: A stack traceback such as is provided by
1162 :func:`traceback.print_stack`, showing the call hierarchy.
1163 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001164
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001165
Georg Brandl116aa622007-08-15 14:28:22 +00001166.. seealso::
1167
1168 :pep:`282` - A Logging System
1169 The proposal which described this feature for inclusion in the Python standard
1170 library.
1171
Christian Heimes255f53b2007-12-08 15:33:56 +00001172 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001173 This is the original source for the :mod:`logging` package. The version of the
1174 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1175 and 2.2.x, which do not include the :mod:`logging` package in the standard
1176 library.
1177
Vinay Sajip4039aff2010-09-11 10:25:28 +00001178.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001179
1180Logger Objects
1181--------------
1182
1183Loggers have the following attributes and methods. Note that Loggers are never
1184instantiated directly, but always through the module-level function
1185``logging.getLogger(name)``.
1186
Vinay Sajip0258ce82010-09-22 20:34:53 +00001187.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001188
1189.. attribute:: Logger.propagate
1190
1191 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001192 its child loggers to the handlers of higher level (ancestor) loggers. The
1193 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001194
1195
1196.. method:: Logger.setLevel(lvl)
1197
1198 Sets the threshold for this logger to *lvl*. Logging messages which are less
1199 severe than *lvl* will be ignored. When a logger is created, the level is set to
1200 :const:`NOTSET` (which causes all messages to be processed when the logger is
1201 the root logger, or delegation to the parent when the logger is a non-root
1202 logger). Note that the root logger is created with level :const:`WARNING`.
1203
1204 The term "delegation to the parent" means that if a logger has a level of
1205 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1206 a level other than NOTSET is found, or the root is reached.
1207
1208 If an ancestor is found with a level other than NOTSET, then that ancestor's
1209 level is treated as the effective level of the logger where the ancestor search
1210 began, and is used to determine how a logging event is handled.
1211
1212 If the root is reached, and it has a level of NOTSET, then all messages will be
1213 processed. Otherwise, the root's level will be used as the effective level.
1214
1215
1216.. method:: Logger.isEnabledFor(lvl)
1217
1218 Indicates if a message of severity *lvl* would be processed by this logger.
1219 This method checks first the module-level level set by
1220 ``logging.disable(lvl)`` and then the logger's effective level as determined
1221 by :meth:`getEffectiveLevel`.
1222
1223
1224.. method:: Logger.getEffectiveLevel()
1225
1226 Indicates the effective level for this logger. If a value other than
1227 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1228 the hierarchy is traversed towards the root until a value other than
1229 :const:`NOTSET` is found, and that value is returned.
1230
1231
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001232.. method:: Logger.getChild(suffix)
1233
1234 Returns a logger which is a descendant to this logger, as determined by the suffix.
1235 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1236 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1237 convenience method, useful when the parent logger is named using e.g. ``__name__``
1238 rather than a literal string.
1239
1240 .. versionadded:: 3.2
1241
Georg Brandl67b21b72010-08-17 15:07:14 +00001242
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001243.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001244
1245 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1246 message format string, and the *args* are the arguments which are merged into
1247 *msg* using the string formatting operator. (Note that this means that you can
1248 use keywords in the format string, together with a single dictionary argument.)
1249
Vinay Sajip8593ae62010-11-14 21:33:04 +00001250 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001251 which, if it does not evaluate as false, causes exception information to be
1252 added to the logging message. If an exception tuple (in the format returned by
1253 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1254 is called to get the exception information.
1255
Vinay Sajip8593ae62010-11-14 21:33:04 +00001256 The second optional keyword argument is *stack_info*, which defaults to
1257 False. If specified as True, stack information is added to the logging
1258 message, including the actual logging call. Note that this is not the same
1259 stack information as that displayed through specifying *exc_info*: The
1260 former is stack frames from the bottom of the stack up to the logging call
1261 in the current thread, whereas the latter is information about stack frames
1262 which have been unwound, following an exception, while searching for
1263 exception handlers.
1264
1265 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1266 how you got to a certain point in your code, even when no exceptions were
1267 raised. The stack frames are printed following a header line which says::
1268
1269 Stack (most recent call last):
1270
1271 This mimics the `Traceback (most recent call last):` which is used when
1272 displaying exception frames.
1273
1274 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001275 dictionary which is used to populate the __dict__ of the LogRecord created for
1276 the logging event with user-defined attributes. These custom attributes can then
1277 be used as you like. For example, they could be incorporated into logged
1278 messages. For example::
1279
1280 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1281 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001282 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001283 logger = logging.getLogger("tcpserver")
1284 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1285
1286 would print something like ::
1287
1288 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1289
1290 The keys in the dictionary passed in *extra* should not clash with the keys used
1291 by the logging system. (See the :class:`Formatter` documentation for more
1292 information on which keys are used by the logging system.)
1293
1294 If you choose to use these attributes in logged messages, you need to exercise
1295 some care. In the above example, for instance, the :class:`Formatter` has been
1296 set up with a format string which expects 'clientip' and 'user' in the attribute
1297 dictionary of the LogRecord. If these are missing, the message will not be
1298 logged because a string formatting exception will occur. So in this case, you
1299 always need to pass the *extra* dictionary with these keys.
1300
1301 While this might be annoying, this feature is intended for use in specialized
1302 circumstances, such as multi-threaded servers where the same code executes in
1303 many contexts, and interesting conditions which arise are dependent on this
1304 context (such as remote client IP address and authenticated user name, in the
1305 above example). In such circumstances, it is likely that specialized
1306 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1307
Vinay Sajip8593ae62010-11-14 21:33:04 +00001308 .. versionadded:: 3.2
1309 The *stack_info* parameter was added.
1310
Georg Brandl116aa622007-08-15 14:28:22 +00001311
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001312.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001313
1314 Logs a message with level :const:`INFO` on this logger. The arguments are
1315 interpreted as for :meth:`debug`.
1316
1317
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001318.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320 Logs a message with level :const:`WARNING` on this logger. The arguments are
1321 interpreted as for :meth:`debug`.
1322
1323
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001324.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326 Logs a message with level :const:`ERROR` on this logger. The arguments are
1327 interpreted as for :meth:`debug`.
1328
1329
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001330.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001331
1332 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1333 interpreted as for :meth:`debug`.
1334
1335
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001336.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338 Logs a message with integer level *lvl* on this logger. The other arguments are
1339 interpreted as for :meth:`debug`.
1340
1341
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001342.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344 Logs a message with level :const:`ERROR` on this logger. The arguments are
1345 interpreted as for :meth:`debug`. Exception info is added to the logging
1346 message. This method should only be called from an exception handler.
1347
1348
1349.. method:: Logger.addFilter(filt)
1350
1351 Adds the specified filter *filt* to this logger.
1352
1353
1354.. method:: Logger.removeFilter(filt)
1355
1356 Removes the specified filter *filt* from this logger.
1357
1358
1359.. method:: Logger.filter(record)
1360
1361 Applies this logger's filters to the record and returns a true value if the
1362 record is to be processed.
1363
1364
1365.. method:: Logger.addHandler(hdlr)
1366
1367 Adds the specified handler *hdlr* to this logger.
1368
1369
1370.. method:: Logger.removeHandler(hdlr)
1371
1372 Removes the specified handler *hdlr* from this logger.
1373
1374
Vinay Sajip8593ae62010-11-14 21:33:04 +00001375.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001378 number, function name and stack information as a 4-element tuple. The stack
1379 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001380
Georg Brandl116aa622007-08-15 14:28:22 +00001381
1382.. method:: Logger.handle(record)
1383
1384 Handles a record by passing it to all handlers associated with this logger and
1385 its ancestors (until a false value of *propagate* is found). This method is used
1386 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001387 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001388
1389
Vinay Sajip8593ae62010-11-14 21:33:04 +00001390.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001391
1392 This is a factory method which can be overridden in subclasses to create
1393 specialized :class:`LogRecord` instances.
1394
Vinay Sajip83eadd12010-09-20 10:31:18 +00001395.. method:: Logger.hasHandlers()
1396
1397 Checks to see if this logger has any handlers configured. This is done by
1398 looking for handlers in this logger and its parents in the logger hierarchy.
1399 Returns True if a handler was found, else False. The method stops searching
1400 up the hierarchy whenever a logger with the "propagate" attribute set to
1401 False is found - that will be the last logger which is checked for the
1402 existence of handlers.
1403
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001404 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001405
Vinay Sajipa18b9592010-12-12 13:20:55 +00001406.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408Basic example
1409-------------
1410
Georg Brandl116aa622007-08-15 14:28:22 +00001411The :mod:`logging` package provides a lot of flexibility, and its configuration
1412can appear daunting. This section demonstrates that simple use of the logging
1413package is possible.
1414
1415The simplest example shows logging to the console::
1416
1417 import logging
1418
1419 logging.debug('A debug message')
1420 logging.info('Some information')
1421 logging.warning('A shot across the bows')
1422
1423If you run the above script, you'll see this::
1424
1425 WARNING:root:A shot across the bows
1426
1427Because no particular logger was specified, the system used the root logger. The
1428debug and info messages didn't appear because by default, the root logger is
1429configured to only handle messages with a severity of WARNING or above. The
1430message format is also a configuration default, as is the output destination of
1431the messages - ``sys.stderr``. The severity level, the message format and
1432destination can be easily changed, as shown in the example below::
1433
1434 import logging
1435
1436 logging.basicConfig(level=logging.DEBUG,
1437 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001438 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001439 filemode='w')
1440 logging.debug('A debug message')
1441 logging.info('Some information')
1442 logging.warning('A shot across the bows')
1443
1444The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001445which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001446something like the following::
1447
1448 2004-07-02 13:00:08,743 DEBUG A debug message
1449 2004-07-02 13:00:08,743 INFO Some information
1450 2004-07-02 13:00:08,743 WARNING A shot across the bows
1451
1452This time, all messages with a severity of DEBUG or above were handled, and the
1453format of the messages was also changed, and output went to the specified file
1454rather than the console.
1455
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001456.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001457
1458Formatting uses the old Python string formatting - see section
1459:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001460specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1461documentation.
1462
1463+-------------------+-----------------------------------------------+
1464| Format | Description |
1465+===================+===============================================+
1466| ``%(name)s`` | Name of the logger (logging channel). |
1467+-------------------+-----------------------------------------------+
1468| ``%(levelname)s`` | Text logging level for the message |
1469| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1470| | ``'ERROR'``, ``'CRITICAL'``). |
1471+-------------------+-----------------------------------------------+
1472| ``%(asctime)s`` | Human-readable time when the |
1473| | :class:`LogRecord` was created. By default |
1474| | this is of the form "2003-07-08 16:49:45,896" |
1475| | (the numbers after the comma are millisecond |
1476| | portion of the time). |
1477+-------------------+-----------------------------------------------+
1478| ``%(message)s`` | The logged message. |
1479+-------------------+-----------------------------------------------+
1480
1481To change the date/time format, you can pass an additional keyword parameter,
1482*datefmt*, as in the following::
1483
1484 import logging
1485
1486 logging.basicConfig(level=logging.DEBUG,
1487 format='%(asctime)s %(levelname)-8s %(message)s',
1488 datefmt='%a, %d %b %Y %H:%M:%S',
1489 filename='/temp/myapp.log',
1490 filemode='w')
1491 logging.debug('A debug message')
1492 logging.info('Some information')
1493 logging.warning('A shot across the bows')
1494
1495which would result in output like ::
1496
1497 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1498 Fri, 02 Jul 2004 13:06:18 INFO Some information
1499 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1500
1501The date format string follows the requirements of :func:`strftime` - see the
1502documentation for the :mod:`time` module.
1503
1504If, instead of sending logging output to the console or a file, you'd rather use
1505a file-like object which you have created separately, you can pass it to
1506:func:`basicConfig` using the *stream* keyword argument. Note that if both
1507*stream* and *filename* keyword arguments are passed, the *stream* argument is
1508ignored.
1509
1510Of course, you can put variable information in your output. To do this, simply
1511have the message be a format string and pass in additional arguments containing
1512the variable information, as in the following example::
1513
1514 import logging
1515
1516 logging.basicConfig(level=logging.DEBUG,
1517 format='%(asctime)s %(levelname)-8s %(message)s',
1518 datefmt='%a, %d %b %Y %H:%M:%S',
1519 filename='/temp/myapp.log',
1520 filemode='w')
1521 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1522
1523which would result in ::
1524
1525 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1526
1527
Vinay Sajipa18b9592010-12-12 13:20:55 +00001528Using file rotation
1529^^^^^^^^^^^^^^^^^^^
1530
1531.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1532.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1533
1534Sometimes you want to let a log file grow to a certain size, then open a new
1535file and log to that. You may want to keep a certain number of these files, and
1536when that many files have been created, rotate the files so that the number of
1537files and the size of the files both remin bounded. For this usage pattern, the
1538logging package provides a :class:`RotatingFileHandler`::
1539
1540 import glob
1541 import logging
1542 import logging.handlers
1543
1544 LOG_FILENAME = 'logging_rotatingfile_example.out'
1545
1546 # Set up a specific logger with our desired output level
1547 my_logger = logging.getLogger('MyLogger')
1548 my_logger.setLevel(logging.DEBUG)
1549
1550 # Add the log message handler to the logger
1551 handler = logging.handlers.RotatingFileHandler(
1552 LOG_FILENAME, maxBytes=20, backupCount=5)
1553
1554 my_logger.addHandler(handler)
1555
1556 # Log some messages
1557 for i in range(20):
1558 my_logger.debug('i = %d' % i)
1559
1560 # See what files are created
1561 logfiles = glob.glob('%s*' % LOG_FILENAME)
1562
1563 for filename in logfiles:
1564 print(filename)
1565
1566The result should be 6 separate files, each with part of the log history for the
1567application::
1568
1569 logging_rotatingfile_example.out
1570 logging_rotatingfile_example.out.1
1571 logging_rotatingfile_example.out.2
1572 logging_rotatingfile_example.out.3
1573 logging_rotatingfile_example.out.4
1574 logging_rotatingfile_example.out.5
1575
1576The most current file is always :file:`logging_rotatingfile_example.out`,
1577and each time it reaches the size limit it is renamed with the suffix
1578``.1``. Each of the existing backup files is renamed to increment the suffix
1579(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1580
1581Obviously this example sets the log length much much too small as an extreme
1582example. You would want to set *maxBytes* to an appropriate value.
1583
1584
1585The logger, handler, and log message call each specify a level. The log message
1586is only emitted if the handler and logger are configured to emit messages of
1587that level or lower. For example, if a message is ``CRITICAL``, and the logger
1588is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1589the logger is set to produce only ``ERROR``\s, the message is not emitted::
1590
1591 import logging
1592 import sys
1593
1594 LEVELS = {'debug': logging.DEBUG,
1595 'info': logging.INFO,
1596 'warning': logging.WARNING,
1597 'error': logging.ERROR,
1598 'critical': logging.CRITICAL}
1599
1600 if len(sys.argv) > 1:
1601 level_name = sys.argv[1]
1602 level = LEVELS.get(level_name, logging.NOTSET)
1603 logging.basicConfig(level=level)
1604
1605 logging.debug('This is a debug message')
1606 logging.info('This is an info message')
1607 logging.warning('This is a warning message')
1608 logging.error('This is an error message')
1609 logging.critical('This is a critical error message')
1610
1611Run the script with an argument like 'debug' or 'warning' to see which messages
1612show up at different levels::
1613
1614 $ python logging_level_example.py debug
1615 DEBUG:root:This is a debug message
1616 INFO:root:This is an info message
1617 WARNING:root:This is a warning message
1618 ERROR:root:This is an error message
1619 CRITICAL:root:This is a critical error message
1620
1621 $ python logging_level_example.py info
1622 INFO:root:This is an info message
1623 WARNING:root:This is a warning message
1624 ERROR:root:This is an error message
1625 CRITICAL:root:This is a critical error message
1626
1627You will notice that these log messages all have ``root`` embedded in them. The
1628logging module supports a hierarchy of loggers with different names. An easy
1629way to tell where a specific log message comes from is to use a separate logger
1630object for each of your modules. Each new logger "inherits" the configuration
1631of its parent, and log messages sent to a logger include the name of that
1632logger. Optionally, each logger can be configured differently, so that messages
1633from different modules are handled in different ways. Let's look at a simple
1634example of how to log from different modules so it is easy to trace the source
1635of the message::
1636
1637 import logging
1638
1639 logging.basicConfig(level=logging.WARNING)
1640
1641 logger1 = logging.getLogger('package1.module1')
1642 logger2 = logging.getLogger('package2.module2')
1643
1644 logger1.warning('This message comes from one module')
1645 logger2.warning('And this message comes from another module')
1646
1647And the output::
1648
1649 $ python logging_modules_example.py
1650 WARNING:package1.module1:This message comes from one module
1651 WARNING:package2.module2:And this message comes from another module
1652
1653There are many more options for configuring logging, including different log
1654message formatting options, having messages delivered to multiple destinations,
1655and changing the configuration of a long-running application on the fly using a
1656socket interface. All of these options are covered in depth in the library
1657module documentation.
1658
1659
Georg Brandl116aa622007-08-15 14:28:22 +00001660.. _multiple-destinations:
1661
1662Logging to multiple destinations
1663--------------------------------
1664
1665Let's say you want to log to console and file with different message formats and
1666in differing circumstances. Say you want to log messages with levels of DEBUG
1667and higher to file, and those messages at level INFO and higher to the console.
1668Let's also assume that the file should contain timestamps, but the console
1669messages should not. Here's how you can achieve this::
1670
1671 import logging
1672
1673 # set up logging to file - see previous section for more details
1674 logging.basicConfig(level=logging.DEBUG,
1675 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1676 datefmt='%m-%d %H:%M',
1677 filename='/temp/myapp.log',
1678 filemode='w')
1679 # define a Handler which writes INFO messages or higher to the sys.stderr
1680 console = logging.StreamHandler()
1681 console.setLevel(logging.INFO)
1682 # set a format which is simpler for console use
1683 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1684 # tell the handler to use this format
1685 console.setFormatter(formatter)
1686 # add the handler to the root logger
1687 logging.getLogger('').addHandler(console)
1688
1689 # Now, we can log to the root logger, or any other logger. First the root...
1690 logging.info('Jackdaws love my big sphinx of quartz.')
1691
1692 # Now, define a couple of other loggers which might represent areas in your
1693 # application:
1694
1695 logger1 = logging.getLogger('myapp.area1')
1696 logger2 = logging.getLogger('myapp.area2')
1697
1698 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1699 logger1.info('How quickly daft jumping zebras vex.')
1700 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1701 logger2.error('The five boxing wizards jump quickly.')
1702
1703When you run this, on the console you will see ::
1704
1705 root : INFO Jackdaws love my big sphinx of quartz.
1706 myapp.area1 : INFO How quickly daft jumping zebras vex.
1707 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1708 myapp.area2 : ERROR The five boxing wizards jump quickly.
1709
1710and in the file you will see something like ::
1711
1712 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1713 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1714 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1715 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1716 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1717
1718As you can see, the DEBUG message only shows up in the file. The other messages
1719are sent to both destinations.
1720
1721This example uses console and file handlers, but you can use any number and
1722combination of handlers you choose.
1723
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001724.. _logging-exceptions:
1725
1726Exceptions raised during logging
1727--------------------------------
1728
1729The logging package is designed to swallow exceptions which occur while logging
1730in production. This is so that errors which occur while handling logging events
1731- such as logging misconfiguration, network or other similar errors - do not
1732cause the application using logging to terminate prematurely.
1733
1734:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1735swallowed. Other exceptions which occur during the :meth:`emit` method of a
1736:class:`Handler` subclass are passed to its :meth:`handleError` method.
1737
1738The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001739to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1740traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001741
Georg Brandlef871f62010-03-12 10:06:40 +00001742**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001743during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001744occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001745usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001746
Christian Heimes790c8232008-01-07 21:14:23 +00001747.. _context-info:
1748
1749Adding contextual information to your logging output
1750----------------------------------------------------
1751
1752Sometimes you want logging output to contain contextual information in
1753addition to the parameters passed to the logging call. For example, in a
1754networked application, it may be desirable to log client-specific information
1755in the log (e.g. remote client's username, or IP address). Although you could
1756use the *extra* parameter to achieve this, it's not always convenient to pass
1757the information in this way. While it might be tempting to create
1758:class:`Logger` instances on a per-connection basis, this is not a good idea
1759because these instances are not garbage collected. While this is not a problem
1760in practice, when the number of :class:`Logger` instances is dependent on the
1761level of granularity you want to use in logging an application, it could
1762be hard to manage if the number of :class:`Logger` instances becomes
1763effectively unbounded.
1764
Vinay Sajipc31be632010-09-06 22:18:20 +00001765
1766Using LoggerAdapters to impart contextual information
1767^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1768
Christian Heimes04c420f2008-01-18 18:40:46 +00001769An easy way in which you can pass contextual information to be output along
1770with logging event information is to use the :class:`LoggerAdapter` class.
1771This class is designed to look like a :class:`Logger`, so that you can call
1772:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1773:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1774same signatures as their counterparts in :class:`Logger`, so you can use the
1775two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001776
Christian Heimes04c420f2008-01-18 18:40:46 +00001777When you create an instance of :class:`LoggerAdapter`, you pass it a
1778:class:`Logger` instance and a dict-like object which contains your contextual
1779information. When you call one of the logging methods on an instance of
1780:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1781:class:`Logger` passed to its constructor, and arranges to pass the contextual
1782information in the delegated call. Here's a snippet from the code of
1783:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001784
Christian Heimes04c420f2008-01-18 18:40:46 +00001785 def debug(self, msg, *args, **kwargs):
1786 """
1787 Delegate a debug call to the underlying logger, after adding
1788 contextual information from this adapter instance.
1789 """
1790 msg, kwargs = self.process(msg, kwargs)
1791 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001792
Christian Heimes04c420f2008-01-18 18:40:46 +00001793The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1794information is added to the logging output. It's passed the message and
1795keyword arguments of the logging call, and it passes back (potentially)
1796modified versions of these to use in the call to the underlying logger. The
1797default implementation of this method leaves the message alone, but inserts
1798an "extra" key in the keyword argument whose value is the dict-like object
1799passed to the constructor. Of course, if you had passed an "extra" keyword
1800argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001801
Christian Heimes04c420f2008-01-18 18:40:46 +00001802The advantage of using "extra" is that the values in the dict-like object are
1803merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1804customized strings with your :class:`Formatter` instances which know about
1805the keys of the dict-like object. If you need a different method, e.g. if you
1806want to prepend or append the contextual information to the message string,
1807you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1808to do what you need. Here's an example script which uses this class, which
1809also illustrates what dict-like behaviour is needed from an arbitrary
1810"dict-like" object for use in the constructor::
1811
Christian Heimes587c2bf2008-01-19 16:21:02 +00001812 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001813
Christian Heimes587c2bf2008-01-19 16:21:02 +00001814 class ConnInfo:
1815 """
1816 An example class which shows how an arbitrary class can be used as
1817 the 'extra' context information repository passed to a LoggerAdapter.
1818 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001819
Christian Heimes587c2bf2008-01-19 16:21:02 +00001820 def __getitem__(self, name):
1821 """
1822 To allow this instance to look like a dict.
1823 """
1824 from random import choice
1825 if name == "ip":
1826 result = choice(["127.0.0.1", "192.168.0.1"])
1827 elif name == "user":
1828 result = choice(["jim", "fred", "sheila"])
1829 else:
1830 result = self.__dict__.get(name, "?")
1831 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001832
Christian Heimes587c2bf2008-01-19 16:21:02 +00001833 def __iter__(self):
1834 """
1835 To allow iteration over keys, which will be merged into
1836 the LogRecord dict before formatting and output.
1837 """
1838 keys = ["ip", "user"]
1839 keys.extend(self.__dict__.keys())
1840 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001841
Christian Heimes587c2bf2008-01-19 16:21:02 +00001842 if __name__ == "__main__":
1843 from random import choice
1844 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1845 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1846 { "ip" : "123.231.231.123", "user" : "sheila" })
1847 logging.basicConfig(level=logging.DEBUG,
1848 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1849 a1.debug("A debug message")
1850 a1.info("An info message with %s", "some parameters")
1851 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1852 for x in range(10):
1853 lvl = choice(levels)
1854 lvlname = logging.getLevelName(lvl)
1855 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001856
1857When this script is run, the output should look something like this::
1858
Christian Heimes587c2bf2008-01-19 16:21:02 +00001859 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1860 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1861 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
1862 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
1863 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
1864 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
1865 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
1866 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
1867 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
1868 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
1869 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
1870 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 +00001871
Christian Heimes790c8232008-01-07 21:14:23 +00001872
Vinay Sajipac007992010-09-17 12:45:26 +00001873.. _filters-contextual:
1874
Vinay Sajipc31be632010-09-06 22:18:20 +00001875Using Filters to impart contextual information
1876^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1877
1878You can also add contextual information to log output using a user-defined
1879:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1880passed to them, including adding additional attributes which can then be output
1881using a suitable format string, or if needed a custom :class:`Formatter`.
1882
1883For example in a web application, the request being processed (or at least,
1884the interesting parts of it) can be stored in a threadlocal
1885(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1886add, say, information from the request - say, the remote IP address and remote
1887user's username - to the ``LogRecord``, using the attribute names 'ip' and
1888'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1889string can be used to get similar output to that shown above. Here's an example
1890script::
1891
1892 import logging
1893 from random import choice
1894
1895 class ContextFilter(logging.Filter):
1896 """
1897 This is a filter which injects contextual information into the log.
1898
1899 Rather than use actual contextual information, we just use random
1900 data in this demo.
1901 """
1902
1903 USERS = ['jim', 'fred', 'sheila']
1904 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1905
1906 def filter(self, record):
1907
1908 record.ip = choice(ContextFilter.IPS)
1909 record.user = choice(ContextFilter.USERS)
1910 return True
1911
1912 if __name__ == "__main__":
1913 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1914 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1915 { "ip" : "123.231.231.123", "user" : "sheila" })
1916 logging.basicConfig(level=logging.DEBUG,
1917 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1918 a1 = logging.getLogger("a.b.c")
1919 a2 = logging.getLogger("d.e.f")
1920
1921 f = ContextFilter()
1922 a1.addFilter(f)
1923 a2.addFilter(f)
1924 a1.debug("A debug message")
1925 a1.info("An info message with %s", "some parameters")
1926 for x in range(10):
1927 lvl = choice(levels)
1928 lvlname = logging.getLevelName(lvl)
1929 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1930
1931which, when run, produces something like::
1932
1933 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1934 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1935 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
1936 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
1937 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
1938 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
1939 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
1940 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
1941 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
1942 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
1943 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
1944 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
1945
1946
Vinay Sajipd31f3632010-06-29 15:31:15 +00001947.. _multiple-processes:
1948
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001949Logging to a single file from multiple processes
1950------------------------------------------------
1951
1952Although logging is thread-safe, and logging to a single file from multiple
1953threads in a single process *is* supported, logging to a single file from
1954*multiple processes* is *not* supported, because there is no standard way to
1955serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001956need to log to a single file from multiple processes, one way of doing this is
1957to have all the processes log to a :class:`SocketHandler`, and have a separate
1958process which implements a socket server which reads from the socket and logs
1959to file. (If you prefer, you can dedicate one thread in one of the existing
1960processes to perform this function.) The following section documents this
1961approach in more detail and includes a working socket receiver which can be
1962used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001963
Vinay Sajip5a92b132009-08-15 23:35:08 +00001964If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001965:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001966:class:`Lock` class from this module to serialize access to the file from
1967your processes. The existing :class:`FileHandler` and subclasses do not make
1968use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001969Note that at present, the :mod:`multiprocessing` module does not provide
1970working lock functionality on all platforms (see
1971http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001972
Vinay Sajip121a1c42010-09-08 10:46:15 +00001973.. currentmodule:: logging.handlers
1974
1975Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1976all logging events to one of the processes in your multi-process application.
1977The following example script demonstrates how you can do this; in the example
1978a separate listener process listens for events sent by other processes and logs
1979them according to its own logging configuration. Although the example only
1980demonstrates one way of doing it (for example, you may want to use a listener
1981thread rather than a separate listener process - the implementation would be
1982analogous) it does allow for completely different logging configurations for
1983the listener and the other processes in your application, and can be used as
1984the basis for code meeting your own specific requirements::
1985
1986 # You'll need these imports in your own code
1987 import logging
1988 import logging.handlers
1989 import multiprocessing
1990
1991 # Next two import lines for this demo only
1992 from random import choice, random
1993 import time
1994
1995 #
1996 # Because you'll want to define the logging configurations for listener and workers, the
1997 # listener and worker process functions take a configurer parameter which is a callable
1998 # for configuring logging for that process. These functions are also passed the queue,
1999 # which they use for communication.
2000 #
2001 # In practice, you can configure the listener however you want, but note that in this
2002 # simple example, the listener does not apply level or filter logic to received records.
2003 # In practice, you would probably want to do ths logic in the worker processes, to avoid
2004 # sending events which would be filtered out between processes.
2005 #
2006 # The size of the rotated files is made small so you can see the results easily.
2007 def listener_configurer():
2008 root = logging.getLogger()
2009 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2010 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2011 h.setFormatter(f)
2012 root.addHandler(h)
2013
2014 # This is the listener process top-level loop: wait for logging events
2015 # (LogRecords)on the queue and handle them, quit when you get a None for a
2016 # LogRecord.
2017 def listener_process(queue, configurer):
2018 configurer()
2019 while True:
2020 try:
2021 record = queue.get()
2022 if record is None: # We send this as a sentinel to tell the listener to quit.
2023 break
2024 logger = logging.getLogger(record.name)
2025 logger.handle(record) # No level or filter logic applied - just do it!
2026 except (KeyboardInterrupt, SystemExit):
2027 raise
2028 except:
2029 import sys, traceback
2030 print >> sys.stderr, 'Whoops! Problem:'
2031 traceback.print_exc(file=sys.stderr)
2032
2033 # Arrays used for random selections in this demo
2034
2035 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2036 logging.ERROR, logging.CRITICAL]
2037
2038 LOGGERS = ['a.b.c', 'd.e.f']
2039
2040 MESSAGES = [
2041 'Random message #1',
2042 'Random message #2',
2043 'Random message #3',
2044 ]
2045
2046 # The worker configuration is done at the start of the worker process run.
2047 # Note that on Windows you can't rely on fork semantics, so each process
2048 # will run the logging configuration code when it starts.
2049 def worker_configurer(queue):
2050 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2051 root = logging.getLogger()
2052 root.addHandler(h)
2053 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2054
2055 # This is the worker process top-level loop, which just logs ten events with
2056 # random intervening delays before terminating.
2057 # The print messages are just so you know it's doing something!
2058 def worker_process(queue, configurer):
2059 configurer(queue)
2060 name = multiprocessing.current_process().name
2061 print('Worker started: %s' % name)
2062 for i in range(10):
2063 time.sleep(random())
2064 logger = logging.getLogger(choice(LOGGERS))
2065 level = choice(LEVELS)
2066 message = choice(MESSAGES)
2067 logger.log(level, message)
2068 print('Worker finished: %s' % name)
2069
2070 # Here's where the demo gets orchestrated. Create the queue, create and start
2071 # the listener, create ten workers and start them, wait for them to finish,
2072 # then send a None to the queue to tell the listener to finish.
2073 def main():
2074 queue = multiprocessing.Queue(-1)
2075 listener = multiprocessing.Process(target=listener_process,
2076 args=(queue, listener_configurer))
2077 listener.start()
2078 workers = []
2079 for i in range(10):
2080 worker = multiprocessing.Process(target=worker_process,
2081 args=(queue, worker_configurer))
2082 workers.append(worker)
2083 worker.start()
2084 for w in workers:
2085 w.join()
2086 queue.put_nowait(None)
2087 listener.join()
2088
2089 if __name__ == '__main__':
2090 main()
2091
2092
2093.. currentmodule:: logging
2094
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002095
Georg Brandl116aa622007-08-15 14:28:22 +00002096.. _network-logging:
2097
2098Sending and receiving logging events across a network
2099-----------------------------------------------------
2100
2101Let's say you want to send logging events across a network, and handle them at
2102the receiving end. A simple way of doing this is attaching a
2103:class:`SocketHandler` instance to the root logger at the sending end::
2104
2105 import logging, logging.handlers
2106
2107 rootLogger = logging.getLogger('')
2108 rootLogger.setLevel(logging.DEBUG)
2109 socketHandler = logging.handlers.SocketHandler('localhost',
2110 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2111 # don't bother with a formatter, since a socket handler sends the event as
2112 # an unformatted pickle
2113 rootLogger.addHandler(socketHandler)
2114
2115 # Now, we can log to the root logger, or any other logger. First the root...
2116 logging.info('Jackdaws love my big sphinx of quartz.')
2117
2118 # Now, define a couple of other loggers which might represent areas in your
2119 # application:
2120
2121 logger1 = logging.getLogger('myapp.area1')
2122 logger2 = logging.getLogger('myapp.area2')
2123
2124 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2125 logger1.info('How quickly daft jumping zebras vex.')
2126 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2127 logger2.error('The five boxing wizards jump quickly.')
2128
Alexandre Vassalottice261952008-05-12 02:31:37 +00002129At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002130module. Here is a basic working example::
2131
Georg Brandla35f4b92009-05-31 16:41:59 +00002132 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002133 import logging
2134 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002135 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002136 import struct
2137
2138
Alexandre Vassalottice261952008-05-12 02:31:37 +00002139 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002140 """Handler for a streaming logging request.
2141
2142 This basically logs the record using whatever logging policy is
2143 configured locally.
2144 """
2145
2146 def handle(self):
2147 """
2148 Handle multiple requests - each expected to be a 4-byte length,
2149 followed by the LogRecord in pickle format. Logs the record
2150 according to whatever policy is configured locally.
2151 """
Collin Winter46334482007-09-10 00:49:57 +00002152 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002153 chunk = self.connection.recv(4)
2154 if len(chunk) < 4:
2155 break
2156 slen = struct.unpack(">L", chunk)[0]
2157 chunk = self.connection.recv(slen)
2158 while len(chunk) < slen:
2159 chunk = chunk + self.connection.recv(slen - len(chunk))
2160 obj = self.unPickle(chunk)
2161 record = logging.makeLogRecord(obj)
2162 self.handleLogRecord(record)
2163
2164 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002165 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002166
2167 def handleLogRecord(self, record):
2168 # if a name is specified, we use the named logger rather than the one
2169 # implied by the record.
2170 if self.server.logname is not None:
2171 name = self.server.logname
2172 else:
2173 name = record.name
2174 logger = logging.getLogger(name)
2175 # N.B. EVERY record gets logged. This is because Logger.handle
2176 # is normally called AFTER logger-level filtering. If you want
2177 # to do filtering, do it at the client end to save wasting
2178 # cycles and network bandwidth!
2179 logger.handle(record)
2180
Alexandre Vassalottice261952008-05-12 02:31:37 +00002181 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00002182 """simple TCP socket-based logging receiver suitable for testing.
2183 """
2184
2185 allow_reuse_address = 1
2186
2187 def __init__(self, host='localhost',
2188 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2189 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002190 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002191 self.abort = 0
2192 self.timeout = 1
2193 self.logname = None
2194
2195 def serve_until_stopped(self):
2196 import select
2197 abort = 0
2198 while not abort:
2199 rd, wr, ex = select.select([self.socket.fileno()],
2200 [], [],
2201 self.timeout)
2202 if rd:
2203 self.handle_request()
2204 abort = self.abort
2205
2206 def main():
2207 logging.basicConfig(
2208 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
2209 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00002210 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00002211 tcpserver.serve_until_stopped()
2212
2213 if __name__ == "__main__":
2214 main()
2215
2216First run the server, and then the client. On the client side, nothing is
2217printed on the console; on the server side, you should see something like::
2218
2219 About to start TCP server...
2220 59 root INFO Jackdaws love my big sphinx of quartz.
2221 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2222 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2223 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2224 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2225
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002226Note that there are some security issues with pickle in some scenarios. If
2227these affect you, you can use an alternative serialization scheme by overriding
2228the :meth:`makePickle` method and implementing your alternative there, as
2229well as adapting the above script to use your alternative serialization.
2230
Vinay Sajip4039aff2010-09-11 10:25:28 +00002231.. _arbitrary-object-messages:
2232
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002233Using arbitrary objects as messages
2234-----------------------------------
2235
2236In the preceding sections and examples, it has been assumed that the message
2237passed when logging the event is a string. However, this is not the only
2238possibility. You can pass an arbitrary object as a message, and its
2239:meth:`__str__` method will be called when the logging system needs to convert
2240it to a string representation. In fact, if you want to, you can avoid
2241computing a string representation altogether - for example, the
2242:class:`SocketHandler` emits an event by pickling it and sending it over the
2243wire.
2244
Vinay Sajip55778922010-09-23 09:09:15 +00002245Dealing with handlers that block
2246--------------------------------
2247
2248.. currentmodule:: logging.handlers
2249
2250Sometimes you have to get your logging handlers to do their work without
2251blocking the thread you’re logging from. This is common in Web applications,
2252though of course it also occurs in other scenarios.
2253
2254A common culprit which demonstrates sluggish behaviour is the
2255:class:`SMTPHandler`: sending emails can take a long time, for a
2256number of reasons outside the developer’s control (for example, a poorly
2257performing mail or network infrastructure). But almost any network-based
2258handler can block: Even a :class:`SocketHandler` operation may do a
2259DNS query under the hood which is too slow (and this query can be deep in the
2260socket library code, below the Python layer, and outside your control).
2261
2262One solution is to use a two-part approach. For the first part, attach only a
2263:class:`QueueHandler` to those loggers which are accessed from
2264performance-critical threads. They simply write to their queue, which can be
2265sized to a large enough capacity or initialized with no upper bound to their
2266size. The write to the queue will typically be accepted quickly, though you
2267will probably need to catch the :ref:`queue.Full` exception as a precaution
2268in your code. If you are a library developer who has performance-critical
2269threads in their code, be sure to document this (together with a suggestion to
2270attach only ``QueueHandlers`` to your loggers) for the benefit of other
2271developers who will use your code.
2272
2273The second part of the solution is :class:`QueueListener`, which has been
2274designed as the counterpart to :class:`QueueHandler`. A
2275:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2276and it fires up an internal thread which listens to its queue for LogRecords
2277sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2278matter). The ``LogRecords`` are removed from the queue and passed to the
2279handlers for processing.
2280
2281The advantage of having a separate :class:`QueueListener` class is that you
2282can use the same instance to service multiple ``QueueHandlers``. This is more
2283resource-friendly than, say, having threaded versions of the existing handler
2284classes, which would eat up one thread per handler for no particular benefit.
2285
2286An example of using these two classes follows (imports omitted)::
2287
2288 que = queue.Queue(-1) # no limit on size
2289 queue_handler = QueueHandler(que)
2290 handler = logging.StreamHandler()
2291 listener = QueueListener(que, handler)
2292 root = logging.getLogger()
2293 root.addHandler(queue_handler)
2294 formatter = logging.Formatter('%(threadName)s: %(message)s')
2295 handler.setFormatter(formatter)
2296 listener.start()
2297 # The log output will display the thread which generated
2298 # the event (the main thread) rather than the internal
2299 # thread which monitors the internal queue. This is what
2300 # you want to happen.
2301 root.warning('Look out!')
2302 listener.stop()
2303
2304which, when run, will produce::
2305
2306 MainThread: Look out!
2307
2308
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002309Optimization
2310------------
2311
2312Formatting of message arguments is deferred until it cannot be avoided.
2313However, computing the arguments passed to the logging method can also be
2314expensive, and you may want to avoid doing it if the logger will just throw
2315away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2316method which takes a level argument and returns true if the event would be
2317created by the Logger for that level of call. You can write code like this::
2318
2319 if logger.isEnabledFor(logging.DEBUG):
2320 logger.debug("Message with %s, %s", expensive_func1(),
2321 expensive_func2())
2322
2323so that if the logger's threshold is set above ``DEBUG``, the calls to
2324:func:`expensive_func1` and :func:`expensive_func2` are never made.
2325
2326There are other optimizations which can be made for specific applications which
2327need more precise control over what logging information is collected. Here's a
2328list of things you can do to avoid processing during logging which you don't
2329need:
2330
2331+-----------------------------------------------+----------------------------------------+
2332| What you don't want to collect | How to avoid collecting it |
2333+===============================================+========================================+
2334| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2335+-----------------------------------------------+----------------------------------------+
2336| Threading information. | Set ``logging.logThreads`` to ``0``. |
2337+-----------------------------------------------+----------------------------------------+
2338| Process information. | Set ``logging.logProcesses`` to ``0``. |
2339+-----------------------------------------------+----------------------------------------+
2340
2341Also note that the core logging module only includes the basic handlers. If
2342you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2343take up any memory.
2344
2345.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002346
2347Handler Objects
2348---------------
2349
2350Handlers have the following attributes and methods. Note that :class:`Handler`
2351is never instantiated directly; this class acts as a base for more useful
2352subclasses. However, the :meth:`__init__` method in subclasses needs to call
2353:meth:`Handler.__init__`.
2354
2355
2356.. method:: Handler.__init__(level=NOTSET)
2357
2358 Initializes the :class:`Handler` instance by setting its level, setting the list
2359 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2360 serializing access to an I/O mechanism.
2361
2362
2363.. method:: Handler.createLock()
2364
2365 Initializes a thread lock which can be used to serialize access to underlying
2366 I/O functionality which may not be threadsafe.
2367
2368
2369.. method:: Handler.acquire()
2370
2371 Acquires the thread lock created with :meth:`createLock`.
2372
2373
2374.. method:: Handler.release()
2375
2376 Releases the thread lock acquired with :meth:`acquire`.
2377
2378
2379.. method:: Handler.setLevel(lvl)
2380
2381 Sets the threshold for this handler to *lvl*. Logging messages which are less
2382 severe than *lvl* will be ignored. When a handler is created, the level is set
2383 to :const:`NOTSET` (which causes all messages to be processed).
2384
2385
2386.. method:: Handler.setFormatter(form)
2387
2388 Sets the :class:`Formatter` for this handler to *form*.
2389
2390
2391.. method:: Handler.addFilter(filt)
2392
2393 Adds the specified filter *filt* to this handler.
2394
2395
2396.. method:: Handler.removeFilter(filt)
2397
2398 Removes the specified filter *filt* from this handler.
2399
2400
2401.. method:: Handler.filter(record)
2402
2403 Applies this handler's filters to the record and returns a true value if the
2404 record is to be processed.
2405
2406
2407.. method:: Handler.flush()
2408
2409 Ensure all logging output has been flushed. This version does nothing and is
2410 intended to be implemented by subclasses.
2411
2412
2413.. method:: Handler.close()
2414
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002415 Tidy up any resources used by the handler. This version does no output but
2416 removes the handler from an internal list of handlers which is closed when
2417 :func:`shutdown` is called. Subclasses should ensure that this gets called
2418 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002419
2420
2421.. method:: Handler.handle(record)
2422
2423 Conditionally emits the specified logging record, depending on filters which may
2424 have been added to the handler. Wraps the actual emission of the record with
2425 acquisition/release of the I/O thread lock.
2426
2427
2428.. method:: Handler.handleError(record)
2429
2430 This method should be called from handlers when an exception is encountered
2431 during an :meth:`emit` call. By default it does nothing, which means that
2432 exceptions get silently ignored. This is what is mostly wanted for a logging
2433 system - most users will not care about errors in the logging system, they are
2434 more interested in application errors. You could, however, replace this with a
2435 custom handler if you wish. The specified record is the one which was being
2436 processed when the exception occurred.
2437
2438
2439.. method:: Handler.format(record)
2440
2441 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2442 default formatter for the module.
2443
2444
2445.. method:: Handler.emit(record)
2446
2447 Do whatever it takes to actually log the specified logging record. This version
2448 is intended to be implemented by subclasses and so raises a
2449 :exc:`NotImplementedError`.
2450
2451
Vinay Sajipd31f3632010-06-29 15:31:15 +00002452.. _stream-handler:
2453
Georg Brandl116aa622007-08-15 14:28:22 +00002454StreamHandler
2455^^^^^^^^^^^^^
2456
2457The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2458sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2459file-like object (or, more precisely, any object which supports :meth:`write`
2460and :meth:`flush` methods).
2461
2462
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002463.. currentmodule:: logging
2464
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002465.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002466
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002467 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002468 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2469 will be used.
2470
2471
Benjamin Petersone41251e2008-04-25 01:59:09 +00002472 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002473
Benjamin Petersone41251e2008-04-25 01:59:09 +00002474 If a formatter is specified, it is used to format the record. The record
2475 is then written to the stream with a trailing newline. If exception
2476 information is present, it is formatted using
2477 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002478
2479
Benjamin Petersone41251e2008-04-25 01:59:09 +00002480 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002481
Benjamin Petersone41251e2008-04-25 01:59:09 +00002482 Flushes the stream by calling its :meth:`flush` method. Note that the
2483 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002484 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002485
Vinay Sajip05ed6952010-10-20 20:34:09 +00002486.. versionchanged:: 3.2
2487 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2488 value ``"\n"``, which is used as the terminator when writing a formatted
2489 record to a stream. If you don't want this newline termination, you can
2490 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002491
Vinay Sajipd31f3632010-06-29 15:31:15 +00002492.. _file-handler:
2493
Georg Brandl116aa622007-08-15 14:28:22 +00002494FileHandler
2495^^^^^^^^^^^
2496
2497The :class:`FileHandler` class, located in the core :mod:`logging` package,
2498sends logging output to a disk file. It inherits the output functionality from
2499:class:`StreamHandler`.
2500
2501
Vinay Sajipd31f3632010-06-29 15:31:15 +00002502.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002503
2504 Returns a new instance of the :class:`FileHandler` class. The specified file is
2505 opened and used as the stream for logging. If *mode* is not specified,
2506 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002507 with that encoding. If *delay* is true, then file opening is deferred until the
2508 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002509
2510
Benjamin Petersone41251e2008-04-25 01:59:09 +00002511 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002512
Benjamin Petersone41251e2008-04-25 01:59:09 +00002513 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002514
2515
Benjamin Petersone41251e2008-04-25 01:59:09 +00002516 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002517
Benjamin Petersone41251e2008-04-25 01:59:09 +00002518 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002519
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002520
Vinay Sajipd31f3632010-06-29 15:31:15 +00002521.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002522
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002523NullHandler
2524^^^^^^^^^^^
2525
2526.. versionadded:: 3.1
2527
2528The :class:`NullHandler` class, located in the core :mod:`logging` package,
2529does not do any formatting or output. It is essentially a "no-op" handler
2530for use by library developers.
2531
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002532.. class:: NullHandler()
2533
2534 Returns a new instance of the :class:`NullHandler` class.
2535
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002536 .. method:: emit(record)
2537
2538 This method does nothing.
2539
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002540 .. method:: handle(record)
2541
2542 This method does nothing.
2543
2544 .. method:: createLock()
2545
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002546 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002547 underlying I/O to which access needs to be serialized.
2548
2549
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002550See :ref:`library-config` for more information on how to use
2551:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002552
Vinay Sajipd31f3632010-06-29 15:31:15 +00002553.. _watched-file-handler:
2554
Georg Brandl116aa622007-08-15 14:28:22 +00002555WatchedFileHandler
2556^^^^^^^^^^^^^^^^^^
2557
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002558.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002559
Georg Brandl116aa622007-08-15 14:28:22 +00002560The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2561module, is a :class:`FileHandler` which watches the file it is logging to. If
2562the file changes, it is closed and reopened using the file name.
2563
2564A file change can happen because of usage of programs such as *newsyslog* and
2565*logrotate* which perform log file rotation. This handler, intended for use
2566under Unix/Linux, watches the file to see if it has changed since the last emit.
2567(A file is deemed to have changed if its device or inode have changed.) If the
2568file has changed, the old file stream is closed, and the file opened to get a
2569new stream.
2570
2571This handler is not appropriate for use under Windows, because under Windows
2572open log files cannot be moved or renamed - logging opens the files with
2573exclusive locks - and so there is no need for such a handler. Furthermore,
2574*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2575this value.
2576
2577
Christian Heimese7a15bb2008-01-24 16:21:45 +00002578.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002579
2580 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2581 file is opened and used as the stream for logging. If *mode* is not specified,
2582 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002583 with that encoding. If *delay* is true, then file opening is deferred until the
2584 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002585
2586
Benjamin Petersone41251e2008-04-25 01:59:09 +00002587 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002588
Benjamin Petersone41251e2008-04-25 01:59:09 +00002589 Outputs the record to the file, but first checks to see if the file has
2590 changed. If it has, the existing stream is flushed and closed and the
2591 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002592
Vinay Sajipd31f3632010-06-29 15:31:15 +00002593.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002594
2595RotatingFileHandler
2596^^^^^^^^^^^^^^^^^^^
2597
2598The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2599module, supports rotation of disk log files.
2600
2601
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002602.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002603
2604 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2605 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002606 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2607 with that encoding. If *delay* is true, then file opening is deferred until the
2608 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002609
2610 You can use the *maxBytes* and *backupCount* values to allow the file to
2611 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2612 the file is closed and a new file is silently opened for output. Rollover occurs
2613 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2614 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2615 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2616 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2617 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2618 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2619 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2620 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2621 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2622
2623
Benjamin Petersone41251e2008-04-25 01:59:09 +00002624 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002625
Benjamin Petersone41251e2008-04-25 01:59:09 +00002626 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002627
2628
Benjamin Petersone41251e2008-04-25 01:59:09 +00002629 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002630
Benjamin Petersone41251e2008-04-25 01:59:09 +00002631 Outputs the record to the file, catering for rollover as described
2632 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002633
Vinay Sajipd31f3632010-06-29 15:31:15 +00002634.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002635
2636TimedRotatingFileHandler
2637^^^^^^^^^^^^^^^^^^^^^^^^
2638
2639The :class:`TimedRotatingFileHandler` class, located in the
2640:mod:`logging.handlers` module, supports rotation of disk log files at certain
2641timed intervals.
2642
2643
Vinay Sajipd31f3632010-06-29 15:31:15 +00002644.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002645
2646 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2647 specified file is opened and used as the stream for logging. On rotating it also
2648 sets the filename suffix. Rotating happens based on the product of *when* and
2649 *interval*.
2650
2651 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002652 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002653
Christian Heimesb558a2e2008-03-02 22:46:37 +00002654 +----------------+-----------------------+
2655 | Value | Type of interval |
2656 +================+=======================+
2657 | ``'S'`` | Seconds |
2658 +----------------+-----------------------+
2659 | ``'M'`` | Minutes |
2660 +----------------+-----------------------+
2661 | ``'H'`` | Hours |
2662 +----------------+-----------------------+
2663 | ``'D'`` | Days |
2664 +----------------+-----------------------+
2665 | ``'W'`` | Week day (0=Monday) |
2666 +----------------+-----------------------+
2667 | ``'midnight'`` | Roll over at midnight |
2668 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002669
Christian Heimesb558a2e2008-03-02 22:46:37 +00002670 The system will save old log files by appending extensions to the filename.
2671 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002672 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002673 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002674
2675 When computing the next rollover time for the first time (when the handler
2676 is created), the last modification time of an existing log file, or else
2677 the current time, is used to compute when the next rotation will occur.
2678
Georg Brandl0c77a822008-06-10 16:37:50 +00002679 If the *utc* argument is true, times in UTC will be used; otherwise
2680 local time is used.
2681
2682 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002683 will be kept, and if more would be created when rollover occurs, the oldest
2684 one is deleted. The deletion logic uses the interval to determine which
2685 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002686
Vinay Sajipd31f3632010-06-29 15:31:15 +00002687 If *delay* is true, then file opening is deferred until the first call to
2688 :meth:`emit`.
2689
Georg Brandl116aa622007-08-15 14:28:22 +00002690
Benjamin Petersone41251e2008-04-25 01:59:09 +00002691 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002692
Benjamin Petersone41251e2008-04-25 01:59:09 +00002693 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002694
2695
Benjamin Petersone41251e2008-04-25 01:59:09 +00002696 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002697
Benjamin Petersone41251e2008-04-25 01:59:09 +00002698 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002699
2700
Vinay Sajipd31f3632010-06-29 15:31:15 +00002701.. _socket-handler:
2702
Georg Brandl116aa622007-08-15 14:28:22 +00002703SocketHandler
2704^^^^^^^^^^^^^
2705
2706The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2707sends logging output to a network socket. The base class uses a TCP socket.
2708
2709
2710.. class:: SocketHandler(host, port)
2711
2712 Returns a new instance of the :class:`SocketHandler` class intended to
2713 communicate with a remote machine whose address is given by *host* and *port*.
2714
2715
Benjamin Petersone41251e2008-04-25 01:59:09 +00002716 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002717
Benjamin Petersone41251e2008-04-25 01:59:09 +00002718 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002719
2720
Benjamin Petersone41251e2008-04-25 01:59:09 +00002721 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002722
Benjamin Petersone41251e2008-04-25 01:59:09 +00002723 Pickles the record's attribute dictionary and writes it to the socket in
2724 binary format. If there is an error with the socket, silently drops the
2725 packet. If the connection was previously lost, re-establishes the
2726 connection. To unpickle the record at the receiving end into a
2727 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002728
2729
Benjamin Petersone41251e2008-04-25 01:59:09 +00002730 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002731
Benjamin Petersone41251e2008-04-25 01:59:09 +00002732 Handles an error which has occurred during :meth:`emit`. The most likely
2733 cause is a lost connection. Closes the socket so that we can retry on the
2734 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002735
2736
Benjamin Petersone41251e2008-04-25 01:59:09 +00002737 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002738
Benjamin Petersone41251e2008-04-25 01:59:09 +00002739 This is a factory method which allows subclasses to define the precise
2740 type of socket they want. The default implementation creates a TCP socket
2741 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002742
2743
Benjamin Petersone41251e2008-04-25 01:59:09 +00002744 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002745
Benjamin Petersone41251e2008-04-25 01:59:09 +00002746 Pickles the record's attribute dictionary in binary format with a length
2747 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002748
Vinay Sajipd31f3632010-06-29 15:31:15 +00002749 Note that pickles aren't completely secure. If you are concerned about
2750 security, you may want to override this method to implement a more secure
2751 mechanism. For example, you can sign pickles using HMAC and then verify
2752 them on the receiving end, or alternatively you can disable unpickling of
2753 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002754
Benjamin Petersone41251e2008-04-25 01:59:09 +00002755 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002756
Benjamin Petersone41251e2008-04-25 01:59:09 +00002757 Send a pickled string *packet* to the socket. This function allows for
2758 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002759
2760
Vinay Sajipd31f3632010-06-29 15:31:15 +00002761.. _datagram-handler:
2762
Georg Brandl116aa622007-08-15 14:28:22 +00002763DatagramHandler
2764^^^^^^^^^^^^^^^
2765
2766The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2767module, inherits from :class:`SocketHandler` to support sending logging messages
2768over UDP sockets.
2769
2770
2771.. class:: DatagramHandler(host, port)
2772
2773 Returns a new instance of the :class:`DatagramHandler` class intended to
2774 communicate with a remote machine whose address is given by *host* and *port*.
2775
2776
Benjamin Petersone41251e2008-04-25 01:59:09 +00002777 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002778
Benjamin Petersone41251e2008-04-25 01:59:09 +00002779 Pickles the record's attribute dictionary and writes it to the socket in
2780 binary format. If there is an error with the socket, silently drops the
2781 packet. To unpickle the record at the receiving end into a
2782 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002783
2784
Benjamin Petersone41251e2008-04-25 01:59:09 +00002785 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002786
Benjamin Petersone41251e2008-04-25 01:59:09 +00002787 The factory method of :class:`SocketHandler` is here overridden to create
2788 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002789
2790
Benjamin Petersone41251e2008-04-25 01:59:09 +00002791 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002792
Benjamin Petersone41251e2008-04-25 01:59:09 +00002793 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002794
2795
Vinay Sajipd31f3632010-06-29 15:31:15 +00002796.. _syslog-handler:
2797
Georg Brandl116aa622007-08-15 14:28:22 +00002798SysLogHandler
2799^^^^^^^^^^^^^
2800
2801The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2802supports sending logging messages to a remote or local Unix syslog.
2803
2804
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002805.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002806
2807 Returns a new instance of the :class:`SysLogHandler` class intended to
2808 communicate with a remote Unix machine whose address is given by *address* in
2809 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002810 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002811 alternative to providing a ``(host, port)`` tuple is providing an address as a
2812 string, for example "/dev/log". In this case, a Unix domain socket is used to
2813 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002814 :const:`LOG_USER` is used. The type of socket opened depends on the
2815 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2816 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2817 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2818
Vinay Sajip972412d2010-09-23 20:31:24 +00002819 Note that if your server is not listening on UDP port 514,
2820 :class:`SysLogHandler` may appear not to work. In that case, check what
2821 address you should be using for a domain socket - it's system dependent.
2822 For example, on Linux it's usually "/dev/log" but on OS/X it's
2823 "/var/run/syslog". You'll need to check your platform and use the
2824 appropriate address (you may need to do this check at runtime if your
2825 application needs to run on several platforms). On Windows, you pretty
2826 much have to use the UDP option.
2827
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002828 .. versionchanged:: 3.2
2829 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002830
2831
Benjamin Petersone41251e2008-04-25 01:59:09 +00002832 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002833
Benjamin Petersone41251e2008-04-25 01:59:09 +00002834 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002835
2836
Benjamin Petersone41251e2008-04-25 01:59:09 +00002837 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002838
Benjamin Petersone41251e2008-04-25 01:59:09 +00002839 The record is formatted, and then sent to the syslog server. If exception
2840 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002841
2842
Benjamin Petersone41251e2008-04-25 01:59:09 +00002843 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002844
Benjamin Petersone41251e2008-04-25 01:59:09 +00002845 Encodes the facility and priority into an integer. You can pass in strings
2846 or integers - if strings are passed, internal mapping dictionaries are
2847 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002848
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002849 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2850 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002851
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002852 **Priorities**
2853
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002854 +--------------------------+---------------+
2855 | Name (string) | Symbolic value|
2856 +==========================+===============+
2857 | ``alert`` | LOG_ALERT |
2858 +--------------------------+---------------+
2859 | ``crit`` or ``critical`` | LOG_CRIT |
2860 +--------------------------+---------------+
2861 | ``debug`` | LOG_DEBUG |
2862 +--------------------------+---------------+
2863 | ``emerg`` or ``panic`` | LOG_EMERG |
2864 +--------------------------+---------------+
2865 | ``err`` or ``error`` | LOG_ERR |
2866 +--------------------------+---------------+
2867 | ``info`` | LOG_INFO |
2868 +--------------------------+---------------+
2869 | ``notice`` | LOG_NOTICE |
2870 +--------------------------+---------------+
2871 | ``warn`` or ``warning`` | LOG_WARNING |
2872 +--------------------------+---------------+
2873
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002874 **Facilities**
2875
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002876 +---------------+---------------+
2877 | Name (string) | Symbolic value|
2878 +===============+===============+
2879 | ``auth`` | LOG_AUTH |
2880 +---------------+---------------+
2881 | ``authpriv`` | LOG_AUTHPRIV |
2882 +---------------+---------------+
2883 | ``cron`` | LOG_CRON |
2884 +---------------+---------------+
2885 | ``daemon`` | LOG_DAEMON |
2886 +---------------+---------------+
2887 | ``ftp`` | LOG_FTP |
2888 +---------------+---------------+
2889 | ``kern`` | LOG_KERN |
2890 +---------------+---------------+
2891 | ``lpr`` | LOG_LPR |
2892 +---------------+---------------+
2893 | ``mail`` | LOG_MAIL |
2894 +---------------+---------------+
2895 | ``news`` | LOG_NEWS |
2896 +---------------+---------------+
2897 | ``syslog`` | LOG_SYSLOG |
2898 +---------------+---------------+
2899 | ``user`` | LOG_USER |
2900 +---------------+---------------+
2901 | ``uucp`` | LOG_UUCP |
2902 +---------------+---------------+
2903 | ``local0`` | LOG_LOCAL0 |
2904 +---------------+---------------+
2905 | ``local1`` | LOG_LOCAL1 |
2906 +---------------+---------------+
2907 | ``local2`` | LOG_LOCAL2 |
2908 +---------------+---------------+
2909 | ``local3`` | LOG_LOCAL3 |
2910 +---------------+---------------+
2911 | ``local4`` | LOG_LOCAL4 |
2912 +---------------+---------------+
2913 | ``local5`` | LOG_LOCAL5 |
2914 +---------------+---------------+
2915 | ``local6`` | LOG_LOCAL6 |
2916 +---------------+---------------+
2917 | ``local7`` | LOG_LOCAL7 |
2918 +---------------+---------------+
2919
2920 .. method:: mapPriority(levelname)
2921
2922 Maps a logging level name to a syslog priority name.
2923 You may need to override this if you are using custom levels, or
2924 if the default algorithm is not suitable for your needs. The
2925 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2926 ``CRITICAL`` to the equivalent syslog names, and all other level
2927 names to "warning".
2928
2929.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002930
2931NTEventLogHandler
2932^^^^^^^^^^^^^^^^^
2933
2934The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2935module, supports sending logging messages to a local Windows NT, Windows 2000 or
2936Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2937extensions for Python installed.
2938
2939
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002940.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002941
2942 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2943 used to define the application name as it appears in the event log. An
2944 appropriate registry entry is created using this name. The *dllname* should give
2945 the fully qualified pathname of a .dll or .exe which contains message
2946 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2947 - this is installed with the Win32 extensions and contains some basic
2948 placeholder message definitions. Note that use of these placeholders will make
2949 your event logs big, as the entire message source is held in the log. If you
2950 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2951 contains the message definitions you want to use in the event log). The
2952 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2953 defaults to ``'Application'``.
2954
2955
Benjamin Petersone41251e2008-04-25 01:59:09 +00002956 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002957
Benjamin Petersone41251e2008-04-25 01:59:09 +00002958 At this point, you can remove the application name from the registry as a
2959 source of event log entries. However, if you do this, you will not be able
2960 to see the events as you intended in the Event Log Viewer - it needs to be
2961 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002962 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002963
2964
Benjamin Petersone41251e2008-04-25 01:59:09 +00002965 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002966
Benjamin Petersone41251e2008-04-25 01:59:09 +00002967 Determines the message ID, event category and event type, and then logs
2968 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002969
2970
Benjamin Petersone41251e2008-04-25 01:59:09 +00002971 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002972
Benjamin Petersone41251e2008-04-25 01:59:09 +00002973 Returns the event category for the record. Override this if you want to
2974 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002975
2976
Benjamin Petersone41251e2008-04-25 01:59:09 +00002977 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002978
Benjamin Petersone41251e2008-04-25 01:59:09 +00002979 Returns the event type for the record. Override this if you want to
2980 specify your own types. This version does a mapping using the handler's
2981 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2982 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2983 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2984 your own levels, you will either need to override this method or place a
2985 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002986
2987
Benjamin Petersone41251e2008-04-25 01:59:09 +00002988 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002989
Benjamin Petersone41251e2008-04-25 01:59:09 +00002990 Returns the message ID for the record. If you are using your own messages,
2991 you could do this by having the *msg* passed to the logger being an ID
2992 rather than a format string. Then, in here, you could use a dictionary
2993 lookup to get the message ID. This version returns 1, which is the base
2994 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002995
Vinay Sajipd31f3632010-06-29 15:31:15 +00002996.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002997
2998SMTPHandler
2999^^^^^^^^^^^
3000
3001The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
3002supports sending logging messages to an email address via SMTP.
3003
3004
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003005.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003006
3007 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3008 initialized with the from and to addresses and subject line of the email. The
3009 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3010 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3011 the standard SMTP port is used. If your SMTP server requires authentication, you
3012 can specify a (username, password) tuple for the *credentials* argument.
3013
Georg Brandl116aa622007-08-15 14:28:22 +00003014
Benjamin Petersone41251e2008-04-25 01:59:09 +00003015 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003016
Benjamin Petersone41251e2008-04-25 01:59:09 +00003017 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003018
3019
Benjamin Petersone41251e2008-04-25 01:59:09 +00003020 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003021
Benjamin Petersone41251e2008-04-25 01:59:09 +00003022 If you want to specify a subject line which is record-dependent, override
3023 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003024
Vinay Sajipd31f3632010-06-29 15:31:15 +00003025.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003026
3027MemoryHandler
3028^^^^^^^^^^^^^
3029
3030The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3031supports buffering of logging records in memory, periodically flushing them to a
3032:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3033event of a certain severity or greater is seen.
3034
3035:class:`MemoryHandler` is a subclass of the more general
3036:class:`BufferingHandler`, which is an abstract class. This buffers logging
3037records in memory. Whenever each record is added to the buffer, a check is made
3038by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3039should, then :meth:`flush` is expected to do the needful.
3040
3041
3042.. class:: BufferingHandler(capacity)
3043
3044 Initializes the handler with a buffer of the specified capacity.
3045
3046
Benjamin Petersone41251e2008-04-25 01:59:09 +00003047 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003048
Benjamin Petersone41251e2008-04-25 01:59:09 +00003049 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3050 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003051
3052
Benjamin Petersone41251e2008-04-25 01:59:09 +00003053 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003054
Benjamin Petersone41251e2008-04-25 01:59:09 +00003055 You can override this to implement custom flushing behavior. This version
3056 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003057
3058
Benjamin Petersone41251e2008-04-25 01:59:09 +00003059 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003060
Benjamin Petersone41251e2008-04-25 01:59:09 +00003061 Returns true if the buffer is up to capacity. This method can be
3062 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003063
3064
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003065.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003066
3067 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3068 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3069 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3070 set using :meth:`setTarget` before this handler does anything useful.
3071
3072
Benjamin Petersone41251e2008-04-25 01:59:09 +00003073 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003074
Benjamin Petersone41251e2008-04-25 01:59:09 +00003075 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3076 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003077
3078
Benjamin Petersone41251e2008-04-25 01:59:09 +00003079 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003080
Benjamin Petersone41251e2008-04-25 01:59:09 +00003081 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003082 records to the target, if there is one. The buffer is also cleared when
3083 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003084
3085
Benjamin Petersone41251e2008-04-25 01:59:09 +00003086 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003087
Benjamin Petersone41251e2008-04-25 01:59:09 +00003088 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003089
3090
Benjamin Petersone41251e2008-04-25 01:59:09 +00003091 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003092
Benjamin Petersone41251e2008-04-25 01:59:09 +00003093 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003094
3095
Vinay Sajipd31f3632010-06-29 15:31:15 +00003096.. _http-handler:
3097
Georg Brandl116aa622007-08-15 14:28:22 +00003098HTTPHandler
3099^^^^^^^^^^^
3100
3101The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3102supports sending logging messages to a Web server, using either ``GET`` or
3103``POST`` semantics.
3104
3105
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003106.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003107
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003108 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3109 of the form ``host:port``, should you need to use a specific port number.
3110 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3111 connection will be used. If *credentials* is specified, it should be a
3112 2-tuple consisting of userid and password, which will be placed in an HTTP
3113 'Authorization' header using Basic authentication. If you specify
3114 credentials, you should also specify secure=True so that your userid and
3115 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003116
3117
Benjamin Petersone41251e2008-04-25 01:59:09 +00003118 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003119
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003120 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003121
3122
Vinay Sajip121a1c42010-09-08 10:46:15 +00003123.. _queue-handler:
3124
3125
3126QueueHandler
3127^^^^^^^^^^^^
3128
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003129.. versionadded:: 3.2
3130
Vinay Sajip121a1c42010-09-08 10:46:15 +00003131The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3132supports sending logging messages to a queue, such as those implemented in the
3133:mod:`queue` or :mod:`multiprocessing` modules.
3134
Vinay Sajip0637d492010-09-23 08:15:54 +00003135Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3136to let handlers do their work on a separate thread from the one which does the
3137logging. This is important in Web applications and also other service
3138applications where threads servicing clients need to respond as quickly as
3139possible, while any potentially slow operations (such as sending an email via
3140:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003141
3142.. class:: QueueHandler(queue)
3143
3144 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003145 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003146 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003147 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003148
3149
3150 .. method:: emit(record)
3151
Vinay Sajip0258ce82010-09-22 20:34:53 +00003152 Enqueues the result of preparing the LogRecord.
3153
3154 .. method:: prepare(record)
3155
3156 Prepares a record for queuing. The object returned by this
3157 method is enqueued.
3158
3159 The base implementation formats the record to merge the message
3160 and arguments, and removes unpickleable items from the record
3161 in-place.
3162
3163 You might want to override this method if you want to convert
3164 the record to a dict or JSON string, or send a modified copy
3165 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003166
3167 .. method:: enqueue(record)
3168
3169 Enqueues the record on the queue using ``put_nowait()``; you may
3170 want to override this if you want to use blocking behaviour, or a
3171 timeout, or a customised queue implementation.
3172
3173
Vinay Sajip121a1c42010-09-08 10:46:15 +00003174
Vinay Sajip0637d492010-09-23 08:15:54 +00003175.. queue-listener:
3176
3177QueueListener
3178^^^^^^^^^^^^^
3179
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003180.. versionadded:: 3.2
3181
Vinay Sajip0637d492010-09-23 08:15:54 +00003182The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3183module, supports receiving logging messages from a queue, such as those
3184implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3185messages are received from a queue in an internal thread and passed, on
3186the same thread, to one or more handlers for processing.
3187
3188Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3189to let handlers do their work on a separate thread from the one which does the
3190logging. This is important in Web applications and also other service
3191applications where threads servicing clients need to respond as quickly as
3192possible, while any potentially slow operations (such as sending an email via
3193:class:`SMTPHandler`) are done on a separate thread.
3194
3195.. class:: QueueListener(queue, *handlers)
3196
3197 Returns a new instance of the :class:`QueueListener` class. The instance is
3198 initialized with the queue to send messages to and a list of handlers which
3199 will handle entries placed on the queue. The queue can be any queue-
3200 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3201 to know how to get messages from it.
3202
3203 .. method:: dequeue(block)
3204
3205 Dequeues a record and return it, optionally blocking.
3206
3207 The base implementation uses ``get()``. You may want to override this
3208 method if you want to use timeouts or work with custom queue
3209 implementations.
3210
3211 .. method:: prepare(record)
3212
3213 Prepare a record for handling.
3214
3215 This implementation just returns the passed-in record. You may want to
3216 override this method if you need to do any custom marshalling or
3217 manipulation of the record before passing it to the handlers.
3218
3219 .. method:: handle(record)
3220
3221 Handle a record.
3222
3223 This just loops through the handlers offering them the record
3224 to handle. The actual object passed to the handlers is that which
3225 is returned from :meth:`prepare`.
3226
3227 .. method:: start()
3228
3229 Starts the listener.
3230
3231 This starts up a background thread to monitor the queue for
3232 LogRecords to process.
3233
3234 .. method:: stop()
3235
3236 Stops the listener.
3237
3238 This asks the thread to terminate, and then waits for it to do so.
3239 Note that if you don't call this before your application exits, there
3240 may be some records still left on the queue, which won't be processed.
3241
Vinay Sajip0637d492010-09-23 08:15:54 +00003242
Vinay Sajip63891ed2010-09-13 20:02:39 +00003243.. _zeromq-handlers:
3244
Vinay Sajip0637d492010-09-23 08:15:54 +00003245Subclassing QueueHandler
3246^^^^^^^^^^^^^^^^^^^^^^^^
3247
Vinay Sajip63891ed2010-09-13 20:02:39 +00003248You can use a :class:`QueueHandler` subclass to send messages to other kinds
3249of queues, for example a ZeroMQ "publish" socket. In the example below,the
3250socket is created separately and passed to the handler (as its 'queue')::
3251
3252 import zmq # using pyzmq, the Python binding for ZeroMQ
3253 import json # for serializing records portably
3254
3255 ctx = zmq.Context()
3256 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3257 sock.bind('tcp://*:5556') # or wherever
3258
3259 class ZeroMQSocketHandler(QueueHandler):
3260 def enqueue(self, record):
3261 data = json.dumps(record.__dict__)
3262 self.queue.send(data)
3263
Vinay Sajip0055c422010-09-14 09:42:39 +00003264 handler = ZeroMQSocketHandler(sock)
3265
3266
Vinay Sajip63891ed2010-09-13 20:02:39 +00003267Of course there are other ways of organizing this, for example passing in the
3268data needed by the handler to create the socket::
3269
3270 class ZeroMQSocketHandler(QueueHandler):
3271 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3272 self.ctx = ctx or zmq.Context()
3273 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003274 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003275 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003276
3277 def enqueue(self, record):
3278 data = json.dumps(record.__dict__)
3279 self.queue.send(data)
3280
Vinay Sajipde726922010-09-14 06:59:24 +00003281 def close(self):
3282 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003283
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003284
Vinay Sajip0637d492010-09-23 08:15:54 +00003285Subclassing QueueListener
3286^^^^^^^^^^^^^^^^^^^^^^^^^
3287
3288You can also subclass :class:`QueueListener` to get messages from other kinds
3289of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
3290
3291 class ZeroMQSocketListener(QueueListener):
3292 def __init__(self, uri, *handlers, **kwargs):
3293 self.ctx = kwargs.get('ctx') or zmq.Context()
3294 socket = zmq.Socket(self.ctx, zmq.SUB)
3295 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3296 socket.connect(uri)
3297
3298 def dequeue(self):
3299 msg = self.queue.recv()
3300 return logging.makeLogRecord(json.loads(msg))
3301
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003302
Christian Heimes8b0facf2007-12-04 19:30:01 +00003303.. _formatter-objects:
3304
Georg Brandl116aa622007-08-15 14:28:22 +00003305Formatter Objects
3306-----------------
3307
Benjamin Peterson75edad02009-01-01 15:05:06 +00003308.. currentmodule:: logging
3309
Georg Brandl116aa622007-08-15 14:28:22 +00003310:class:`Formatter`\ s have the following attributes and methods. They are
3311responsible for converting a :class:`LogRecord` to (usually) a string which can
3312be interpreted by either a human or an external system. The base
3313:class:`Formatter` allows a formatting string to be specified. If none is
3314supplied, the default value of ``'%(message)s'`` is used.
3315
3316A Formatter can be initialized with a format string which makes use of knowledge
3317of the :class:`LogRecord` attributes - such as the default value mentioned above
3318making use of the fact that the user's message and arguments are pre-formatted
3319into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003320standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003321for more information on string formatting.
3322
3323Currently, the useful mapping keys in a :class:`LogRecord` are:
3324
3325+-------------------------+-----------------------------------------------+
3326| Format | Description |
3327+=========================+===============================================+
3328| ``%(name)s`` | Name of the logger (logging channel). |
3329+-------------------------+-----------------------------------------------+
3330| ``%(levelno)s`` | Numeric logging level for the message |
3331| | (:const:`DEBUG`, :const:`INFO`, |
3332| | :const:`WARNING`, :const:`ERROR`, |
3333| | :const:`CRITICAL`). |
3334+-------------------------+-----------------------------------------------+
3335| ``%(levelname)s`` | Text logging level for the message |
3336| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3337| | ``'ERROR'``, ``'CRITICAL'``). |
3338+-------------------------+-----------------------------------------------+
3339| ``%(pathname)s`` | Full pathname of the source file where the |
3340| | logging call was issued (if available). |
3341+-------------------------+-----------------------------------------------+
3342| ``%(filename)s`` | Filename portion of pathname. |
3343+-------------------------+-----------------------------------------------+
3344| ``%(module)s`` | Module (name portion of filename). |
3345+-------------------------+-----------------------------------------------+
3346| ``%(funcName)s`` | Name of function containing the logging call. |
3347+-------------------------+-----------------------------------------------+
3348| ``%(lineno)d`` | Source line number where the logging call was |
3349| | issued (if available). |
3350+-------------------------+-----------------------------------------------+
3351| ``%(created)f`` | Time when the :class:`LogRecord` was created |
3352| | (as returned by :func:`time.time`). |
3353+-------------------------+-----------------------------------------------+
3354| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3355| | created, relative to the time the logging |
3356| | module was loaded. |
3357+-------------------------+-----------------------------------------------+
3358| ``%(asctime)s`` | Human-readable time when the |
3359| | :class:`LogRecord` was created. By default |
3360| | this is of the form "2003-07-08 16:49:45,896" |
3361| | (the numbers after the comma are millisecond |
3362| | portion of the time). |
3363+-------------------------+-----------------------------------------------+
3364| ``%(msecs)d`` | Millisecond portion of the time when the |
3365| | :class:`LogRecord` was created. |
3366+-------------------------+-----------------------------------------------+
3367| ``%(thread)d`` | Thread ID (if available). |
3368+-------------------------+-----------------------------------------------+
3369| ``%(threadName)s`` | Thread name (if available). |
3370+-------------------------+-----------------------------------------------+
3371| ``%(process)d`` | Process ID (if available). |
3372+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003373| ``%(processName)s`` | Process name (if available). |
3374+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003375| ``%(message)s`` | The logged message, computed as ``msg % |
3376| | args``. |
3377+-------------------------+-----------------------------------------------+
3378
Georg Brandl116aa622007-08-15 14:28:22 +00003379
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003380.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003381
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003382 Returns a new instance of the :class:`Formatter` class. The instance is
3383 initialized with a format string for the message as a whole, as well as a
3384 format string for the date/time portion of a message. If no *fmt* is
3385 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3386 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003387
Benjamin Petersone41251e2008-04-25 01:59:09 +00003388 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003389
Benjamin Petersone41251e2008-04-25 01:59:09 +00003390 The record's attribute dictionary is used as the operand to a string
3391 formatting operation. Returns the resulting string. Before formatting the
3392 dictionary, a couple of preparatory steps are carried out. The *message*
3393 attribute of the record is computed using *msg* % *args*. If the
3394 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3395 to format the event time. If there is exception information, it is
3396 formatted using :meth:`formatException` and appended to the message. Note
3397 that the formatted exception information is cached in attribute
3398 *exc_text*. This is useful because the exception information can be
3399 pickled and sent across the wire, but you should be careful if you have
3400 more than one :class:`Formatter` subclass which customizes the formatting
3401 of exception information. In this case, you will have to clear the cached
3402 value after a formatter has done its formatting, so that the next
3403 formatter to handle the event doesn't use the cached value but
3404 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003405
Vinay Sajip8593ae62010-11-14 21:33:04 +00003406 If stack information is available, it's appended after the exception
3407 information, using :meth:`formatStack` to transform it if necessary.
3408
Georg Brandl116aa622007-08-15 14:28:22 +00003409
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003410 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003411
Benjamin Petersone41251e2008-04-25 01:59:09 +00003412 This method should be called from :meth:`format` by a formatter which
3413 wants to make use of a formatted time. This method can be overridden in
3414 formatters to provide for any specific requirement, but the basic behavior
3415 is as follows: if *datefmt* (a string) is specified, it is used with
3416 :func:`time.strftime` to format the creation time of the
3417 record. Otherwise, the ISO8601 format is used. The resulting string is
3418 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003419
3420
Benjamin Petersone41251e2008-04-25 01:59:09 +00003421 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003422
Benjamin Petersone41251e2008-04-25 01:59:09 +00003423 Formats the specified exception information (a standard exception tuple as
3424 returned by :func:`sys.exc_info`) as a string. This default implementation
3425 just uses :func:`traceback.print_exception`. The resulting string is
3426 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003427
Vinay Sajip8593ae62010-11-14 21:33:04 +00003428 .. method:: formatStack(stack_info)
3429
3430 Formats the specified stack information (a string as returned by
3431 :func:`traceback.print_stack`, but with the last newline removed) as a
3432 string. This default implementation just returns the input value.
3433
Vinay Sajipd31f3632010-06-29 15:31:15 +00003434.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003435
3436Filter Objects
3437--------------
3438
Georg Brandl5c66bca2010-10-29 05:36:28 +00003439``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003440filtering than is provided by levels. The base filter class only allows events
3441which are below a certain point in the logger hierarchy. For example, a filter
3442initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3443"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3444empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003445
3446
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003447.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003448
3449 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3450 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003451 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003452
3453
Benjamin Petersone41251e2008-04-25 01:59:09 +00003454 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003455
Benjamin Petersone41251e2008-04-25 01:59:09 +00003456 Is the specified record to be logged? Returns zero for no, nonzero for
3457 yes. If deemed appropriate, the record may be modified in-place by this
3458 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003459
Vinay Sajip81010212010-08-19 19:17:41 +00003460Note that filters attached to handlers are consulted whenever an event is
3461emitted by the handler, whereas filters attached to loggers are consulted
3462whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3463etc.) This means that events which have been generated by descendant loggers
3464will not be filtered by a logger's filter setting, unless the filter has also
3465been applied to those descendant loggers.
3466
Vinay Sajip22246fd2010-10-20 11:40:02 +00003467You don't actually need to subclass ``Filter``: you can pass any instance
3468which has a ``filter`` method with the same semantics.
3469
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003470.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003471 You don't need to create specialized ``Filter`` classes, or use other
3472 classes with a ``filter`` method: you can use a function (or other
3473 callable) as a filter. The filtering logic will check to see if the filter
3474 object has a ``filter`` attribute: if it does, it's assumed to be a
3475 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3476 assumed to be a callable and called with the record as the single
3477 parameter. The returned value should conform to that returned by
3478 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003479
Vinay Sajipac007992010-09-17 12:45:26 +00003480Other uses for filters
3481^^^^^^^^^^^^^^^^^^^^^^
3482
3483Although filters are used primarily to filter records based on more
3484sophisticated criteria than levels, they get to see every record which is
3485processed by the handler or logger they're attached to: this can be useful if
3486you want to do things like counting how many records were processed by a
3487particular logger or handler, or adding, changing or removing attributes in
3488the LogRecord being processed. Obviously changing the LogRecord needs to be
3489done with some care, but it does allow the injection of contextual information
3490into logs (see :ref:`filters-contextual`).
3491
Vinay Sajipd31f3632010-06-29 15:31:15 +00003492.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003493
3494LogRecord Objects
3495-----------------
3496
Vinay Sajip4039aff2010-09-11 10:25:28 +00003497:class:`LogRecord` instances are created automatically by the :class:`Logger`
3498every time something is logged, and can be created manually via
3499:func:`makeLogRecord` (for example, from a pickled event received over the
3500wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003501
3502
Vinay Sajipa18b9592010-12-12 13:20:55 +00003503.. class:: LogRecord(name, levelno, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003504
Vinay Sajip4039aff2010-09-11 10:25:28 +00003505 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003506
Vinay Sajip4039aff2010-09-11 10:25:28 +00003507 The primary information is passed in :attr:`msg` and :attr:`args`, which
3508 are combined using ``msg % args`` to create the :attr:`message` field of the
3509 record.
3510
3511 .. attribute:: args
3512
3513 Tuple of arguments to be used in formatting :attr:`msg`.
3514
3515 .. attribute:: exc_info
3516
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003517 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003518 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003519
3520 .. attribute:: func
3521
3522 Name of the function of origin (i.e. in which the logging call was made).
3523
3524 .. attribute:: lineno
3525
3526 Line number in the source file of origin.
3527
Vinay Sajipa18b9592010-12-12 13:20:55 +00003528 .. attribute:: levelno
Vinay Sajip4039aff2010-09-11 10:25:28 +00003529
3530 Numeric logging level.
3531
3532 .. attribute:: message
3533
3534 Bound to the result of :meth:`getMessage` when
3535 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3536
3537 .. attribute:: msg
3538
3539 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3540 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3541
3542 .. attribute:: name
3543
3544 Name of the logger that emitted the record.
3545
3546 .. attribute:: pathname
3547
3548 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003549
Vinay Sajip8593ae62010-11-14 21:33:04 +00003550 .. attribute:: stack_info
3551
3552 Stack frame information (where available) from the bottom of the stack
3553 in the current thread, up to and including the stack frame of the
3554 logging call which resulted in the creation of this record.
3555
Benjamin Petersone41251e2008-04-25 01:59:09 +00003556 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003557
Benjamin Petersone41251e2008-04-25 01:59:09 +00003558 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003559 user-supplied arguments with the message. If the user-supplied message
3560 argument to the logging call is not a string, :func:`str` is called on it to
3561 convert it to a string. This allows use of user-defined classes as
3562 messages, whose ``__str__`` method can return the actual format string to
3563 be used.
3564
Vinay Sajip61561522010-12-03 11:50:38 +00003565 .. versionchanged:: 3.2
3566 The creation of a ``LogRecord`` has been made more configurable by
3567 providing a factory which is used to create the record. The factory can be
3568 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3569 (see this for the factory's signature).
3570
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003571 This functionality can be used to inject your own values into a
3572 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003573
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003574 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003575
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003576 def record_factory(*args, **kwargs):
3577 record = old_factory(*args, **kwargs)
3578 record.custom_attribute = 0xdecafbad
3579 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003580
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003581 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003582
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003583 With this pattern, multiple factories could be chained, and as long
3584 as they don't overwrite each other's attributes or unintentionally
3585 overwrite the standard attributes listed above, there should be no
3586 surprises.
3587
Vinay Sajip61561522010-12-03 11:50:38 +00003588
Vinay Sajipd31f3632010-06-29 15:31:15 +00003589.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003590
Christian Heimes04c420f2008-01-18 18:40:46 +00003591LoggerAdapter Objects
3592---------------------
3593
Christian Heimes04c420f2008-01-18 18:40:46 +00003594:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003595information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003596:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003597
Christian Heimes04c420f2008-01-18 18:40:46 +00003598
3599.. class:: LoggerAdapter(logger, extra)
3600
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003601 Returns an instance of :class:`LoggerAdapter` initialized with an
3602 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003603
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003604 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003605
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003606 Modifies the message and/or keyword arguments passed to a logging call in
3607 order to insert contextual information. This implementation takes the object
3608 passed as *extra* to the constructor and adds it to *kwargs* using key
3609 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3610 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003611
Vinay Sajipc84f0162010-09-21 11:25:39 +00003612In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003613methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003614:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3615:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3616:meth:`hasHandlers`. These methods have the same signatures as their
3617counterparts in :class:`Logger`, so you can use the two types of instances
3618interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003619
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003620.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003621 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3622 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3623 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003624
Georg Brandl116aa622007-08-15 14:28:22 +00003625
3626Thread Safety
3627-------------
3628
3629The logging module is intended to be thread-safe without any special work
3630needing to be done by its clients. It achieves this though using threading
3631locks; there is one lock to serialize access to the module's shared data, and
3632each handler also creates a lock to serialize access to its underlying I/O.
3633
Benjamin Petersond23f8222009-04-05 19:13:16 +00003634If you are implementing asynchronous signal handlers using the :mod:`signal`
3635module, you may not be able to use logging from within such handlers. This is
3636because lock implementations in the :mod:`threading` module are not always
3637re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003638
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003639
3640Integration with the warnings module
3641------------------------------------
3642
3643The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3644with the :mod:`warnings` module.
3645
3646.. function:: captureWarnings(capture)
3647
3648 This function is used to turn the capture of warnings by logging on and
3649 off.
3650
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003651 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3652 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003653 formatted using :func:`warnings.formatwarning` and the resulting string
3654 logged to a logger named "py.warnings" with a severity of `WARNING`.
3655
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003656 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003657 will stop, and warnings will be redirected to their original destinations
3658 (i.e. those in effect before `captureWarnings(True)` was called).
3659
3660
Georg Brandl116aa622007-08-15 14:28:22 +00003661Configuration
3662-------------
3663
3664
3665.. _logging-config-api:
3666
3667Configuration functions
3668^^^^^^^^^^^^^^^^^^^^^^^
3669
Georg Brandl116aa622007-08-15 14:28:22 +00003670The following functions configure the logging module. They are located in the
3671:mod:`logging.config` module. Their use is optional --- you can configure the
3672logging module using these functions or by making calls to the main API (defined
3673in :mod:`logging` itself) and defining handlers which are declared either in
3674:mod:`logging` or :mod:`logging.handlers`.
3675
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003676.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003677
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003678 Takes the logging configuration from a dictionary. The contents of
3679 this dictionary are described in :ref:`logging-config-dictschema`
3680 below.
3681
3682 If an error is encountered during configuration, this function will
3683 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3684 or :exc:`ImportError` with a suitably descriptive message. The
3685 following is a (possibly incomplete) list of conditions which will
3686 raise an error:
3687
3688 * A ``level`` which is not a string or which is a string not
3689 corresponding to an actual logging level.
3690 * A ``propagate`` value which is not a boolean.
3691 * An id which does not have a corresponding destination.
3692 * A non-existent handler id found during an incremental call.
3693 * An invalid logger name.
3694 * Inability to resolve to an internal or external object.
3695
3696 Parsing is performed by the :class:`DictConfigurator` class, whose
3697 constructor is passed the dictionary used for configuration, and
3698 has a :meth:`configure` method. The :mod:`logging.config` module
3699 has a callable attribute :attr:`dictConfigClass`
3700 which is initially set to :class:`DictConfigurator`.
3701 You can replace the value of :attr:`dictConfigClass` with a
3702 suitable implementation of your own.
3703
3704 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3705 the specified dictionary, and then calls the :meth:`configure` method on
3706 the returned object to put the configuration into effect::
3707
3708 def dictConfig(config):
3709 dictConfigClass(config).configure()
3710
3711 For example, a subclass of :class:`DictConfigurator` could call
3712 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3713 set up custom prefixes which would be usable in the subsequent
3714 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3715 this new subclass, and then :func:`dictConfig` could be called exactly as
3716 in the default, uncustomized state.
3717
3718.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003719
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003720 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003721 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003722 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003723 configurations (if the developer provides a mechanism to present the choices
3724 and load the chosen configuration). Defaults to be passed to the ConfigParser
3725 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003726
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003727
3728.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003729
3730 Starts up a socket server on the specified port, and listens for new
3731 configurations. If no port is specified, the module's default
3732 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3733 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3734 :class:`Thread` instance on which you can call :meth:`start` to start the
3735 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003736 call :func:`stopListening`.
3737
3738 To send a configuration to the socket, read in the configuration file and
3739 send it to the socket as a string of bytes preceded by a four-byte length
3740 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003741
3742
3743.. function:: stopListening()
3744
Christian Heimes8b0facf2007-12-04 19:30:01 +00003745 Stops the listening server which was created with a call to :func:`listen`.
3746 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003747 :func:`listen`.
3748
3749
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003750.. _logging-config-dictschema:
3751
3752Configuration dictionary schema
3753^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3754
3755Describing a logging configuration requires listing the various
3756objects to create and the connections between them; for example, you
3757may create a handler named "console" and then say that the logger
3758named "startup" will send its messages to the "console" handler.
3759These objects aren't limited to those provided by the :mod:`logging`
3760module because you might write your own formatter or handler class.
3761The parameters to these classes may also need to include external
3762objects such as ``sys.stderr``. The syntax for describing these
3763objects and connections is defined in :ref:`logging-config-dict-connections`
3764below.
3765
3766Dictionary Schema Details
3767"""""""""""""""""""""""""
3768
3769The dictionary passed to :func:`dictConfig` must contain the following
3770keys:
3771
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003772* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003773 version. The only valid value at present is 1, but having this key
3774 allows the schema to evolve while still preserving backwards
3775 compatibility.
3776
3777All other keys are optional, but if present they will be interpreted
3778as described below. In all cases below where a 'configuring dict' is
3779mentioned, it will be checked for the special ``'()'`` key to see if a
3780custom instantiation is required. If so, the mechanism described in
3781:ref:`logging-config-dict-userdef` below is used to create an instance;
3782otherwise, the context is used to determine what to instantiate.
3783
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003784* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003785 key is a formatter id and each value is a dict describing how to
3786 configure the corresponding Formatter instance.
3787
3788 The configuring dict is searched for keys ``format`` and ``datefmt``
3789 (with defaults of ``None``) and these are used to construct a
3790 :class:`logging.Formatter` instance.
3791
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003792* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003793 is a filter id and each value is a dict describing how to configure
3794 the corresponding Filter instance.
3795
3796 The configuring dict is searched for the key ``name`` (defaulting to the
3797 empty string) and this is used to construct a :class:`logging.Filter`
3798 instance.
3799
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003800* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003801 key is a handler id and each value is a dict describing how to
3802 configure the corresponding Handler instance.
3803
3804 The configuring dict is searched for the following keys:
3805
3806 * ``class`` (mandatory). This is the fully qualified name of the
3807 handler class.
3808
3809 * ``level`` (optional). The level of the handler.
3810
3811 * ``formatter`` (optional). The id of the formatter for this
3812 handler.
3813
3814 * ``filters`` (optional). A list of ids of the filters for this
3815 handler.
3816
3817 All *other* keys are passed through as keyword arguments to the
3818 handler's constructor. For example, given the snippet::
3819
3820 handlers:
3821 console:
3822 class : logging.StreamHandler
3823 formatter: brief
3824 level : INFO
3825 filters: [allow_foo]
3826 stream : ext://sys.stdout
3827 file:
3828 class : logging.handlers.RotatingFileHandler
3829 formatter: precise
3830 filename: logconfig.log
3831 maxBytes: 1024
3832 backupCount: 3
3833
3834 the handler with id ``console`` is instantiated as a
3835 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3836 stream. The handler with id ``file`` is instantiated as a
3837 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3838 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3839
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003840* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003841 is a logger name and each value is a dict describing how to
3842 configure the corresponding Logger instance.
3843
3844 The configuring dict is searched for the following keys:
3845
3846 * ``level`` (optional). The level of the logger.
3847
3848 * ``propagate`` (optional). The propagation setting of the logger.
3849
3850 * ``filters`` (optional). A list of ids of the filters for this
3851 logger.
3852
3853 * ``handlers`` (optional). A list of ids of the handlers for this
3854 logger.
3855
3856 The specified loggers will be configured according to the level,
3857 propagation, filters and handlers specified.
3858
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003859* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003860 Processing of the configuration will be as for any logger, except
3861 that the ``propagate`` setting will not be applicable.
3862
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003863* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003864 incremental to the existing configuration. This value defaults to
3865 ``False``, which means that the specified configuration replaces the
3866 existing configuration with the same semantics as used by the
3867 existing :func:`fileConfig` API.
3868
3869 If the specified value is ``True``, the configuration is processed
3870 as described in the section on :ref:`logging-config-dict-incremental`.
3871
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003872* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003873 disabled. This setting mirrors the parameter of the same name in
3874 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003875 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003876
3877.. _logging-config-dict-incremental:
3878
3879Incremental Configuration
3880"""""""""""""""""""""""""
3881
3882It is difficult to provide complete flexibility for incremental
3883configuration. For example, because objects such as filters
3884and formatters are anonymous, once a configuration is set up, it is
3885not possible to refer to such anonymous objects when augmenting a
3886configuration.
3887
3888Furthermore, there is not a compelling case for arbitrarily altering
3889the object graph of loggers, handlers, filters, formatters at
3890run-time, once a configuration is set up; the verbosity of loggers and
3891handlers can be controlled just by setting levels (and, in the case of
3892loggers, propagation flags). Changing the object graph arbitrarily in
3893a safe way is problematic in a multi-threaded environment; while not
3894impossible, the benefits are not worth the complexity it adds to the
3895implementation.
3896
3897Thus, when the ``incremental`` key of a configuration dict is present
3898and is ``True``, the system will completely ignore any ``formatters`` and
3899``filters`` entries, and process only the ``level``
3900settings in the ``handlers`` entries, and the ``level`` and
3901``propagate`` settings in the ``loggers`` and ``root`` entries.
3902
3903Using a value in the configuration dict lets configurations to be sent
3904over the wire as pickled dicts to a socket listener. Thus, the logging
3905verbosity of a long-running application can be altered over time with
3906no need to stop and restart the application.
3907
3908.. _logging-config-dict-connections:
3909
3910Object connections
3911""""""""""""""""""
3912
3913The schema describes a set of logging objects - loggers,
3914handlers, formatters, filters - which are connected to each other in
3915an object graph. Thus, the schema needs to represent connections
3916between the objects. For example, say that, once configured, a
3917particular logger has attached to it a particular handler. For the
3918purposes of this discussion, we can say that the logger represents the
3919source, and the handler the destination, of a connection between the
3920two. Of course in the configured objects this is represented by the
3921logger holding a reference to the handler. In the configuration dict,
3922this is done by giving each destination object an id which identifies
3923it unambiguously, and then using the id in the source object's
3924configuration to indicate that a connection exists between the source
3925and the destination object with that id.
3926
3927So, for example, consider the following YAML snippet::
3928
3929 formatters:
3930 brief:
3931 # configuration for formatter with id 'brief' goes here
3932 precise:
3933 # configuration for formatter with id 'precise' goes here
3934 handlers:
3935 h1: #This is an id
3936 # configuration of handler with id 'h1' goes here
3937 formatter: brief
3938 h2: #This is another id
3939 # configuration of handler with id 'h2' goes here
3940 formatter: precise
3941 loggers:
3942 foo.bar.baz:
3943 # other configuration for logger 'foo.bar.baz'
3944 handlers: [h1, h2]
3945
3946(Note: YAML used here because it's a little more readable than the
3947equivalent Python source form for the dictionary.)
3948
3949The ids for loggers are the logger names which would be used
3950programmatically to obtain a reference to those loggers, e.g.
3951``foo.bar.baz``. The ids for Formatters and Filters can be any string
3952value (such as ``brief``, ``precise`` above) and they are transient,
3953in that they are only meaningful for processing the configuration
3954dictionary and used to determine connections between objects, and are
3955not persisted anywhere when the configuration call is complete.
3956
3957The above snippet indicates that logger named ``foo.bar.baz`` should
3958have two handlers attached to it, which are described by the handler
3959ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3960``brief``, and the formatter for ``h2`` is that described by id
3961``precise``.
3962
3963
3964.. _logging-config-dict-userdef:
3965
3966User-defined objects
3967""""""""""""""""""""
3968
3969The schema supports user-defined objects for handlers, filters and
3970formatters. (Loggers do not need to have different types for
3971different instances, so there is no support in this configuration
3972schema for user-defined logger classes.)
3973
3974Objects to be configured are described by dictionaries
3975which detail their configuration. In some places, the logging system
3976will be able to infer from the context how an object is to be
3977instantiated, but when a user-defined object is to be instantiated,
3978the system will not know how to do this. In order to provide complete
3979flexibility for user-defined object instantiation, the user needs
3980to provide a 'factory' - a callable which is called with a
3981configuration dictionary and which returns the instantiated object.
3982This is signalled by an absolute import path to the factory being
3983made available under the special key ``'()'``. Here's a concrete
3984example::
3985
3986 formatters:
3987 brief:
3988 format: '%(message)s'
3989 default:
3990 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3991 datefmt: '%Y-%m-%d %H:%M:%S'
3992 custom:
3993 (): my.package.customFormatterFactory
3994 bar: baz
3995 spam: 99.9
3996 answer: 42
3997
3998The above YAML snippet defines three formatters. The first, with id
3999``brief``, is a standard :class:`logging.Formatter` instance with the
4000specified format string. The second, with id ``default``, has a
4001longer format and also defines the time format explicitly, and will
4002result in a :class:`logging.Formatter` initialized with those two format
4003strings. Shown in Python source form, the ``brief`` and ``default``
4004formatters have configuration sub-dictionaries::
4005
4006 {
4007 'format' : '%(message)s'
4008 }
4009
4010and::
4011
4012 {
4013 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4014 'datefmt' : '%Y-%m-%d %H:%M:%S'
4015 }
4016
4017respectively, and as these dictionaries do not contain the special key
4018``'()'``, the instantiation is inferred from the context: as a result,
4019standard :class:`logging.Formatter` instances are created. The
4020configuration sub-dictionary for the third formatter, with id
4021``custom``, is::
4022
4023 {
4024 '()' : 'my.package.customFormatterFactory',
4025 'bar' : 'baz',
4026 'spam' : 99.9,
4027 'answer' : 42
4028 }
4029
4030and this contains the special key ``'()'``, which means that
4031user-defined instantiation is wanted. In this case, the specified
4032factory callable will be used. If it is an actual callable it will be
4033used directly - otherwise, if you specify a string (as in the example)
4034the actual callable will be located using normal import mechanisms.
4035The callable will be called with the **remaining** items in the
4036configuration sub-dictionary as keyword arguments. In the above
4037example, the formatter with id ``custom`` will be assumed to be
4038returned by the call::
4039
4040 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4041
4042The key ``'()'`` has been used as the special key because it is not a
4043valid keyword parameter name, and so will not clash with the names of
4044the keyword arguments used in the call. The ``'()'`` also serves as a
4045mnemonic that the corresponding value is a callable.
4046
4047
4048.. _logging-config-dict-externalobj:
4049
4050Access to external objects
4051""""""""""""""""""""""""""
4052
4053There are times where a configuration needs to refer to objects
4054external to the configuration, for example ``sys.stderr``. If the
4055configuration dict is constructed using Python code, this is
4056straightforward, but a problem arises when the configuration is
4057provided via a text file (e.g. JSON, YAML). In a text file, there is
4058no standard way to distinguish ``sys.stderr`` from the literal string
4059``'sys.stderr'``. To facilitate this distinction, the configuration
4060system looks for certain special prefixes in string values and
4061treat them specially. For example, if the literal string
4062``'ext://sys.stderr'`` is provided as a value in the configuration,
4063then the ``ext://`` will be stripped off and the remainder of the
4064value processed using normal import mechanisms.
4065
4066The handling of such prefixes is done in a way analogous to protocol
4067handling: there is a generic mechanism to look for prefixes which
4068match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4069whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4070in a prefix-dependent manner and the result of the processing replaces
4071the string value. If the prefix is not recognised, then the string
4072value will be left as-is.
4073
4074
4075.. _logging-config-dict-internalobj:
4076
4077Access to internal objects
4078""""""""""""""""""""""""""
4079
4080As well as external objects, there is sometimes also a need to refer
4081to objects in the configuration. This will be done implicitly by the
4082configuration system for things that it knows about. For example, the
4083string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4084automatically be converted to the value ``logging.DEBUG``, and the
4085``handlers``, ``filters`` and ``formatter`` entries will take an
4086object id and resolve to the appropriate destination object.
4087
4088However, a more generic mechanism is needed for user-defined
4089objects which are not known to the :mod:`logging` module. For
4090example, consider :class:`logging.handlers.MemoryHandler`, which takes
4091a ``target`` argument which is another handler to delegate to. Since
4092the system already knows about this class, then in the configuration,
4093the given ``target`` just needs to be the object id of the relevant
4094target handler, and the system will resolve to the handler from the
4095id. If, however, a user defines a ``my.package.MyHandler`` which has
4096an ``alternate`` handler, the configuration system would not know that
4097the ``alternate`` referred to a handler. To cater for this, a generic
4098resolution system allows the user to specify::
4099
4100 handlers:
4101 file:
4102 # configuration of file handler goes here
4103
4104 custom:
4105 (): my.package.MyHandler
4106 alternate: cfg://handlers.file
4107
4108The literal string ``'cfg://handlers.file'`` will be resolved in an
4109analogous way to strings with the ``ext://`` prefix, but looking
4110in the configuration itself rather than the import namespace. The
4111mechanism allows access by dot or by index, in a similar way to
4112that provided by ``str.format``. Thus, given the following snippet::
4113
4114 handlers:
4115 email:
4116 class: logging.handlers.SMTPHandler
4117 mailhost: localhost
4118 fromaddr: my_app@domain.tld
4119 toaddrs:
4120 - support_team@domain.tld
4121 - dev_team@domain.tld
4122 subject: Houston, we have a problem.
4123
4124in the configuration, the string ``'cfg://handlers'`` would resolve to
4125the dict with key ``handlers``, the string ``'cfg://handlers.email``
4126would resolve to the dict with key ``email`` in the ``handlers`` dict,
4127and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4128resolve to ``'dev_team.domain.tld'`` and the string
4129``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4130``'support_team@domain.tld'``. The ``subject`` value could be accessed
4131using either ``'cfg://handlers.email.subject'`` or, equivalently,
4132``'cfg://handlers.email[subject]'``. The latter form only needs to be
4133used if the key contains spaces or non-alphanumeric characters. If an
4134index value consists only of decimal digits, access will be attempted
4135using the corresponding integer value, falling back to the string
4136value if needed.
4137
4138Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4139resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4140If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4141the system will attempt to retrieve the value from
4142``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4143to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4144fails.
4145
Georg Brandl116aa622007-08-15 14:28:22 +00004146.. _logging-config-fileformat:
4147
4148Configuration file format
4149^^^^^^^^^^^^^^^^^^^^^^^^^
4150
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004151The configuration file format understood by :func:`fileConfig` is based on
4152:mod:`configparser` functionality. The file must contain sections called
4153``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4154entities of each type which are defined in the file. For each such entity, there
4155is a separate section which identifies how that entity is configured. Thus, for
4156a logger named ``log01`` in the ``[loggers]`` section, the relevant
4157configuration details are held in a section ``[logger_log01]``. Similarly, a
4158handler called ``hand01`` in the ``[handlers]`` section will have its
4159configuration held in a section called ``[handler_hand01]``, while a formatter
4160called ``form01`` in the ``[formatters]`` section will have its configuration
4161specified in a section called ``[formatter_form01]``. The root logger
4162configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004163
4164Examples of these sections in the file are given below. ::
4165
4166 [loggers]
4167 keys=root,log02,log03,log04,log05,log06,log07
4168
4169 [handlers]
4170 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4171
4172 [formatters]
4173 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4174
4175The root logger must specify a level and a list of handlers. An example of a
4176root logger section is given below. ::
4177
4178 [logger_root]
4179 level=NOTSET
4180 handlers=hand01
4181
4182The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4183``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4184logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4185package's namespace.
4186
4187The ``handlers`` entry is a comma-separated list of handler names, which must
4188appear in the ``[handlers]`` section. These names must appear in the
4189``[handlers]`` section and have corresponding sections in the configuration
4190file.
4191
4192For loggers other than the root logger, some additional information is required.
4193This is illustrated by the following example. ::
4194
4195 [logger_parser]
4196 level=DEBUG
4197 handlers=hand01
4198 propagate=1
4199 qualname=compiler.parser
4200
4201The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4202except that if a non-root logger's level is specified as ``NOTSET``, the system
4203consults loggers higher up the hierarchy to determine the effective level of the
4204logger. The ``propagate`` entry is set to 1 to indicate that messages must
4205propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4206indicate that messages are **not** propagated to handlers up the hierarchy. The
4207``qualname`` entry is the hierarchical channel name of the logger, that is to
4208say the name used by the application to get the logger.
4209
4210Sections which specify handler configuration are exemplified by the following.
4211::
4212
4213 [handler_hand01]
4214 class=StreamHandler
4215 level=NOTSET
4216 formatter=form01
4217 args=(sys.stdout,)
4218
4219The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4220in the ``logging`` package's namespace). The ``level`` is interpreted as for
4221loggers, and ``NOTSET`` is taken to mean "log everything".
4222
4223The ``formatter`` entry indicates the key name of the formatter for this
4224handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4225If a name is specified, it must appear in the ``[formatters]`` section and have
4226a corresponding section in the configuration file.
4227
4228The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4229package's namespace, is the list of arguments to the constructor for the handler
4230class. Refer to the constructors for the relevant handlers, or to the examples
4231below, to see how typical entries are constructed. ::
4232
4233 [handler_hand02]
4234 class=FileHandler
4235 level=DEBUG
4236 formatter=form02
4237 args=('python.log', 'w')
4238
4239 [handler_hand03]
4240 class=handlers.SocketHandler
4241 level=INFO
4242 formatter=form03
4243 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4244
4245 [handler_hand04]
4246 class=handlers.DatagramHandler
4247 level=WARN
4248 formatter=form04
4249 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4250
4251 [handler_hand05]
4252 class=handlers.SysLogHandler
4253 level=ERROR
4254 formatter=form05
4255 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4256
4257 [handler_hand06]
4258 class=handlers.NTEventLogHandler
4259 level=CRITICAL
4260 formatter=form06
4261 args=('Python Application', '', 'Application')
4262
4263 [handler_hand07]
4264 class=handlers.SMTPHandler
4265 level=WARN
4266 formatter=form07
4267 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4268
4269 [handler_hand08]
4270 class=handlers.MemoryHandler
4271 level=NOTSET
4272 formatter=form08
4273 target=
4274 args=(10, ERROR)
4275
4276 [handler_hand09]
4277 class=handlers.HTTPHandler
4278 level=NOTSET
4279 formatter=form09
4280 args=('localhost:9022', '/log', 'GET')
4281
4282Sections which specify formatter configuration are typified by the following. ::
4283
4284 [formatter_form01]
4285 format=F1 %(asctime)s %(levelname)s %(message)s
4286 datefmt=
4287 class=logging.Formatter
4288
4289The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004290the :func:`strftime`\ -compatible date/time format string. If empty, the
4291package substitutes ISO8601 format date/times, which is almost equivalent to
4292specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
4293also specifies milliseconds, which are appended to the result of using the above
4294format string, with a comma separator. An example time in ISO8601 format is
4295``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004296
4297The ``class`` entry is optional. It indicates the name of the formatter's class
4298(as a dotted module and class name.) This option is useful for instantiating a
4299:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4300exception tracebacks in an expanded or condensed format.
4301
Christian Heimes8b0facf2007-12-04 19:30:01 +00004302
4303Configuration server example
4304^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4305
4306Here is an example of a module using the logging configuration server::
4307
4308 import logging
4309 import logging.config
4310 import time
4311 import os
4312
4313 # read initial config file
4314 logging.config.fileConfig("logging.conf")
4315
4316 # create and start listener on port 9999
4317 t = logging.config.listen(9999)
4318 t.start()
4319
4320 logger = logging.getLogger("simpleExample")
4321
4322 try:
4323 # loop through logging calls to see the difference
4324 # new configurations make, until Ctrl+C is pressed
4325 while True:
4326 logger.debug("debug message")
4327 logger.info("info message")
4328 logger.warn("warn message")
4329 logger.error("error message")
4330 logger.critical("critical message")
4331 time.sleep(5)
4332 except KeyboardInterrupt:
4333 # cleanup
4334 logging.config.stopListening()
4335 t.join()
4336
4337And here is a script that takes a filename and sends that file to the server,
4338properly preceded with the binary-encoded length, as the new logging
4339configuration::
4340
4341 #!/usr/bin/env python
4342 import socket, sys, struct
4343
4344 data_to_send = open(sys.argv[1], "r").read()
4345
4346 HOST = 'localhost'
4347 PORT = 9999
4348 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00004349 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004350 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00004351 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004352 s.send(struct.pack(">L", len(data_to_send)))
4353 s.send(data_to_send)
4354 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00004355 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004356
4357
4358More examples
4359-------------
4360
4361Multiple handlers and formatters
4362^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4363
4364Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4365or maximum quota for the number of handlers you may add. Sometimes it will be
4366beneficial for an application to log all messages of all severities to a text
4367file while simultaneously logging errors or above to the console. To set this
4368up, simply configure the appropriate handlers. The logging calls in the
4369application code will remain unchanged. Here is a slight modification to the
4370previous simple module-based configuration example::
4371
4372 import logging
4373
4374 logger = logging.getLogger("simple_example")
4375 logger.setLevel(logging.DEBUG)
4376 # create file handler which logs even debug messages
4377 fh = logging.FileHandler("spam.log")
4378 fh.setLevel(logging.DEBUG)
4379 # create console handler with a higher log level
4380 ch = logging.StreamHandler()
4381 ch.setLevel(logging.ERROR)
4382 # create formatter and add it to the handlers
4383 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4384 ch.setFormatter(formatter)
4385 fh.setFormatter(formatter)
4386 # add the handlers to logger
4387 logger.addHandler(ch)
4388 logger.addHandler(fh)
4389
4390 # "application" code
4391 logger.debug("debug message")
4392 logger.info("info message")
4393 logger.warn("warn message")
4394 logger.error("error message")
4395 logger.critical("critical message")
4396
4397Notice that the "application" code does not care about multiple handlers. All
4398that changed was the addition and configuration of a new handler named *fh*.
4399
4400The ability to create new handlers with higher- or lower-severity filters can be
4401very helpful when writing and testing an application. Instead of using many
4402``print`` statements for debugging, use ``logger.debug``: Unlike the print
4403statements, which you will have to delete or comment out later, the logger.debug
4404statements can remain intact in the source code and remain dormant until you
4405need them again. At that time, the only change that needs to happen is to
4406modify the severity level of the logger and/or handler to debug.
4407
4408
4409Using logging in multiple modules
4410^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4411
4412It was mentioned above that multiple calls to
4413``logging.getLogger('someLogger')`` return a reference to the same logger
4414object. This is true not only within the same module, but also across modules
4415as long as it is in the same Python interpreter process. It is true for
4416references to the same object; additionally, application code can define and
4417configure a parent logger in one module and create (but not configure) a child
4418logger in a separate module, and all logger calls to the child will pass up to
4419the parent. Here is a main module::
4420
4421 import logging
4422 import auxiliary_module
4423
4424 # create logger with "spam_application"
4425 logger = logging.getLogger("spam_application")
4426 logger.setLevel(logging.DEBUG)
4427 # create file handler which logs even debug messages
4428 fh = logging.FileHandler("spam.log")
4429 fh.setLevel(logging.DEBUG)
4430 # create console handler with a higher log level
4431 ch = logging.StreamHandler()
4432 ch.setLevel(logging.ERROR)
4433 # create formatter and add it to the handlers
4434 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4435 fh.setFormatter(formatter)
4436 ch.setFormatter(formatter)
4437 # add the handlers to the logger
4438 logger.addHandler(fh)
4439 logger.addHandler(ch)
4440
4441 logger.info("creating an instance of auxiliary_module.Auxiliary")
4442 a = auxiliary_module.Auxiliary()
4443 logger.info("created an instance of auxiliary_module.Auxiliary")
4444 logger.info("calling auxiliary_module.Auxiliary.do_something")
4445 a.do_something()
4446 logger.info("finished auxiliary_module.Auxiliary.do_something")
4447 logger.info("calling auxiliary_module.some_function()")
4448 auxiliary_module.some_function()
4449 logger.info("done with auxiliary_module.some_function()")
4450
4451Here is the auxiliary module::
4452
4453 import logging
4454
4455 # create logger
4456 module_logger = logging.getLogger("spam_application.auxiliary")
4457
4458 class Auxiliary:
4459 def __init__(self):
4460 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4461 self.logger.info("creating an instance of Auxiliary")
4462 def do_something(self):
4463 self.logger.info("doing something")
4464 a = 1 + 1
4465 self.logger.info("done doing something")
4466
4467 def some_function():
4468 module_logger.info("received a call to \"some_function\"")
4469
4470The output looks like this::
4471
Christian Heimes043d6f62008-01-07 17:19:16 +00004472 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004473 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004474 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004475 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004476 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004477 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004478 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004479 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004480 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004481 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004482 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004483 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004484 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004485 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004486 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004487 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004488 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004489 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004490 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004491 done with auxiliary_module.some_function()
4492