blob: 29854a40f02d06843be452d39b467e2de105e39d [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 Sajipa18b9592010-12-12 13:20:55 +0000322The root of the hierarchy of loggers is called the root logger. That's the
323logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
324:func:`error` and :func:`critical`, which just call the same-named method of
325the root logger. The functions and the methods have the same signatures. The
326root logger's name is printed as 'root' in the logged output.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Vinay Sajipa18b9592010-12-12 13:20:55 +0000328It is, of course, possible to log messages to different destinations. Support
329for writing log messages to files, HTTP GET/POST locations, email via SMTP,
330generic sockets, or OS-specific logging mechanisms is included in the package.
331Destinations are served by :dfn:`handler` classes. You can create your own log
Vinay Sajipdfa0a2a2010-12-10 08:17:05 +0000332destination class if you have special requirements not met by any of the
Vinay Sajipa18b9592010-12-12 13:20:55 +0000333built-in handler classes.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000334
Vinay Sajipa18b9592010-12-12 13:20:55 +0000335By default, no destination is set for any logging messages. You can specify
336a destination (such as console or file) by using :func:`basicConfig` as in the
337tutorial examples. If you call the functions :func:`debug`, :func:`info`,
338:func:`warning`, :func:`error` and :func:`critical`, they will check to see
339if no destination is set; and if one is not set, they will set a destination
340of the console (``sys.stderr``) and a default format for the displayed
341message before delegating to the root logger to do the actual message output.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000342
Vinay Sajipa18b9592010-12-12 13:20:55 +0000343The default format set by :func:`basicConfig` for messages is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000344
Vinay Sajipa18b9592010-12-12 13:20:55 +0000345 severity:logger name:message
Christian Heimes8b0facf2007-12-04 19:30:01 +0000346
Vinay Sajipa18b9592010-12-12 13:20:55 +0000347You can change this by passing a format string to :func:`basicConfig` with the
348*format* keyword argument. For all options regarding how a format string is
349constructed, see :ref:`formatter-objects`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000350
Christian Heimes8b0facf2007-12-04 19:30:01 +0000351
352Loggers
353^^^^^^^
354
Christian Heimes8b0facf2007-12-04 19:30:01 +0000355:class:`Logger` objects have a threefold job. First, they expose several
356methods to application code so that applications can log messages at runtime.
357Second, logger objects determine which log messages to act upon based upon
358severity (the default filtering facility) or filter objects. Third, logger
359objects pass along relevant log messages to all interested log handlers.
360
361The most widely used methods on logger objects fall into two categories:
362configuration and message sending.
363
364* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
365 will handle, where debug is the lowest built-in severity level and critical is
366 the highest built-in severity. For example, if the severity level is info,
367 the logger will handle only info, warning, error, and critical messages and
368 will ignore debug messages.
369
370* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
371 objects from the logger object. This tutorial does not address filters.
372
373With the logger object configured, the following methods create log messages:
374
375* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
376 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
377 a message and a level that corresponds to their respective method names. The
378 message is actually a format string, which may contain the standard string
379 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
380 rest of their arguments is a list of objects that correspond with the
381 substitution fields in the message. With regard to :const:`**kwargs`, the
382 logging methods care only about a keyword of :const:`exc_info` and use it to
383 determine whether to log exception information.
384
385* :meth:`Logger.exception` creates a log message similar to
386 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
387 stack trace along with it. Call this method only from an exception handler.
388
389* :meth:`Logger.log` takes a log level as an explicit argument. This is a
390 little more verbose for logging messages than using the log level convenience
391 methods listed above, but this is how to log at custom log levels.
392
Christian Heimesdcca98d2008-02-25 13:19:43 +0000393:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000394name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000395hierarchical structures. Multiple calls to :func:`getLogger` with the same name
396will return a reference to the same logger object. Loggers that are further
397down in the hierarchical list are children of loggers higher up in the list.
398For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000399``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
400Child loggers propagate messages up to the handlers associated with their
401ancestor loggers. Because of this, it is unnecessary to define and configure
402handlers for all the loggers an application uses. It is sufficient to
403configure handlers for a top-level logger and create child loggers as needed.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000404
405
406Handlers
407^^^^^^^^
408
409:class:`Handler` objects are responsible for dispatching the appropriate log
410messages (based on the log messages' severity) to the handler's specified
411destination. Logger objects can add zero or more handler objects to themselves
412with an :func:`addHandler` method. As an example scenario, an application may
413want to send all log messages to a log file, all log messages of error or higher
414to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000415requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000416messages of a specific severity to a specific location.
417
418The standard library includes quite a few handler types; this tutorial uses only
419:class:`StreamHandler` and :class:`FileHandler` in its examples.
420
421There are very few methods in a handler for application developers to concern
422themselves with. The only handler methods that seem relevant for application
423developers who are using the built-in handler objects (that is, not creating
424custom handlers) are the following configuration methods:
425
426* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
427 lowest severity that will be dispatched to the appropriate destination. Why
428 are there two :func:`setLevel` methods? The level set in the logger
429 determines which severity of messages it will pass to its handlers. The level
430 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000431
432* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000433
434* :func:`addFilter` and :func:`removeFilter` respectively configure and
435 deconfigure filter objects on handlers.
436
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000437Application code should not directly instantiate and use instances of
438:class:`Handler`. Instead, the :class:`Handler` class is a base class that
439defines the interface that all handlers should have and establishes some
440default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000441
442
443Formatters
444^^^^^^^^^^
445
446Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000447message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000448instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000449if your application needs special behavior. The constructor takes three
450optional arguments -- a message format string, a date format string and a style
451indicator.
452
453.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
454
455If there is no message format string, the default is to use the
456raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000457
458 %Y-%m-%d %H:%M:%S
459
Vinay Sajipa39c5712010-10-25 13:57:39 +0000460with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
461or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000462
Vinay Sajipa39c5712010-10-25 13:57:39 +0000463If the ``style`` is '%', the message format string uses
464``%(<dictionary key>)s`` styled string substitution; the possible keys are
465documented in :ref:`formatter-objects`. If the style is '{', the message format
466string is assumed to be compatible with :meth:`str.format` (using keyword
467arguments), while if the style is '$' then the message format string should
468conform to what is expected by :meth:`string.Template.substitute`.
469
470.. versionchanged:: 3.2
471 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000472
473The following message format string will log the time in a human-readable
474format, the severity of the message, and the contents of the message, in that
475order::
476
477 "%(asctime)s - %(levelname)s - %(message)s"
478
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000479Formatters use a user-configurable function to convert the creation time of a
480record to a tuple. By default, :func:`time.localtime` is used; to change this
481for a particular formatter instance, set the ``converter`` attribute of the
482instance to a function with the same signature as :func:`time.localtime` or
483:func:`time.gmtime`. To change it for all formatters, for example if you want
484all logging times to be shown in GMT, set the ``converter`` attribute in the
485Formatter class (to ``time.gmtime`` for GMT display).
486
Christian Heimes8b0facf2007-12-04 19:30:01 +0000487
488Configuring Logging
489^^^^^^^^^^^^^^^^^^^
490
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000491Programmers can configure logging in three ways:
492
4931. Creating loggers, handlers, and formatters explicitly using Python
494 code that calls the configuration methods listed above.
4952. Creating a logging config file and reading it using the :func:`fileConfig`
496 function.
4973. Creating a dictionary of configuration information and passing it
498 to the :func:`dictConfig` function.
499
500The following example configures a very simple logger, a console
501handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000502
503 import logging
504
505 # create logger
506 logger = logging.getLogger("simple_example")
507 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000508
Christian Heimes8b0facf2007-12-04 19:30:01 +0000509 # create console handler and set level to debug
510 ch = logging.StreamHandler()
511 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000512
Christian Heimes8b0facf2007-12-04 19:30:01 +0000513 # create formatter
514 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000515
Christian Heimes8b0facf2007-12-04 19:30:01 +0000516 # add formatter to ch
517 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000518
Christian Heimes8b0facf2007-12-04 19:30:01 +0000519 # add ch to logger
520 logger.addHandler(ch)
521
522 # "application" code
523 logger.debug("debug message")
524 logger.info("info message")
525 logger.warn("warn message")
526 logger.error("error message")
527 logger.critical("critical message")
528
529Running this module from the command line produces the following output::
530
531 $ python simple_logging_module.py
532 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
533 2005-03-19 15:10:26,620 - simple_example - INFO - info message
534 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
535 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
536 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
537
538The following Python module creates a logger, handler, and formatter nearly
539identical to those in the example listed above, with the only difference being
540the names of the objects::
541
542 import logging
543 import logging.config
544
545 logging.config.fileConfig("logging.conf")
546
547 # create logger
548 logger = logging.getLogger("simpleExample")
549
550 # "application" code
551 logger.debug("debug message")
552 logger.info("info message")
553 logger.warn("warn message")
554 logger.error("error message")
555 logger.critical("critical message")
556
557Here is the logging.conf file::
558
559 [loggers]
560 keys=root,simpleExample
561
562 [handlers]
563 keys=consoleHandler
564
565 [formatters]
566 keys=simpleFormatter
567
568 [logger_root]
569 level=DEBUG
570 handlers=consoleHandler
571
572 [logger_simpleExample]
573 level=DEBUG
574 handlers=consoleHandler
575 qualname=simpleExample
576 propagate=0
577
578 [handler_consoleHandler]
579 class=StreamHandler
580 level=DEBUG
581 formatter=simpleFormatter
582 args=(sys.stdout,)
583
584 [formatter_simpleFormatter]
585 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
586 datefmt=
587
588The output is nearly identical to that of the non-config-file-based example::
589
590 $ python simple_logging_config.py
591 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
592 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
593 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
594 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
595 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
596
597You can see that the config file approach has a few advantages over the Python
598code approach, mainly separation of configuration and code and the ability of
599noncoders to easily modify the logging properties.
600
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000601Note that the class names referenced in config files need to be either relative
602to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000603import mechanisms. Thus, you could use either
604:class:`handlers.WatchedFileHandler` (relative to the logging module) or
605``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
606and module ``mymodule``, where ``mypackage`` is available on the Python import
607path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000608
Benjamin Peterson56894b52010-06-28 00:16:12 +0000609In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000610dictionaries to hold configuration information. This provides a superset of the
611functionality of the config-file-based approach outlined above, and is the
612recommended configuration method for new applications and deployments. Because
613a Python dictionary is used to hold configuration information, and since you
614can populate that dictionary using different means, you have more options for
615configuration. For example, you can use a configuration file in JSON format,
616or, if you have access to YAML processing functionality, a file in YAML
617format, to populate the configuration dictionary. Or, of course, you can
618construct the dictionary in Python code, receive it in pickled form over a
619socket, or use whatever approach makes sense for your application.
620
621Here's an example of the same configuration as above, in YAML format for
622the new dictionary-based approach::
623
624 version: 1
625 formatters:
626 simple:
627 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
628 handlers:
629 console:
630 class: logging.StreamHandler
631 level: DEBUG
632 formatter: simple
633 stream: ext://sys.stdout
634 loggers:
635 simpleExample:
636 level: DEBUG
637 handlers: [console]
638 propagate: no
639 root:
640 level: DEBUG
641 handlers: [console]
642
643For more information about logging using a dictionary, see
644:ref:`logging-config-api`.
645
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000646.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000647
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000648Configuring Logging for a Library
649^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
650
651When developing a library which uses logging, some consideration needs to be
652given to its configuration. If the using application does not use logging, and
653library code makes logging calls, then a one-off message "No handlers could be
654found for logger X.Y.Z" is printed to the console. This message is intended
655to catch mistakes in logging configuration, but will confuse an application
656developer who is not aware of logging by the library.
657
658In addition to documenting how a library uses logging, a good way to configure
659library logging so that it does not cause a spurious message is to add a
660handler which does nothing. This avoids the message being printed, since a
661handler will be found: it just doesn't produce any output. If the library user
662configures logging for application use, presumably that configuration will add
663some handlers, and if levels are suitably configured then logging calls made
664in library code will send output to those handlers, as normal.
665
666A do-nothing handler can be simply defined as follows::
667
668 import logging
669
670 class NullHandler(logging.Handler):
671 def emit(self, record):
672 pass
673
674An instance of this handler should be added to the top-level logger of the
675logging namespace used by the library. If all logging by a library *foo* is
676done using loggers with names matching "foo.x.y", then the code::
677
678 import logging
679
680 h = NullHandler()
681 logging.getLogger("foo").addHandler(h)
682
683should have the desired effect. If an organisation produces a number of
684libraries, then the logger name specified can be "orgname.foo" rather than
685just "foo".
686
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000687**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
688than* :class:`NullHandler` *to your library's loggers*. This is because the
689configuration of handlers is the prerogative of the application developer who
690uses your library. The application developer knows their target audience and
691what handlers are most appropriate for their application: if you add handlers
692"under the hood", you might well interfere with their ability to carry out
693unit tests and deliver logs which suit their requirements.
694
Georg Brandlf9734072008-12-07 15:30:06 +0000695.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000696 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000697
Christian Heimes8b0facf2007-12-04 19:30:01 +0000698
699Logging Levels
700--------------
701
Georg Brandl116aa622007-08-15 14:28:22 +0000702The numeric values of logging levels are given in the following table. These are
703primarily of interest if you want to define your own levels, and need them to
704have specific values relative to the predefined levels. If you define a level
705with the same numeric value, it overwrites the predefined value; the predefined
706name is lost.
707
708+--------------+---------------+
709| Level | Numeric value |
710+==============+===============+
711| ``CRITICAL`` | 50 |
712+--------------+---------------+
713| ``ERROR`` | 40 |
714+--------------+---------------+
715| ``WARNING`` | 30 |
716+--------------+---------------+
717| ``INFO`` | 20 |
718+--------------+---------------+
719| ``DEBUG`` | 10 |
720+--------------+---------------+
721| ``NOTSET`` | 0 |
722+--------------+---------------+
723
724Levels can also be associated with loggers, being set either by the developer or
725through loading a saved logging configuration. When a logging method is called
726on a logger, the logger compares its own level with the level associated with
727the method call. If the logger's level is higher than the method call's, no
728logging message is actually generated. This is the basic mechanism controlling
729the verbosity of logging output.
730
731Logging messages are encoded as instances of the :class:`LogRecord` class. When
732a logger decides to actually log an event, a :class:`LogRecord` instance is
733created from the logging message.
734
735Logging messages are subjected to a dispatch mechanism through the use of
736:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
737class. Handlers are responsible for ensuring that a logged message (in the form
738of a :class:`LogRecord`) ends up in a particular location (or set of locations)
739which is useful for the target audience for that message (such as end users,
740support desk staff, system administrators, developers). Handlers are passed
741:class:`LogRecord` instances intended for particular destinations. Each logger
742can have zero, one or more handlers associated with it (via the
743:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
744directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000745of the logger* are called to dispatch the message (unless the *propagate* flag
746for a logger is set to a false value, at which point the passing to ancestor
747handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000748
749Just as for loggers, handlers can have levels associated with them. A handler's
750level acts as a filter in the same way as a logger's level does. If a handler
751decides to actually dispatch an event, the :meth:`emit` method is used to send
752the message to its destination. Most user-defined subclasses of :class:`Handler`
753will need to override this :meth:`emit`.
754
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000755.. _custom-levels:
756
757Custom Levels
758^^^^^^^^^^^^^
759
760Defining your own levels is possible, but should not be necessary, as the
761existing levels have been chosen on the basis of practical experience.
762However, if you are convinced that you need custom levels, great care should
763be exercised when doing this, and it is possibly *a very bad idea to define
764custom levels if you are developing a library*. That's because if multiple
765library authors all define their own custom levels, there is a chance that
766the logging output from such multiple libraries used together will be
767difficult for the using developer to control and/or interpret, because a
768given numeric value might mean different things for different libraries.
769
770
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000771Useful Handlers
772---------------
773
Georg Brandl116aa622007-08-15 14:28:22 +0000774In addition to the base :class:`Handler` class, many useful subclasses are
775provided:
776
Vinay Sajip121a1c42010-09-08 10:46:15 +0000777#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000778 objects).
779
Vinay Sajip121a1c42010-09-08 10:46:15 +0000780#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000782.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000783
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000784#. :class:`BaseRotatingHandler` is the base class for handlers that
785 rotate log files at a certain point. It is not meant to be instantiated
786 directly. Instead, use :class:`RotatingFileHandler` or
787 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Vinay Sajip121a1c42010-09-08 10:46:15 +0000789#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000790 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000791
Vinay Sajip121a1c42010-09-08 10:46:15 +0000792#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000793 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000794
Vinay Sajip121a1c42010-09-08 10:46:15 +0000795#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000796 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Vinay Sajip121a1c42010-09-08 10:46:15 +0000798#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000799 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Vinay Sajip121a1c42010-09-08 10:46:15 +0000801#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000802 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000803
Vinay Sajip121a1c42010-09-08 10:46:15 +0000804#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000805 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000806
Vinay Sajip121a1c42010-09-08 10:46:15 +0000807#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000808 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000809
Vinay Sajip121a1c42010-09-08 10:46:15 +0000810#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000811 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Vinay Sajip121a1c42010-09-08 10:46:15 +0000813#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000814 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000816#. :class:`WatchedFileHandler` instances watch the file they are
817 logging to. If the file changes, it is closed and reopened using the file
818 name. This handler is only useful on Unix-like systems; Windows does not
819 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000820
Vinay Sajip121a1c42010-09-08 10:46:15 +0000821#. :class:`QueueHandler` instances send messages to a queue, such as
822 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
823
Vinay Sajip30bf1222009-01-10 19:23:34 +0000824.. currentmodule:: logging
825
Georg Brandlf9734072008-12-07 15:30:06 +0000826#. :class:`NullHandler` instances do nothing with error messages. They are used
827 by library developers who want to use logging, but want to avoid the "No
828 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000829 the library user has not configured logging. See :ref:`library-config` for
830 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000831
832.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000833 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000834
Vinay Sajip121a1c42010-09-08 10:46:15 +0000835.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000836 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000837
Vinay Sajipa17775f2008-12-30 07:32:59 +0000838The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
839classes are defined in the core logging package. The other handlers are
840defined in a sub- module, :mod:`logging.handlers`. (There is also another
841sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843Logged messages are formatted for presentation through instances of the
844:class:`Formatter` class. They are initialized with a format string suitable for
845use with the % operator and a dictionary.
846
847For formatting multiple messages in a batch, instances of
848:class:`BufferingFormatter` can be used. In addition to the format string (which
849is applied to each message in the batch), there is provision for header and
850trailer format strings.
851
852When filtering based on logger level and/or handler level is not enough,
853instances of :class:`Filter` can be added to both :class:`Logger` and
854:class:`Handler` instances (through their :meth:`addFilter` method). Before
855deciding to process a message further, both loggers and handlers consult all
856their filters for permission. If any filter returns a false value, the message
857is not processed further.
858
859The basic :class:`Filter` functionality allows filtering by specific logger
860name. If this feature is used, messages sent to the named logger and its
861children are allowed through the filter, and all others dropped.
862
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000863Module-Level Functions
864----------------------
865
Georg Brandl116aa622007-08-15 14:28:22 +0000866In addition to the classes described above, there are a number of module- level
867functions.
868
869
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000870.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000871
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000872 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000873 logger which is the root logger of the hierarchy. If specified, the name is
874 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
875 Choice of these names is entirely up to the developer who is using logging.
876
877 All calls to this function with a given name return the same logger instance.
878 This means that logger instances never need to be passed between different parts
879 of an application.
880
881
882.. function:: getLoggerClass()
883
884 Return either the standard :class:`Logger` class, or the last class passed to
885 :func:`setLoggerClass`. This function may be called from within a new class
886 definition, to ensure that installing a customised :class:`Logger` class will
887 not undo customisations already applied by other code. For example::
888
889 class MyLogger(logging.getLoggerClass()):
890 # ... override behaviour here
891
892
Vinay Sajip61561522010-12-03 11:50:38 +0000893.. function:: getLogRecordFactory()
894
895 Return a callable which is used to create a :class:`LogRecord`.
896
897 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000898 This function has been provided, along with :func:`setLogRecordFactory`,
899 to allow developers more control over how the :class:`LogRecord`
900 representing a logging event is constructed.
901
902 See :func:`setLogRecordFactory` for more information about the how the
903 factory is called.
904
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000905.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000906
907 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
908 message format string, and the *args* are the arguments which are merged into
909 *msg* using the string formatting operator. (Note that this means that you can
910 use keywords in the format string, together with a single dictionary argument.)
911
Vinay Sajip8593ae62010-11-14 21:33:04 +0000912 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +0000913 which, if it does not evaluate as false, causes exception information to be
914 added to the logging message. If an exception tuple (in the format returned by
915 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
916 is called to get the exception information.
917
Vinay Sajip8593ae62010-11-14 21:33:04 +0000918 The second optional keyword argument is *stack_info*, which defaults to
919 False. If specified as True, stack information is added to the logging
920 message, including the actual logging call. Note that this is not the same
921 stack information as that displayed through specifying *exc_info*: The
922 former is stack frames from the bottom of the stack up to the logging call
923 in the current thread, whereas the latter is information about stack frames
924 which have been unwound, following an exception, while searching for
925 exception handlers.
926
927 You can specify *stack_info* independently of *exc_info*, e.g. to just show
928 how you got to a certain point in your code, even when no exceptions were
929 raised. The stack frames are printed following a header line which says::
930
931 Stack (most recent call last):
932
933 This mimics the `Traceback (most recent call last):` which is used when
934 displaying exception frames.
935
936 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +0000937 dictionary which is used to populate the __dict__ of the LogRecord created for
938 the logging event with user-defined attributes. These custom attributes can then
939 be used as you like. For example, they could be incorporated into logged
940 messages. For example::
941
942 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
943 logging.basicConfig(format=FORMAT)
944 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
945 logging.warning("Protocol problem: %s", "connection reset", extra=d)
946
Vinay Sajip4039aff2010-09-11 10:25:28 +0000947 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
950
951 The keys in the dictionary passed in *extra* should not clash with the keys used
952 by the logging system. (See the :class:`Formatter` documentation for more
953 information on which keys are used by the logging system.)
954
955 If you choose to use these attributes in logged messages, you need to exercise
956 some care. In the above example, for instance, the :class:`Formatter` has been
957 set up with a format string which expects 'clientip' and 'user' in the attribute
958 dictionary of the LogRecord. If these are missing, the message will not be
959 logged because a string formatting exception will occur. So in this case, you
960 always need to pass the *extra* dictionary with these keys.
961
962 While this might be annoying, this feature is intended for use in specialized
963 circumstances, such as multi-threaded servers where the same code executes in
964 many contexts, and interesting conditions which arise are dependent on this
965 context (such as remote client IP address and authenticated user name, in the
966 above example). In such circumstances, it is likely that specialized
967 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
968
Vinay Sajip8593ae62010-11-14 21:33:04 +0000969 .. versionadded:: 3.2
970 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000972.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000973
974 Logs a message with level :const:`INFO` on the root logger. The arguments are
975 interpreted as for :func:`debug`.
976
977
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000978.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980 Logs a message with level :const:`WARNING` on the root logger. The arguments are
981 interpreted as for :func:`debug`.
982
983
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000984.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986 Logs a message with level :const:`ERROR` on the root logger. The arguments are
987 interpreted as for :func:`debug`.
988
989
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000990.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
993 are interpreted as for :func:`debug`.
994
995
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000996.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998 Logs a message with level :const:`ERROR` on the root logger. The arguments are
999 interpreted as for :func:`debug`. Exception info is added to the logging
1000 message. This function should only be called from an exception handler.
1001
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001002.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004 Logs a message with level *level* on the root logger. The other arguments are
1005 interpreted as for :func:`debug`.
1006
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001007 PLEASE NOTE: The above module-level functions which delegate to the root
1008 logger should *not* be used in threads, in versions of Python earlier than
1009 2.7.1 and 3.2, unless at least one handler has been added to the root
1010 logger *before* the threads are started. These convenience functions call
1011 :func:`basicConfig` to ensure that at least one handler is available; in
1012 earlier versions of Python, this can (under rare circumstances) lead to
1013 handlers being added multiple times to the root logger, which can in turn
1014 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001015
1016.. function:: disable(lvl)
1017
1018 Provides an overriding level *lvl* for all loggers which takes precedence over
1019 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001020 output down across the whole application, this function can be useful. Its
1021 effect is to disable all logging calls of severity *lvl* and below, so that
1022 if you call it with a value of INFO, then all INFO and DEBUG events would be
1023 discarded, whereas those of severity WARNING and above would be processed
1024 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001025
1026
1027.. function:: addLevelName(lvl, levelName)
1028
1029 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1030 used to map numeric levels to a textual representation, for example when a
1031 :class:`Formatter` formats a message. This function can also be used to define
1032 your own levels. The only constraints are that all levels used must be
1033 registered using this function, levels should be positive integers and they
1034 should increase in increasing order of severity.
1035
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001036 NOTE: If you are thinking of defining your own levels, please see the section
1037 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001038
1039.. function:: getLevelName(lvl)
1040
1041 Returns the textual representation of logging level *lvl*. If the level is one
1042 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1043 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1044 have associated levels with names using :func:`addLevelName` then the name you
1045 have associated with *lvl* is returned. If a numeric value corresponding to one
1046 of the defined levels is passed in, the corresponding string representation is
1047 returned. Otherwise, the string "Level %s" % lvl is returned.
1048
1049
1050.. function:: makeLogRecord(attrdict)
1051
1052 Creates and returns a new :class:`LogRecord` instance whose attributes are
1053 defined by *attrdict*. This function is useful for taking a pickled
1054 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1055 it as a :class:`LogRecord` instance at the receiving end.
1056
1057
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001058.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001059
1060 Does basic configuration for the logging system by creating a
1061 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001062 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001063 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1064 if no handlers are defined for the root logger.
1065
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001066 This function does nothing if the root logger already has handlers
1067 configured for it.
1068
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001069 PLEASE NOTE: This function should be called from the main thread
1070 before other threads are started. In versions of Python prior to
1071 2.7.1 and 3.2, if this function is called from multiple threads,
1072 it is possible (in rare circumstances) that a handler will be added
1073 to the root logger more than once, leading to unexpected results
1074 such as messages being duplicated in the log.
1075
Georg Brandl116aa622007-08-15 14:28:22 +00001076 The following keyword arguments are supported.
1077
1078 +--------------+---------------------------------------------+
1079 | Format | Description |
1080 +==============+=============================================+
1081 | ``filename`` | Specifies that a FileHandler be created, |
1082 | | using the specified filename, rather than a |
1083 | | StreamHandler. |
1084 +--------------+---------------------------------------------+
1085 | ``filemode`` | Specifies the mode to open the file, if |
1086 | | filename is specified (if filemode is |
1087 | | unspecified, it defaults to 'a'). |
1088 +--------------+---------------------------------------------+
1089 | ``format`` | Use the specified format string for the |
1090 | | handler. |
1091 +--------------+---------------------------------------------+
1092 | ``datefmt`` | Use the specified date/time format. |
1093 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001094 | ``style`` | If ``format`` is specified, use this style |
1095 | | for the format string. One of '%', '{' or |
1096 | | '$' for %-formatting, :meth:`str.format` or |
1097 | | :class:`string.Template` respectively, and |
1098 | | defaulting to '%' if not specified. |
1099 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001100 | ``level`` | Set the root logger level to the specified |
1101 | | level. |
1102 +--------------+---------------------------------------------+
1103 | ``stream`` | Use the specified stream to initialize the |
1104 | | StreamHandler. Note that this argument is |
1105 | | incompatible with 'filename' - if both are |
1106 | | present, 'stream' is ignored. |
1107 +--------------+---------------------------------------------+
1108
Vinay Sajipc5b27302010-10-31 14:59:16 +00001109 .. versionchanged:: 3.2
1110 The ``style`` argument was added.
1111
1112
Georg Brandl116aa622007-08-15 14:28:22 +00001113.. function:: shutdown()
1114
1115 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001116 closing all handlers. This should be called at application exit and no
1117 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001118
1119
1120.. function:: setLoggerClass(klass)
1121
1122 Tells the logging system to use the class *klass* when instantiating a logger.
1123 The class should define :meth:`__init__` such that only a name argument is
1124 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1125 function is typically called before any loggers are instantiated by applications
1126 which need to use custom logger behavior.
1127
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001128
Vinay Sajip61561522010-12-03 11:50:38 +00001129.. function:: setLogRecordFactory(factory)
1130
1131 Set a callable which is used to create a :class:`LogRecord`.
1132
1133 :param factory: The factory callable to be used to instantiate a log record.
1134
1135 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001136 This function has been provided, along with :func:`getLogRecordFactory`, to
1137 allow developers more control over how the :class:`LogRecord` representing
1138 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001139
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001140 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001141
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001142 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, \*\*kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001143
1144 :name: The logger name.
1145 :level: The logging level (numeric).
1146 :fn: The full pathname of the file where the logging call was made.
1147 :lno: The line number in the file where the logging call was made.
1148 :msg: The logging message.
1149 :args: The arguments for the logging message.
1150 :exc_info: An exception tuple, or None.
1151 :func: The name of the function or method which invoked the logging
1152 call.
1153 :sinfo: A stack traceback such as is provided by
1154 :func:`traceback.print_stack`, showing the call hierarchy.
1155 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001156
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001157
Georg Brandl116aa622007-08-15 14:28:22 +00001158.. seealso::
1159
1160 :pep:`282` - A Logging System
1161 The proposal which described this feature for inclusion in the Python standard
1162 library.
1163
Christian Heimes255f53b2007-12-08 15:33:56 +00001164 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001165 This is the original source for the :mod:`logging` package. The version of the
1166 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1167 and 2.2.x, which do not include the :mod:`logging` package in the standard
1168 library.
1169
Vinay Sajip4039aff2010-09-11 10:25:28 +00001170.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001171
1172Logger Objects
1173--------------
1174
1175Loggers have the following attributes and methods. Note that Loggers are never
1176instantiated directly, but always through the module-level function
1177``logging.getLogger(name)``.
1178
Vinay Sajip0258ce82010-09-22 20:34:53 +00001179.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001180
1181.. attribute:: Logger.propagate
1182
1183 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001184 its child loggers to the handlers of higher level (ancestor) loggers. The
1185 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187
1188.. method:: Logger.setLevel(lvl)
1189
1190 Sets the threshold for this logger to *lvl*. Logging messages which are less
1191 severe than *lvl* will be ignored. When a logger is created, the level is set to
1192 :const:`NOTSET` (which causes all messages to be processed when the logger is
1193 the root logger, or delegation to the parent when the logger is a non-root
1194 logger). Note that the root logger is created with level :const:`WARNING`.
1195
1196 The term "delegation to the parent" means that if a logger has a level of
1197 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1198 a level other than NOTSET is found, or the root is reached.
1199
1200 If an ancestor is found with a level other than NOTSET, then that ancestor's
1201 level is treated as the effective level of the logger where the ancestor search
1202 began, and is used to determine how a logging event is handled.
1203
1204 If the root is reached, and it has a level of NOTSET, then all messages will be
1205 processed. Otherwise, the root's level will be used as the effective level.
1206
1207
1208.. method:: Logger.isEnabledFor(lvl)
1209
1210 Indicates if a message of severity *lvl* would be processed by this logger.
1211 This method checks first the module-level level set by
1212 ``logging.disable(lvl)`` and then the logger's effective level as determined
1213 by :meth:`getEffectiveLevel`.
1214
1215
1216.. method:: Logger.getEffectiveLevel()
1217
1218 Indicates the effective level for this logger. If a value other than
1219 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1220 the hierarchy is traversed towards the root until a value other than
1221 :const:`NOTSET` is found, and that value is returned.
1222
1223
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001224.. method:: Logger.getChild(suffix)
1225
1226 Returns a logger which is a descendant to this logger, as determined by the suffix.
1227 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1228 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1229 convenience method, useful when the parent logger is named using e.g. ``__name__``
1230 rather than a literal string.
1231
1232 .. versionadded:: 3.2
1233
Georg Brandl67b21b72010-08-17 15:07:14 +00001234
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001235.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001236
1237 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1238 message format string, and the *args* are the arguments which are merged into
1239 *msg* using the string formatting operator. (Note that this means that you can
1240 use keywords in the format string, together with a single dictionary argument.)
1241
Vinay Sajip8593ae62010-11-14 21:33:04 +00001242 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001243 which, if it does not evaluate as false, causes exception information to be
1244 added to the logging message. If an exception tuple (in the format returned by
1245 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1246 is called to get the exception information.
1247
Vinay Sajip8593ae62010-11-14 21:33:04 +00001248 The second optional keyword argument is *stack_info*, which defaults to
1249 False. If specified as True, stack information is added to the logging
1250 message, including the actual logging call. Note that this is not the same
1251 stack information as that displayed through specifying *exc_info*: The
1252 former is stack frames from the bottom of the stack up to the logging call
1253 in the current thread, whereas the latter is information about stack frames
1254 which have been unwound, following an exception, while searching for
1255 exception handlers.
1256
1257 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1258 how you got to a certain point in your code, even when no exceptions were
1259 raised. The stack frames are printed following a header line which says::
1260
1261 Stack (most recent call last):
1262
1263 This mimics the `Traceback (most recent call last):` which is used when
1264 displaying exception frames.
1265
1266 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001267 dictionary which is used to populate the __dict__ of the LogRecord created for
1268 the logging event with user-defined attributes. These custom attributes can then
1269 be used as you like. For example, they could be incorporated into logged
1270 messages. For example::
1271
1272 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1273 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001274 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001275 logger = logging.getLogger("tcpserver")
1276 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1277
1278 would print something like ::
1279
1280 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1281
1282 The keys in the dictionary passed in *extra* should not clash with the keys used
1283 by the logging system. (See the :class:`Formatter` documentation for more
1284 information on which keys are used by the logging system.)
1285
1286 If you choose to use these attributes in logged messages, you need to exercise
1287 some care. In the above example, for instance, the :class:`Formatter` has been
1288 set up with a format string which expects 'clientip' and 'user' in the attribute
1289 dictionary of the LogRecord. If these are missing, the message will not be
1290 logged because a string formatting exception will occur. So in this case, you
1291 always need to pass the *extra* dictionary with these keys.
1292
1293 While this might be annoying, this feature is intended for use in specialized
1294 circumstances, such as multi-threaded servers where the same code executes in
1295 many contexts, and interesting conditions which arise are dependent on this
1296 context (such as remote client IP address and authenticated user name, in the
1297 above example). In such circumstances, it is likely that specialized
1298 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1299
Vinay Sajip8593ae62010-11-14 21:33:04 +00001300 .. versionadded:: 3.2
1301 The *stack_info* parameter was added.
1302
Georg Brandl116aa622007-08-15 14:28:22 +00001303
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001304.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001305
1306 Logs a message with level :const:`INFO` on this logger. The arguments are
1307 interpreted as for :meth:`debug`.
1308
1309
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001310.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312 Logs a message with level :const:`WARNING` on this logger. The arguments are
1313 interpreted as for :meth:`debug`.
1314
1315
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001316.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318 Logs a message with level :const:`ERROR` on this logger. The arguments are
1319 interpreted as for :meth:`debug`.
1320
1321
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001322.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001323
1324 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1325 interpreted as for :meth:`debug`.
1326
1327
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001328.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001329
1330 Logs a message with integer level *lvl* on this logger. The other arguments are
1331 interpreted as for :meth:`debug`.
1332
1333
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001334.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001335
1336 Logs a message with level :const:`ERROR` on this logger. The arguments are
1337 interpreted as for :meth:`debug`. Exception info is added to the logging
1338 message. This method should only be called from an exception handler.
1339
1340
1341.. method:: Logger.addFilter(filt)
1342
1343 Adds the specified filter *filt* to this logger.
1344
1345
1346.. method:: Logger.removeFilter(filt)
1347
1348 Removes the specified filter *filt* from this logger.
1349
1350
1351.. method:: Logger.filter(record)
1352
1353 Applies this logger's filters to the record and returns a true value if the
1354 record is to be processed.
1355
1356
1357.. method:: Logger.addHandler(hdlr)
1358
1359 Adds the specified handler *hdlr* to this logger.
1360
1361
1362.. method:: Logger.removeHandler(hdlr)
1363
1364 Removes the specified handler *hdlr* from this logger.
1365
1366
Vinay Sajip8593ae62010-11-14 21:33:04 +00001367.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001370 number, function name and stack information as a 4-element tuple. The stack
1371 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001372
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374.. method:: Logger.handle(record)
1375
1376 Handles a record by passing it to all handlers associated with this logger and
1377 its ancestors (until a false value of *propagate* is found). This method is used
1378 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001379 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001380
1381
Vinay Sajip8593ae62010-11-14 21:33:04 +00001382.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001383
1384 This is a factory method which can be overridden in subclasses to create
1385 specialized :class:`LogRecord` instances.
1386
Vinay Sajip83eadd12010-09-20 10:31:18 +00001387.. method:: Logger.hasHandlers()
1388
1389 Checks to see if this logger has any handlers configured. This is done by
1390 looking for handlers in this logger and its parents in the logger hierarchy.
1391 Returns True if a handler was found, else False. The method stops searching
1392 up the hierarchy whenever a logger with the "propagate" attribute set to
1393 False is found - that will be the last logger which is checked for the
1394 existence of handlers.
1395
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001396 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001397
Vinay Sajipa18b9592010-12-12 13:20:55 +00001398.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001399
1400Basic example
1401-------------
1402
Georg Brandl116aa622007-08-15 14:28:22 +00001403The :mod:`logging` package provides a lot of flexibility, and its configuration
1404can appear daunting. This section demonstrates that simple use of the logging
1405package is possible.
1406
1407The simplest example shows logging to the console::
1408
1409 import logging
1410
1411 logging.debug('A debug message')
1412 logging.info('Some information')
1413 logging.warning('A shot across the bows')
1414
1415If you run the above script, you'll see this::
1416
1417 WARNING:root:A shot across the bows
1418
1419Because no particular logger was specified, the system used the root logger. The
1420debug and info messages didn't appear because by default, the root logger is
1421configured to only handle messages with a severity of WARNING or above. The
1422message format is also a configuration default, as is the output destination of
1423the messages - ``sys.stderr``. The severity level, the message format and
1424destination can be easily changed, as shown in the example below::
1425
1426 import logging
1427
1428 logging.basicConfig(level=logging.DEBUG,
1429 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001430 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001431 filemode='w')
1432 logging.debug('A debug message')
1433 logging.info('Some information')
1434 logging.warning('A shot across the bows')
1435
1436The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001437which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001438something like the following::
1439
1440 2004-07-02 13:00:08,743 DEBUG A debug message
1441 2004-07-02 13:00:08,743 INFO Some information
1442 2004-07-02 13:00:08,743 WARNING A shot across the bows
1443
1444This time, all messages with a severity of DEBUG or above were handled, and the
1445format of the messages was also changed, and output went to the specified file
1446rather than the console.
1447
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001448.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001449
1450Formatting uses the old Python string formatting - see section
1451:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001452specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1453documentation.
1454
1455+-------------------+-----------------------------------------------+
1456| Format | Description |
1457+===================+===============================================+
1458| ``%(name)s`` | Name of the logger (logging channel). |
1459+-------------------+-----------------------------------------------+
1460| ``%(levelname)s`` | Text logging level for the message |
1461| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1462| | ``'ERROR'``, ``'CRITICAL'``). |
1463+-------------------+-----------------------------------------------+
1464| ``%(asctime)s`` | Human-readable time when the |
1465| | :class:`LogRecord` was created. By default |
1466| | this is of the form "2003-07-08 16:49:45,896" |
1467| | (the numbers after the comma are millisecond |
1468| | portion of the time). |
1469+-------------------+-----------------------------------------------+
1470| ``%(message)s`` | The logged message. |
1471+-------------------+-----------------------------------------------+
1472
1473To change the date/time format, you can pass an additional keyword parameter,
1474*datefmt*, as in the following::
1475
1476 import logging
1477
1478 logging.basicConfig(level=logging.DEBUG,
1479 format='%(asctime)s %(levelname)-8s %(message)s',
1480 datefmt='%a, %d %b %Y %H:%M:%S',
1481 filename='/temp/myapp.log',
1482 filemode='w')
1483 logging.debug('A debug message')
1484 logging.info('Some information')
1485 logging.warning('A shot across the bows')
1486
1487which would result in output like ::
1488
1489 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1490 Fri, 02 Jul 2004 13:06:18 INFO Some information
1491 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1492
1493The date format string follows the requirements of :func:`strftime` - see the
1494documentation for the :mod:`time` module.
1495
1496If, instead of sending logging output to the console or a file, you'd rather use
1497a file-like object which you have created separately, you can pass it to
1498:func:`basicConfig` using the *stream* keyword argument. Note that if both
1499*stream* and *filename* keyword arguments are passed, the *stream* argument is
1500ignored.
1501
1502Of course, you can put variable information in your output. To do this, simply
1503have the message be a format string and pass in additional arguments containing
1504the variable information, as in the following example::
1505
1506 import logging
1507
1508 logging.basicConfig(level=logging.DEBUG,
1509 format='%(asctime)s %(levelname)-8s %(message)s',
1510 datefmt='%a, %d %b %Y %H:%M:%S',
1511 filename='/temp/myapp.log',
1512 filemode='w')
1513 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1514
1515which would result in ::
1516
1517 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1518
1519
Vinay Sajipa18b9592010-12-12 13:20:55 +00001520Using file rotation
1521^^^^^^^^^^^^^^^^^^^
1522
1523.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1524.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1525
1526Sometimes you want to let a log file grow to a certain size, then open a new
1527file and log to that. You may want to keep a certain number of these files, and
1528when that many files have been created, rotate the files so that the number of
1529files and the size of the files both remin bounded. For this usage pattern, the
1530logging package provides a :class:`RotatingFileHandler`::
1531
1532 import glob
1533 import logging
1534 import logging.handlers
1535
1536 LOG_FILENAME = 'logging_rotatingfile_example.out'
1537
1538 # Set up a specific logger with our desired output level
1539 my_logger = logging.getLogger('MyLogger')
1540 my_logger.setLevel(logging.DEBUG)
1541
1542 # Add the log message handler to the logger
1543 handler = logging.handlers.RotatingFileHandler(
1544 LOG_FILENAME, maxBytes=20, backupCount=5)
1545
1546 my_logger.addHandler(handler)
1547
1548 # Log some messages
1549 for i in range(20):
1550 my_logger.debug('i = %d' % i)
1551
1552 # See what files are created
1553 logfiles = glob.glob('%s*' % LOG_FILENAME)
1554
1555 for filename in logfiles:
1556 print(filename)
1557
1558The result should be 6 separate files, each with part of the log history for the
1559application::
1560
1561 logging_rotatingfile_example.out
1562 logging_rotatingfile_example.out.1
1563 logging_rotatingfile_example.out.2
1564 logging_rotatingfile_example.out.3
1565 logging_rotatingfile_example.out.4
1566 logging_rotatingfile_example.out.5
1567
1568The most current file is always :file:`logging_rotatingfile_example.out`,
1569and each time it reaches the size limit it is renamed with the suffix
1570``.1``. Each of the existing backup files is renamed to increment the suffix
1571(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1572
1573Obviously this example sets the log length much much too small as an extreme
1574example. You would want to set *maxBytes* to an appropriate value.
1575
1576
1577The logger, handler, and log message call each specify a level. The log message
1578is only emitted if the handler and logger are configured to emit messages of
1579that level or lower. For example, if a message is ``CRITICAL``, and the logger
1580is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1581the logger is set to produce only ``ERROR``\s, the message is not emitted::
1582
1583 import logging
1584 import sys
1585
1586 LEVELS = {'debug': logging.DEBUG,
1587 'info': logging.INFO,
1588 'warning': logging.WARNING,
1589 'error': logging.ERROR,
1590 'critical': logging.CRITICAL}
1591
1592 if len(sys.argv) > 1:
1593 level_name = sys.argv[1]
1594 level = LEVELS.get(level_name, logging.NOTSET)
1595 logging.basicConfig(level=level)
1596
1597 logging.debug('This is a debug message')
1598 logging.info('This is an info message')
1599 logging.warning('This is a warning message')
1600 logging.error('This is an error message')
1601 logging.critical('This is a critical error message')
1602
1603Run the script with an argument like 'debug' or 'warning' to see which messages
1604show up at different levels::
1605
1606 $ python logging_level_example.py debug
1607 DEBUG:root:This is a debug message
1608 INFO:root:This is an info message
1609 WARNING:root:This is a warning message
1610 ERROR:root:This is an error message
1611 CRITICAL:root:This is a critical error message
1612
1613 $ python logging_level_example.py info
1614 INFO:root:This is an info message
1615 WARNING:root:This is a warning message
1616 ERROR:root:This is an error message
1617 CRITICAL:root:This is a critical error message
1618
1619You will notice that these log messages all have ``root`` embedded in them. The
1620logging module supports a hierarchy of loggers with different names. An easy
1621way to tell where a specific log message comes from is to use a separate logger
1622object for each of your modules. Each new logger "inherits" the configuration
1623of its parent, and log messages sent to a logger include the name of that
1624logger. Optionally, each logger can be configured differently, so that messages
1625from different modules are handled in different ways. Let's look at a simple
1626example of how to log from different modules so it is easy to trace the source
1627of the message::
1628
1629 import logging
1630
1631 logging.basicConfig(level=logging.WARNING)
1632
1633 logger1 = logging.getLogger('package1.module1')
1634 logger2 = logging.getLogger('package2.module2')
1635
1636 logger1.warning('This message comes from one module')
1637 logger2.warning('And this message comes from another module')
1638
1639And the output::
1640
1641 $ python logging_modules_example.py
1642 WARNING:package1.module1:This message comes from one module
1643 WARNING:package2.module2:And this message comes from another module
1644
1645There are many more options for configuring logging, including different log
1646message formatting options, having messages delivered to multiple destinations,
1647and changing the configuration of a long-running application on the fly using a
1648socket interface. All of these options are covered in depth in the library
1649module documentation.
1650
1651
Georg Brandl116aa622007-08-15 14:28:22 +00001652.. _multiple-destinations:
1653
1654Logging to multiple destinations
1655--------------------------------
1656
1657Let's say you want to log to console and file with different message formats and
1658in differing circumstances. Say you want to log messages with levels of DEBUG
1659and higher to file, and those messages at level INFO and higher to the console.
1660Let's also assume that the file should contain timestamps, but the console
1661messages should not. Here's how you can achieve this::
1662
1663 import logging
1664
1665 # set up logging to file - see previous section for more details
1666 logging.basicConfig(level=logging.DEBUG,
1667 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1668 datefmt='%m-%d %H:%M',
1669 filename='/temp/myapp.log',
1670 filemode='w')
1671 # define a Handler which writes INFO messages or higher to the sys.stderr
1672 console = logging.StreamHandler()
1673 console.setLevel(logging.INFO)
1674 # set a format which is simpler for console use
1675 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1676 # tell the handler to use this format
1677 console.setFormatter(formatter)
1678 # add the handler to the root logger
1679 logging.getLogger('').addHandler(console)
1680
1681 # Now, we can log to the root logger, or any other logger. First the root...
1682 logging.info('Jackdaws love my big sphinx of quartz.')
1683
1684 # Now, define a couple of other loggers which might represent areas in your
1685 # application:
1686
1687 logger1 = logging.getLogger('myapp.area1')
1688 logger2 = logging.getLogger('myapp.area2')
1689
1690 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1691 logger1.info('How quickly daft jumping zebras vex.')
1692 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1693 logger2.error('The five boxing wizards jump quickly.')
1694
1695When you run this, on the console you will see ::
1696
1697 root : INFO Jackdaws love my big sphinx of quartz.
1698 myapp.area1 : INFO How quickly daft jumping zebras vex.
1699 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1700 myapp.area2 : ERROR The five boxing wizards jump quickly.
1701
1702and in the file you will see something like ::
1703
1704 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1705 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1706 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1707 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1708 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1709
1710As you can see, the DEBUG message only shows up in the file. The other messages
1711are sent to both destinations.
1712
1713This example uses console and file handlers, but you can use any number and
1714combination of handlers you choose.
1715
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001716.. _logging-exceptions:
1717
1718Exceptions raised during logging
1719--------------------------------
1720
1721The logging package is designed to swallow exceptions which occur while logging
1722in production. This is so that errors which occur while handling logging events
1723- such as logging misconfiguration, network or other similar errors - do not
1724cause the application using logging to terminate prematurely.
1725
1726:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1727swallowed. Other exceptions which occur during the :meth:`emit` method of a
1728:class:`Handler` subclass are passed to its :meth:`handleError` method.
1729
1730The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001731to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1732traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001733
Georg Brandlef871f62010-03-12 10:06:40 +00001734**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001735during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001736occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001737usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001738
Christian Heimes790c8232008-01-07 21:14:23 +00001739.. _context-info:
1740
1741Adding contextual information to your logging output
1742----------------------------------------------------
1743
1744Sometimes you want logging output to contain contextual information in
1745addition to the parameters passed to the logging call. For example, in a
1746networked application, it may be desirable to log client-specific information
1747in the log (e.g. remote client's username, or IP address). Although you could
1748use the *extra* parameter to achieve this, it's not always convenient to pass
1749the information in this way. While it might be tempting to create
1750:class:`Logger` instances on a per-connection basis, this is not a good idea
1751because these instances are not garbage collected. While this is not a problem
1752in practice, when the number of :class:`Logger` instances is dependent on the
1753level of granularity you want to use in logging an application, it could
1754be hard to manage if the number of :class:`Logger` instances becomes
1755effectively unbounded.
1756
Vinay Sajipc31be632010-09-06 22:18:20 +00001757
1758Using LoggerAdapters to impart contextual information
1759^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1760
Christian Heimes04c420f2008-01-18 18:40:46 +00001761An easy way in which you can pass contextual information to be output along
1762with logging event information is to use the :class:`LoggerAdapter` class.
1763This class is designed to look like a :class:`Logger`, so that you can call
1764:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1765:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1766same signatures as their counterparts in :class:`Logger`, so you can use the
1767two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001768
Christian Heimes04c420f2008-01-18 18:40:46 +00001769When you create an instance of :class:`LoggerAdapter`, you pass it a
1770:class:`Logger` instance and a dict-like object which contains your contextual
1771information. When you call one of the logging methods on an instance of
1772:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1773:class:`Logger` passed to its constructor, and arranges to pass the contextual
1774information in the delegated call. Here's a snippet from the code of
1775:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001776
Christian Heimes04c420f2008-01-18 18:40:46 +00001777 def debug(self, msg, *args, **kwargs):
1778 """
1779 Delegate a debug call to the underlying logger, after adding
1780 contextual information from this adapter instance.
1781 """
1782 msg, kwargs = self.process(msg, kwargs)
1783 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001784
Christian Heimes04c420f2008-01-18 18:40:46 +00001785The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1786information is added to the logging output. It's passed the message and
1787keyword arguments of the logging call, and it passes back (potentially)
1788modified versions of these to use in the call to the underlying logger. The
1789default implementation of this method leaves the message alone, but inserts
1790an "extra" key in the keyword argument whose value is the dict-like object
1791passed to the constructor. Of course, if you had passed an "extra" keyword
1792argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001793
Christian Heimes04c420f2008-01-18 18:40:46 +00001794The advantage of using "extra" is that the values in the dict-like object are
1795merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1796customized strings with your :class:`Formatter` instances which know about
1797the keys of the dict-like object. If you need a different method, e.g. if you
1798want to prepend or append the contextual information to the message string,
1799you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1800to do what you need. Here's an example script which uses this class, which
1801also illustrates what dict-like behaviour is needed from an arbitrary
1802"dict-like" object for use in the constructor::
1803
Christian Heimes587c2bf2008-01-19 16:21:02 +00001804 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001805
Christian Heimes587c2bf2008-01-19 16:21:02 +00001806 class ConnInfo:
1807 """
1808 An example class which shows how an arbitrary class can be used as
1809 the 'extra' context information repository passed to a LoggerAdapter.
1810 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001811
Christian Heimes587c2bf2008-01-19 16:21:02 +00001812 def __getitem__(self, name):
1813 """
1814 To allow this instance to look like a dict.
1815 """
1816 from random import choice
1817 if name == "ip":
1818 result = choice(["127.0.0.1", "192.168.0.1"])
1819 elif name == "user":
1820 result = choice(["jim", "fred", "sheila"])
1821 else:
1822 result = self.__dict__.get(name, "?")
1823 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001824
Christian Heimes587c2bf2008-01-19 16:21:02 +00001825 def __iter__(self):
1826 """
1827 To allow iteration over keys, which will be merged into
1828 the LogRecord dict before formatting and output.
1829 """
1830 keys = ["ip", "user"]
1831 keys.extend(self.__dict__.keys())
1832 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001833
Christian Heimes587c2bf2008-01-19 16:21:02 +00001834 if __name__ == "__main__":
1835 from random import choice
1836 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1837 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1838 { "ip" : "123.231.231.123", "user" : "sheila" })
1839 logging.basicConfig(level=logging.DEBUG,
1840 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1841 a1.debug("A debug message")
1842 a1.info("An info message with %s", "some parameters")
1843 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1844 for x in range(10):
1845 lvl = choice(levels)
1846 lvlname = logging.getLevelName(lvl)
1847 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001848
1849When this script is run, the output should look something like this::
1850
Christian Heimes587c2bf2008-01-19 16:21:02 +00001851 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1852 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1853 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
1854 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
1855 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
1856 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
1857 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
1858 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
1859 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
1860 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
1861 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
1862 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 +00001863
Christian Heimes790c8232008-01-07 21:14:23 +00001864
Vinay Sajipac007992010-09-17 12:45:26 +00001865.. _filters-contextual:
1866
Vinay Sajipc31be632010-09-06 22:18:20 +00001867Using Filters to impart contextual information
1868^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1869
1870You can also add contextual information to log output using a user-defined
1871:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1872passed to them, including adding additional attributes which can then be output
1873using a suitable format string, or if needed a custom :class:`Formatter`.
1874
1875For example in a web application, the request being processed (or at least,
1876the interesting parts of it) can be stored in a threadlocal
1877(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1878add, say, information from the request - say, the remote IP address and remote
1879user's username - to the ``LogRecord``, using the attribute names 'ip' and
1880'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1881string can be used to get similar output to that shown above. Here's an example
1882script::
1883
1884 import logging
1885 from random import choice
1886
1887 class ContextFilter(logging.Filter):
1888 """
1889 This is a filter which injects contextual information into the log.
1890
1891 Rather than use actual contextual information, we just use random
1892 data in this demo.
1893 """
1894
1895 USERS = ['jim', 'fred', 'sheila']
1896 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1897
1898 def filter(self, record):
1899
1900 record.ip = choice(ContextFilter.IPS)
1901 record.user = choice(ContextFilter.USERS)
1902 return True
1903
1904 if __name__ == "__main__":
1905 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1906 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1907 { "ip" : "123.231.231.123", "user" : "sheila" })
1908 logging.basicConfig(level=logging.DEBUG,
1909 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1910 a1 = logging.getLogger("a.b.c")
1911 a2 = logging.getLogger("d.e.f")
1912
1913 f = ContextFilter()
1914 a1.addFilter(f)
1915 a2.addFilter(f)
1916 a1.debug("A debug message")
1917 a1.info("An info message with %s", "some parameters")
1918 for x in range(10):
1919 lvl = choice(levels)
1920 lvlname = logging.getLevelName(lvl)
1921 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1922
1923which, when run, produces something like::
1924
1925 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1926 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1927 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
1928 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
1929 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
1930 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
1931 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
1932 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
1933 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
1934 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
1935 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
1936 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
1937
1938
Vinay Sajipd31f3632010-06-29 15:31:15 +00001939.. _multiple-processes:
1940
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001941Logging to a single file from multiple processes
1942------------------------------------------------
1943
1944Although logging is thread-safe, and logging to a single file from multiple
1945threads in a single process *is* supported, logging to a single file from
1946*multiple processes* is *not* supported, because there is no standard way to
1947serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00001948need to log to a single file from multiple processes, one way of doing this is
1949to have all the processes log to a :class:`SocketHandler`, and have a separate
1950process which implements a socket server which reads from the socket and logs
1951to file. (If you prefer, you can dedicate one thread in one of the existing
1952processes to perform this function.) The following section documents this
1953approach in more detail and includes a working socket receiver which can be
1954used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00001955
Vinay Sajip5a92b132009-08-15 23:35:08 +00001956If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00001957:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00001958:class:`Lock` class from this module to serialize access to the file from
1959your processes. The existing :class:`FileHandler` and subclasses do not make
1960use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00001961Note that at present, the :mod:`multiprocessing` module does not provide
1962working lock functionality on all platforms (see
1963http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00001964
Vinay Sajip121a1c42010-09-08 10:46:15 +00001965.. currentmodule:: logging.handlers
1966
1967Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
1968all logging events to one of the processes in your multi-process application.
1969The following example script demonstrates how you can do this; in the example
1970a separate listener process listens for events sent by other processes and logs
1971them according to its own logging configuration. Although the example only
1972demonstrates one way of doing it (for example, you may want to use a listener
1973thread rather than a separate listener process - the implementation would be
1974analogous) it does allow for completely different logging configurations for
1975the listener and the other processes in your application, and can be used as
1976the basis for code meeting your own specific requirements::
1977
1978 # You'll need these imports in your own code
1979 import logging
1980 import logging.handlers
1981 import multiprocessing
1982
1983 # Next two import lines for this demo only
1984 from random import choice, random
1985 import time
1986
1987 #
1988 # Because you'll want to define the logging configurations for listener and workers, the
1989 # listener and worker process functions take a configurer parameter which is a callable
1990 # for configuring logging for that process. These functions are also passed the queue,
1991 # which they use for communication.
1992 #
1993 # In practice, you can configure the listener however you want, but note that in this
1994 # simple example, the listener does not apply level or filter logic to received records.
1995 # In practice, you would probably want to do ths logic in the worker processes, to avoid
1996 # sending events which would be filtered out between processes.
1997 #
1998 # The size of the rotated files is made small so you can see the results easily.
1999 def listener_configurer():
2000 root = logging.getLogger()
2001 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2002 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2003 h.setFormatter(f)
2004 root.addHandler(h)
2005
2006 # This is the listener process top-level loop: wait for logging events
2007 # (LogRecords)on the queue and handle them, quit when you get a None for a
2008 # LogRecord.
2009 def listener_process(queue, configurer):
2010 configurer()
2011 while True:
2012 try:
2013 record = queue.get()
2014 if record is None: # We send this as a sentinel to tell the listener to quit.
2015 break
2016 logger = logging.getLogger(record.name)
2017 logger.handle(record) # No level or filter logic applied - just do it!
2018 except (KeyboardInterrupt, SystemExit):
2019 raise
2020 except:
2021 import sys, traceback
2022 print >> sys.stderr, 'Whoops! Problem:'
2023 traceback.print_exc(file=sys.stderr)
2024
2025 # Arrays used for random selections in this demo
2026
2027 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2028 logging.ERROR, logging.CRITICAL]
2029
2030 LOGGERS = ['a.b.c', 'd.e.f']
2031
2032 MESSAGES = [
2033 'Random message #1',
2034 'Random message #2',
2035 'Random message #3',
2036 ]
2037
2038 # The worker configuration is done at the start of the worker process run.
2039 # Note that on Windows you can't rely on fork semantics, so each process
2040 # will run the logging configuration code when it starts.
2041 def worker_configurer(queue):
2042 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2043 root = logging.getLogger()
2044 root.addHandler(h)
2045 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2046
2047 # This is the worker process top-level loop, which just logs ten events with
2048 # random intervening delays before terminating.
2049 # The print messages are just so you know it's doing something!
2050 def worker_process(queue, configurer):
2051 configurer(queue)
2052 name = multiprocessing.current_process().name
2053 print('Worker started: %s' % name)
2054 for i in range(10):
2055 time.sleep(random())
2056 logger = logging.getLogger(choice(LOGGERS))
2057 level = choice(LEVELS)
2058 message = choice(MESSAGES)
2059 logger.log(level, message)
2060 print('Worker finished: %s' % name)
2061
2062 # Here's where the demo gets orchestrated. Create the queue, create and start
2063 # the listener, create ten workers and start them, wait for them to finish,
2064 # then send a None to the queue to tell the listener to finish.
2065 def main():
2066 queue = multiprocessing.Queue(-1)
2067 listener = multiprocessing.Process(target=listener_process,
2068 args=(queue, listener_configurer))
2069 listener.start()
2070 workers = []
2071 for i in range(10):
2072 worker = multiprocessing.Process(target=worker_process,
2073 args=(queue, worker_configurer))
2074 workers.append(worker)
2075 worker.start()
2076 for w in workers:
2077 w.join()
2078 queue.put_nowait(None)
2079 listener.join()
2080
2081 if __name__ == '__main__':
2082 main()
2083
2084
2085.. currentmodule:: logging
2086
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002087
Georg Brandl116aa622007-08-15 14:28:22 +00002088.. _network-logging:
2089
2090Sending and receiving logging events across a network
2091-----------------------------------------------------
2092
2093Let's say you want to send logging events across a network, and handle them at
2094the receiving end. A simple way of doing this is attaching a
2095:class:`SocketHandler` instance to the root logger at the sending end::
2096
2097 import logging, logging.handlers
2098
2099 rootLogger = logging.getLogger('')
2100 rootLogger.setLevel(logging.DEBUG)
2101 socketHandler = logging.handlers.SocketHandler('localhost',
2102 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2103 # don't bother with a formatter, since a socket handler sends the event as
2104 # an unformatted pickle
2105 rootLogger.addHandler(socketHandler)
2106
2107 # Now, we can log to the root logger, or any other logger. First the root...
2108 logging.info('Jackdaws love my big sphinx of quartz.')
2109
2110 # Now, define a couple of other loggers which might represent areas in your
2111 # application:
2112
2113 logger1 = logging.getLogger('myapp.area1')
2114 logger2 = logging.getLogger('myapp.area2')
2115
2116 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2117 logger1.info('How quickly daft jumping zebras vex.')
2118 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2119 logger2.error('The five boxing wizards jump quickly.')
2120
Alexandre Vassalottice261952008-05-12 02:31:37 +00002121At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002122module. Here is a basic working example::
2123
Georg Brandla35f4b92009-05-31 16:41:59 +00002124 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002125 import logging
2126 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002127 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002128 import struct
2129
2130
Alexandre Vassalottice261952008-05-12 02:31:37 +00002131 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002132 """Handler for a streaming logging request.
2133
2134 This basically logs the record using whatever logging policy is
2135 configured locally.
2136 """
2137
2138 def handle(self):
2139 """
2140 Handle multiple requests - each expected to be a 4-byte length,
2141 followed by the LogRecord in pickle format. Logs the record
2142 according to whatever policy is configured locally.
2143 """
Collin Winter46334482007-09-10 00:49:57 +00002144 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002145 chunk = self.connection.recv(4)
2146 if len(chunk) < 4:
2147 break
2148 slen = struct.unpack(">L", chunk)[0]
2149 chunk = self.connection.recv(slen)
2150 while len(chunk) < slen:
2151 chunk = chunk + self.connection.recv(slen - len(chunk))
2152 obj = self.unPickle(chunk)
2153 record = logging.makeLogRecord(obj)
2154 self.handleLogRecord(record)
2155
2156 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002157 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002158
2159 def handleLogRecord(self, record):
2160 # if a name is specified, we use the named logger rather than the one
2161 # implied by the record.
2162 if self.server.logname is not None:
2163 name = self.server.logname
2164 else:
2165 name = record.name
2166 logger = logging.getLogger(name)
2167 # N.B. EVERY record gets logged. This is because Logger.handle
2168 # is normally called AFTER logger-level filtering. If you want
2169 # to do filtering, do it at the client end to save wasting
2170 # cycles and network bandwidth!
2171 logger.handle(record)
2172
Alexandre Vassalottice261952008-05-12 02:31:37 +00002173 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00002174 """simple TCP socket-based logging receiver suitable for testing.
2175 """
2176
2177 allow_reuse_address = 1
2178
2179 def __init__(self, host='localhost',
2180 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2181 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002182 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002183 self.abort = 0
2184 self.timeout = 1
2185 self.logname = None
2186
2187 def serve_until_stopped(self):
2188 import select
2189 abort = 0
2190 while not abort:
2191 rd, wr, ex = select.select([self.socket.fileno()],
2192 [], [],
2193 self.timeout)
2194 if rd:
2195 self.handle_request()
2196 abort = self.abort
2197
2198 def main():
2199 logging.basicConfig(
2200 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
2201 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00002202 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00002203 tcpserver.serve_until_stopped()
2204
2205 if __name__ == "__main__":
2206 main()
2207
2208First run the server, and then the client. On the client side, nothing is
2209printed on the console; on the server side, you should see something like::
2210
2211 About to start TCP server...
2212 59 root INFO Jackdaws love my big sphinx of quartz.
2213 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2214 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2215 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2216 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2217
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002218Note that there are some security issues with pickle in some scenarios. If
2219these affect you, you can use an alternative serialization scheme by overriding
2220the :meth:`makePickle` method and implementing your alternative there, as
2221well as adapting the above script to use your alternative serialization.
2222
Vinay Sajip4039aff2010-09-11 10:25:28 +00002223.. _arbitrary-object-messages:
2224
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002225Using arbitrary objects as messages
2226-----------------------------------
2227
2228In the preceding sections and examples, it has been assumed that the message
2229passed when logging the event is a string. However, this is not the only
2230possibility. You can pass an arbitrary object as a message, and its
2231:meth:`__str__` method will be called when the logging system needs to convert
2232it to a string representation. In fact, if you want to, you can avoid
2233computing a string representation altogether - for example, the
2234:class:`SocketHandler` emits an event by pickling it and sending it over the
2235wire.
2236
Vinay Sajip55778922010-09-23 09:09:15 +00002237Dealing with handlers that block
2238--------------------------------
2239
2240.. currentmodule:: logging.handlers
2241
2242Sometimes you have to get your logging handlers to do their work without
2243blocking the thread you’re logging from. This is common in Web applications,
2244though of course it also occurs in other scenarios.
2245
2246A common culprit which demonstrates sluggish behaviour is the
2247:class:`SMTPHandler`: sending emails can take a long time, for a
2248number of reasons outside the developer’s control (for example, a poorly
2249performing mail or network infrastructure). But almost any network-based
2250handler can block: Even a :class:`SocketHandler` operation may do a
2251DNS query under the hood which is too slow (and this query can be deep in the
2252socket library code, below the Python layer, and outside your control).
2253
2254One solution is to use a two-part approach. For the first part, attach only a
2255:class:`QueueHandler` to those loggers which are accessed from
2256performance-critical threads. They simply write to their queue, which can be
2257sized to a large enough capacity or initialized with no upper bound to their
2258size. The write to the queue will typically be accepted quickly, though you
2259will probably need to catch the :ref:`queue.Full` exception as a precaution
2260in your code. If you are a library developer who has performance-critical
2261threads in their code, be sure to document this (together with a suggestion to
2262attach only ``QueueHandlers`` to your loggers) for the benefit of other
2263developers who will use your code.
2264
2265The second part of the solution is :class:`QueueListener`, which has been
2266designed as the counterpart to :class:`QueueHandler`. A
2267:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2268and it fires up an internal thread which listens to its queue for LogRecords
2269sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2270matter). The ``LogRecords`` are removed from the queue and passed to the
2271handlers for processing.
2272
2273The advantage of having a separate :class:`QueueListener` class is that you
2274can use the same instance to service multiple ``QueueHandlers``. This is more
2275resource-friendly than, say, having threaded versions of the existing handler
2276classes, which would eat up one thread per handler for no particular benefit.
2277
2278An example of using these two classes follows (imports omitted)::
2279
2280 que = queue.Queue(-1) # no limit on size
2281 queue_handler = QueueHandler(que)
2282 handler = logging.StreamHandler()
2283 listener = QueueListener(que, handler)
2284 root = logging.getLogger()
2285 root.addHandler(queue_handler)
2286 formatter = logging.Formatter('%(threadName)s: %(message)s')
2287 handler.setFormatter(formatter)
2288 listener.start()
2289 # The log output will display the thread which generated
2290 # the event (the main thread) rather than the internal
2291 # thread which monitors the internal queue. This is what
2292 # you want to happen.
2293 root.warning('Look out!')
2294 listener.stop()
2295
2296which, when run, will produce::
2297
2298 MainThread: Look out!
2299
2300
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002301Optimization
2302------------
2303
2304Formatting of message arguments is deferred until it cannot be avoided.
2305However, computing the arguments passed to the logging method can also be
2306expensive, and you may want to avoid doing it if the logger will just throw
2307away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2308method which takes a level argument and returns true if the event would be
2309created by the Logger for that level of call. You can write code like this::
2310
2311 if logger.isEnabledFor(logging.DEBUG):
2312 logger.debug("Message with %s, %s", expensive_func1(),
2313 expensive_func2())
2314
2315so that if the logger's threshold is set above ``DEBUG``, the calls to
2316:func:`expensive_func1` and :func:`expensive_func2` are never made.
2317
2318There are other optimizations which can be made for specific applications which
2319need more precise control over what logging information is collected. Here's a
2320list of things you can do to avoid processing during logging which you don't
2321need:
2322
2323+-----------------------------------------------+----------------------------------------+
2324| What you don't want to collect | How to avoid collecting it |
2325+===============================================+========================================+
2326| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2327+-----------------------------------------------+----------------------------------------+
2328| Threading information. | Set ``logging.logThreads`` to ``0``. |
2329+-----------------------------------------------+----------------------------------------+
2330| Process information. | Set ``logging.logProcesses`` to ``0``. |
2331+-----------------------------------------------+----------------------------------------+
2332
2333Also note that the core logging module only includes the basic handlers. If
2334you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2335take up any memory.
2336
2337.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002338
2339Handler Objects
2340---------------
2341
2342Handlers have the following attributes and methods. Note that :class:`Handler`
2343is never instantiated directly; this class acts as a base for more useful
2344subclasses. However, the :meth:`__init__` method in subclasses needs to call
2345:meth:`Handler.__init__`.
2346
2347
2348.. method:: Handler.__init__(level=NOTSET)
2349
2350 Initializes the :class:`Handler` instance by setting its level, setting the list
2351 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2352 serializing access to an I/O mechanism.
2353
2354
2355.. method:: Handler.createLock()
2356
2357 Initializes a thread lock which can be used to serialize access to underlying
2358 I/O functionality which may not be threadsafe.
2359
2360
2361.. method:: Handler.acquire()
2362
2363 Acquires the thread lock created with :meth:`createLock`.
2364
2365
2366.. method:: Handler.release()
2367
2368 Releases the thread lock acquired with :meth:`acquire`.
2369
2370
2371.. method:: Handler.setLevel(lvl)
2372
2373 Sets the threshold for this handler to *lvl*. Logging messages which are less
2374 severe than *lvl* will be ignored. When a handler is created, the level is set
2375 to :const:`NOTSET` (which causes all messages to be processed).
2376
2377
2378.. method:: Handler.setFormatter(form)
2379
2380 Sets the :class:`Formatter` for this handler to *form*.
2381
2382
2383.. method:: Handler.addFilter(filt)
2384
2385 Adds the specified filter *filt* to this handler.
2386
2387
2388.. method:: Handler.removeFilter(filt)
2389
2390 Removes the specified filter *filt* from this handler.
2391
2392
2393.. method:: Handler.filter(record)
2394
2395 Applies this handler's filters to the record and returns a true value if the
2396 record is to be processed.
2397
2398
2399.. method:: Handler.flush()
2400
2401 Ensure all logging output has been flushed. This version does nothing and is
2402 intended to be implemented by subclasses.
2403
2404
2405.. method:: Handler.close()
2406
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002407 Tidy up any resources used by the handler. This version does no output but
2408 removes the handler from an internal list of handlers which is closed when
2409 :func:`shutdown` is called. Subclasses should ensure that this gets called
2410 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002411
2412
2413.. method:: Handler.handle(record)
2414
2415 Conditionally emits the specified logging record, depending on filters which may
2416 have been added to the handler. Wraps the actual emission of the record with
2417 acquisition/release of the I/O thread lock.
2418
2419
2420.. method:: Handler.handleError(record)
2421
2422 This method should be called from handlers when an exception is encountered
2423 during an :meth:`emit` call. By default it does nothing, which means that
2424 exceptions get silently ignored. This is what is mostly wanted for a logging
2425 system - most users will not care about errors in the logging system, they are
2426 more interested in application errors. You could, however, replace this with a
2427 custom handler if you wish. The specified record is the one which was being
2428 processed when the exception occurred.
2429
2430
2431.. method:: Handler.format(record)
2432
2433 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2434 default formatter for the module.
2435
2436
2437.. method:: Handler.emit(record)
2438
2439 Do whatever it takes to actually log the specified logging record. This version
2440 is intended to be implemented by subclasses and so raises a
2441 :exc:`NotImplementedError`.
2442
2443
Vinay Sajipd31f3632010-06-29 15:31:15 +00002444.. _stream-handler:
2445
Georg Brandl116aa622007-08-15 14:28:22 +00002446StreamHandler
2447^^^^^^^^^^^^^
2448
2449The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2450sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2451file-like object (or, more precisely, any object which supports :meth:`write`
2452and :meth:`flush` methods).
2453
2454
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002455.. currentmodule:: logging
2456
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002457.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002458
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002459 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002460 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2461 will be used.
2462
2463
Benjamin Petersone41251e2008-04-25 01:59:09 +00002464 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002465
Benjamin Petersone41251e2008-04-25 01:59:09 +00002466 If a formatter is specified, it is used to format the record. The record
2467 is then written to the stream with a trailing newline. If exception
2468 information is present, it is formatted using
2469 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002470
2471
Benjamin Petersone41251e2008-04-25 01:59:09 +00002472 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002473
Benjamin Petersone41251e2008-04-25 01:59:09 +00002474 Flushes the stream by calling its :meth:`flush` method. Note that the
2475 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002476 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002477
Vinay Sajip05ed6952010-10-20 20:34:09 +00002478.. versionchanged:: 3.2
2479 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2480 value ``"\n"``, which is used as the terminator when writing a formatted
2481 record to a stream. If you don't want this newline termination, you can
2482 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002483
Vinay Sajipd31f3632010-06-29 15:31:15 +00002484.. _file-handler:
2485
Georg Brandl116aa622007-08-15 14:28:22 +00002486FileHandler
2487^^^^^^^^^^^
2488
2489The :class:`FileHandler` class, located in the core :mod:`logging` package,
2490sends logging output to a disk file. It inherits the output functionality from
2491:class:`StreamHandler`.
2492
2493
Vinay Sajipd31f3632010-06-29 15:31:15 +00002494.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002495
2496 Returns a new instance of the :class:`FileHandler` class. The specified file is
2497 opened and used as the stream for logging. If *mode* is not specified,
2498 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002499 with that encoding. If *delay* is true, then file opening is deferred until the
2500 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002501
2502
Benjamin Petersone41251e2008-04-25 01:59:09 +00002503 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002504
Benjamin Petersone41251e2008-04-25 01:59:09 +00002505 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002506
2507
Benjamin Petersone41251e2008-04-25 01:59:09 +00002508 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002509
Benjamin Petersone41251e2008-04-25 01:59:09 +00002510 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002511
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002512
Vinay Sajipd31f3632010-06-29 15:31:15 +00002513.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002514
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002515NullHandler
2516^^^^^^^^^^^
2517
2518.. versionadded:: 3.1
2519
2520The :class:`NullHandler` class, located in the core :mod:`logging` package,
2521does not do any formatting or output. It is essentially a "no-op" handler
2522for use by library developers.
2523
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002524.. class:: NullHandler()
2525
2526 Returns a new instance of the :class:`NullHandler` class.
2527
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002528 .. method:: emit(record)
2529
2530 This method does nothing.
2531
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002532 .. method:: handle(record)
2533
2534 This method does nothing.
2535
2536 .. method:: createLock()
2537
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002538 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002539 underlying I/O to which access needs to be serialized.
2540
2541
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002542See :ref:`library-config` for more information on how to use
2543:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002544
Vinay Sajipd31f3632010-06-29 15:31:15 +00002545.. _watched-file-handler:
2546
Georg Brandl116aa622007-08-15 14:28:22 +00002547WatchedFileHandler
2548^^^^^^^^^^^^^^^^^^
2549
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002550.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002551
Georg Brandl116aa622007-08-15 14:28:22 +00002552The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2553module, is a :class:`FileHandler` which watches the file it is logging to. If
2554the file changes, it is closed and reopened using the file name.
2555
2556A file change can happen because of usage of programs such as *newsyslog* and
2557*logrotate* which perform log file rotation. This handler, intended for use
2558under Unix/Linux, watches the file to see if it has changed since the last emit.
2559(A file is deemed to have changed if its device or inode have changed.) If the
2560file has changed, the old file stream is closed, and the file opened to get a
2561new stream.
2562
2563This handler is not appropriate for use under Windows, because under Windows
2564open log files cannot be moved or renamed - logging opens the files with
2565exclusive locks - and so there is no need for such a handler. Furthermore,
2566*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2567this value.
2568
2569
Christian Heimese7a15bb2008-01-24 16:21:45 +00002570.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002571
2572 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2573 file is opened and used as the stream for logging. If *mode* is not specified,
2574 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002575 with that encoding. If *delay* is true, then file opening is deferred until the
2576 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002577
2578
Benjamin Petersone41251e2008-04-25 01:59:09 +00002579 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002580
Benjamin Petersone41251e2008-04-25 01:59:09 +00002581 Outputs the record to the file, but first checks to see if the file has
2582 changed. If it has, the existing stream is flushed and closed and the
2583 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002584
Vinay Sajipd31f3632010-06-29 15:31:15 +00002585.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002586
2587RotatingFileHandler
2588^^^^^^^^^^^^^^^^^^^
2589
2590The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2591module, supports rotation of disk log files.
2592
2593
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002594.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002595
2596 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2597 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002598 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2599 with that encoding. If *delay* is true, then file opening is deferred until the
2600 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002601
2602 You can use the *maxBytes* and *backupCount* values to allow the file to
2603 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2604 the file is closed and a new file is silently opened for output. Rollover occurs
2605 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2606 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2607 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2608 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2609 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2610 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2611 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2612 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2613 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2614
2615
Benjamin Petersone41251e2008-04-25 01:59:09 +00002616 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002617
Benjamin Petersone41251e2008-04-25 01:59:09 +00002618 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002619
2620
Benjamin Petersone41251e2008-04-25 01:59:09 +00002621 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002622
Benjamin Petersone41251e2008-04-25 01:59:09 +00002623 Outputs the record to the file, catering for rollover as described
2624 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002625
Vinay Sajipd31f3632010-06-29 15:31:15 +00002626.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002627
2628TimedRotatingFileHandler
2629^^^^^^^^^^^^^^^^^^^^^^^^
2630
2631The :class:`TimedRotatingFileHandler` class, located in the
2632:mod:`logging.handlers` module, supports rotation of disk log files at certain
2633timed intervals.
2634
2635
Vinay Sajipd31f3632010-06-29 15:31:15 +00002636.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002637
2638 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2639 specified file is opened and used as the stream for logging. On rotating it also
2640 sets the filename suffix. Rotating happens based on the product of *when* and
2641 *interval*.
2642
2643 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002644 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002645
Christian Heimesb558a2e2008-03-02 22:46:37 +00002646 +----------------+-----------------------+
2647 | Value | Type of interval |
2648 +================+=======================+
2649 | ``'S'`` | Seconds |
2650 +----------------+-----------------------+
2651 | ``'M'`` | Minutes |
2652 +----------------+-----------------------+
2653 | ``'H'`` | Hours |
2654 +----------------+-----------------------+
2655 | ``'D'`` | Days |
2656 +----------------+-----------------------+
2657 | ``'W'`` | Week day (0=Monday) |
2658 +----------------+-----------------------+
2659 | ``'midnight'`` | Roll over at midnight |
2660 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002661
Christian Heimesb558a2e2008-03-02 22:46:37 +00002662 The system will save old log files by appending extensions to the filename.
2663 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002664 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002665 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002666
2667 When computing the next rollover time for the first time (when the handler
2668 is created), the last modification time of an existing log file, or else
2669 the current time, is used to compute when the next rotation will occur.
2670
Georg Brandl0c77a822008-06-10 16:37:50 +00002671 If the *utc* argument is true, times in UTC will be used; otherwise
2672 local time is used.
2673
2674 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002675 will be kept, and if more would be created when rollover occurs, the oldest
2676 one is deleted. The deletion logic uses the interval to determine which
2677 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002678
Vinay Sajipd31f3632010-06-29 15:31:15 +00002679 If *delay* is true, then file opening is deferred until the first call to
2680 :meth:`emit`.
2681
Georg Brandl116aa622007-08-15 14:28:22 +00002682
Benjamin Petersone41251e2008-04-25 01:59:09 +00002683 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002684
Benjamin Petersone41251e2008-04-25 01:59:09 +00002685 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002686
2687
Benjamin Petersone41251e2008-04-25 01:59:09 +00002688 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002689
Benjamin Petersone41251e2008-04-25 01:59:09 +00002690 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002691
2692
Vinay Sajipd31f3632010-06-29 15:31:15 +00002693.. _socket-handler:
2694
Georg Brandl116aa622007-08-15 14:28:22 +00002695SocketHandler
2696^^^^^^^^^^^^^
2697
2698The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2699sends logging output to a network socket. The base class uses a TCP socket.
2700
2701
2702.. class:: SocketHandler(host, port)
2703
2704 Returns a new instance of the :class:`SocketHandler` class intended to
2705 communicate with a remote machine whose address is given by *host* and *port*.
2706
2707
Benjamin Petersone41251e2008-04-25 01:59:09 +00002708 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002709
Benjamin Petersone41251e2008-04-25 01:59:09 +00002710 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002711
2712
Benjamin Petersone41251e2008-04-25 01:59:09 +00002713 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002714
Benjamin Petersone41251e2008-04-25 01:59:09 +00002715 Pickles the record's attribute dictionary and writes it to the socket in
2716 binary format. If there is an error with the socket, silently drops the
2717 packet. If the connection was previously lost, re-establishes the
2718 connection. To unpickle the record at the receiving end into a
2719 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002720
2721
Benjamin Petersone41251e2008-04-25 01:59:09 +00002722 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002723
Benjamin Petersone41251e2008-04-25 01:59:09 +00002724 Handles an error which has occurred during :meth:`emit`. The most likely
2725 cause is a lost connection. Closes the socket so that we can retry on the
2726 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002727
2728
Benjamin Petersone41251e2008-04-25 01:59:09 +00002729 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002730
Benjamin Petersone41251e2008-04-25 01:59:09 +00002731 This is a factory method which allows subclasses to define the precise
2732 type of socket they want. The default implementation creates a TCP socket
2733 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002734
2735
Benjamin Petersone41251e2008-04-25 01:59:09 +00002736 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002737
Benjamin Petersone41251e2008-04-25 01:59:09 +00002738 Pickles the record's attribute dictionary in binary format with a length
2739 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002740
Vinay Sajipd31f3632010-06-29 15:31:15 +00002741 Note that pickles aren't completely secure. If you are concerned about
2742 security, you may want to override this method to implement a more secure
2743 mechanism. For example, you can sign pickles using HMAC and then verify
2744 them on the receiving end, or alternatively you can disable unpickling of
2745 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002746
Benjamin Petersone41251e2008-04-25 01:59:09 +00002747 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002748
Benjamin Petersone41251e2008-04-25 01:59:09 +00002749 Send a pickled string *packet* to the socket. This function allows for
2750 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002751
2752
Vinay Sajipd31f3632010-06-29 15:31:15 +00002753.. _datagram-handler:
2754
Georg Brandl116aa622007-08-15 14:28:22 +00002755DatagramHandler
2756^^^^^^^^^^^^^^^
2757
2758The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2759module, inherits from :class:`SocketHandler` to support sending logging messages
2760over UDP sockets.
2761
2762
2763.. class:: DatagramHandler(host, port)
2764
2765 Returns a new instance of the :class:`DatagramHandler` class intended to
2766 communicate with a remote machine whose address is given by *host* and *port*.
2767
2768
Benjamin Petersone41251e2008-04-25 01:59:09 +00002769 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002770
Benjamin Petersone41251e2008-04-25 01:59:09 +00002771 Pickles the record's attribute dictionary and writes it to the socket in
2772 binary format. If there is an error with the socket, silently drops the
2773 packet. To unpickle the record at the receiving end into a
2774 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002775
2776
Benjamin Petersone41251e2008-04-25 01:59:09 +00002777 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002778
Benjamin Petersone41251e2008-04-25 01:59:09 +00002779 The factory method of :class:`SocketHandler` is here overridden to create
2780 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002781
2782
Benjamin Petersone41251e2008-04-25 01:59:09 +00002783 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002784
Benjamin Petersone41251e2008-04-25 01:59:09 +00002785 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002786
2787
Vinay Sajipd31f3632010-06-29 15:31:15 +00002788.. _syslog-handler:
2789
Georg Brandl116aa622007-08-15 14:28:22 +00002790SysLogHandler
2791^^^^^^^^^^^^^
2792
2793The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2794supports sending logging messages to a remote or local Unix syslog.
2795
2796
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002797.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002798
2799 Returns a new instance of the :class:`SysLogHandler` class intended to
2800 communicate with a remote Unix machine whose address is given by *address* in
2801 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002802 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002803 alternative to providing a ``(host, port)`` tuple is providing an address as a
2804 string, for example "/dev/log". In this case, a Unix domain socket is used to
2805 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002806 :const:`LOG_USER` is used. The type of socket opened depends on the
2807 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2808 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2809 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2810
Vinay Sajip972412d2010-09-23 20:31:24 +00002811 Note that if your server is not listening on UDP port 514,
2812 :class:`SysLogHandler` may appear not to work. In that case, check what
2813 address you should be using for a domain socket - it's system dependent.
2814 For example, on Linux it's usually "/dev/log" but on OS/X it's
2815 "/var/run/syslog". You'll need to check your platform and use the
2816 appropriate address (you may need to do this check at runtime if your
2817 application needs to run on several platforms). On Windows, you pretty
2818 much have to use the UDP option.
2819
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002820 .. versionchanged:: 3.2
2821 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002822
2823
Benjamin Petersone41251e2008-04-25 01:59:09 +00002824 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002825
Benjamin Petersone41251e2008-04-25 01:59:09 +00002826 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002827
2828
Benjamin Petersone41251e2008-04-25 01:59:09 +00002829 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002830
Benjamin Petersone41251e2008-04-25 01:59:09 +00002831 The record is formatted, and then sent to the syslog server. If exception
2832 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002833
2834
Benjamin Petersone41251e2008-04-25 01:59:09 +00002835 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002836
Benjamin Petersone41251e2008-04-25 01:59:09 +00002837 Encodes the facility and priority into an integer. You can pass in strings
2838 or integers - if strings are passed, internal mapping dictionaries are
2839 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002840
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002841 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2842 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002843
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002844 **Priorities**
2845
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002846 +--------------------------+---------------+
2847 | Name (string) | Symbolic value|
2848 +==========================+===============+
2849 | ``alert`` | LOG_ALERT |
2850 +--------------------------+---------------+
2851 | ``crit`` or ``critical`` | LOG_CRIT |
2852 +--------------------------+---------------+
2853 | ``debug`` | LOG_DEBUG |
2854 +--------------------------+---------------+
2855 | ``emerg`` or ``panic`` | LOG_EMERG |
2856 +--------------------------+---------------+
2857 | ``err`` or ``error`` | LOG_ERR |
2858 +--------------------------+---------------+
2859 | ``info`` | LOG_INFO |
2860 +--------------------------+---------------+
2861 | ``notice`` | LOG_NOTICE |
2862 +--------------------------+---------------+
2863 | ``warn`` or ``warning`` | LOG_WARNING |
2864 +--------------------------+---------------+
2865
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002866 **Facilities**
2867
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002868 +---------------+---------------+
2869 | Name (string) | Symbolic value|
2870 +===============+===============+
2871 | ``auth`` | LOG_AUTH |
2872 +---------------+---------------+
2873 | ``authpriv`` | LOG_AUTHPRIV |
2874 +---------------+---------------+
2875 | ``cron`` | LOG_CRON |
2876 +---------------+---------------+
2877 | ``daemon`` | LOG_DAEMON |
2878 +---------------+---------------+
2879 | ``ftp`` | LOG_FTP |
2880 +---------------+---------------+
2881 | ``kern`` | LOG_KERN |
2882 +---------------+---------------+
2883 | ``lpr`` | LOG_LPR |
2884 +---------------+---------------+
2885 | ``mail`` | LOG_MAIL |
2886 +---------------+---------------+
2887 | ``news`` | LOG_NEWS |
2888 +---------------+---------------+
2889 | ``syslog`` | LOG_SYSLOG |
2890 +---------------+---------------+
2891 | ``user`` | LOG_USER |
2892 +---------------+---------------+
2893 | ``uucp`` | LOG_UUCP |
2894 +---------------+---------------+
2895 | ``local0`` | LOG_LOCAL0 |
2896 +---------------+---------------+
2897 | ``local1`` | LOG_LOCAL1 |
2898 +---------------+---------------+
2899 | ``local2`` | LOG_LOCAL2 |
2900 +---------------+---------------+
2901 | ``local3`` | LOG_LOCAL3 |
2902 +---------------+---------------+
2903 | ``local4`` | LOG_LOCAL4 |
2904 +---------------+---------------+
2905 | ``local5`` | LOG_LOCAL5 |
2906 +---------------+---------------+
2907 | ``local6`` | LOG_LOCAL6 |
2908 +---------------+---------------+
2909 | ``local7`` | LOG_LOCAL7 |
2910 +---------------+---------------+
2911
2912 .. method:: mapPriority(levelname)
2913
2914 Maps a logging level name to a syslog priority name.
2915 You may need to override this if you are using custom levels, or
2916 if the default algorithm is not suitable for your needs. The
2917 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2918 ``CRITICAL`` to the equivalent syslog names, and all other level
2919 names to "warning".
2920
2921.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002922
2923NTEventLogHandler
2924^^^^^^^^^^^^^^^^^
2925
2926The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2927module, supports sending logging messages to a local Windows NT, Windows 2000 or
2928Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2929extensions for Python installed.
2930
2931
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002932.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002933
2934 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2935 used to define the application name as it appears in the event log. An
2936 appropriate registry entry is created using this name. The *dllname* should give
2937 the fully qualified pathname of a .dll or .exe which contains message
2938 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
2939 - this is installed with the Win32 extensions and contains some basic
2940 placeholder message definitions. Note that use of these placeholders will make
2941 your event logs big, as the entire message source is held in the log. If you
2942 want slimmer logs, you have to pass in the name of your own .dll or .exe which
2943 contains the message definitions you want to use in the event log). The
2944 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
2945 defaults to ``'Application'``.
2946
2947
Benjamin Petersone41251e2008-04-25 01:59:09 +00002948 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002949
Benjamin Petersone41251e2008-04-25 01:59:09 +00002950 At this point, you can remove the application name from the registry as a
2951 source of event log entries. However, if you do this, you will not be able
2952 to see the events as you intended in the Event Log Viewer - it needs to be
2953 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002954 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00002955
2956
Benjamin Petersone41251e2008-04-25 01:59:09 +00002957 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002958
Benjamin Petersone41251e2008-04-25 01:59:09 +00002959 Determines the message ID, event category and event type, and then logs
2960 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00002961
2962
Benjamin Petersone41251e2008-04-25 01:59:09 +00002963 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002964
Benjamin Petersone41251e2008-04-25 01:59:09 +00002965 Returns the event category for the record. Override this if you want to
2966 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00002967
2968
Benjamin Petersone41251e2008-04-25 01:59:09 +00002969 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002970
Benjamin Petersone41251e2008-04-25 01:59:09 +00002971 Returns the event type for the record. Override this if you want to
2972 specify your own types. This version does a mapping using the handler's
2973 typemap attribute, which is set up in :meth:`__init__` to a dictionary
2974 which contains mappings for :const:`DEBUG`, :const:`INFO`,
2975 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
2976 your own levels, you will either need to override this method or place a
2977 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002978
2979
Benjamin Petersone41251e2008-04-25 01:59:09 +00002980 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002981
Benjamin Petersone41251e2008-04-25 01:59:09 +00002982 Returns the message ID for the record. If you are using your own messages,
2983 you could do this by having the *msg* passed to the logger being an ID
2984 rather than a format string. Then, in here, you could use a dictionary
2985 lookup to get the message ID. This version returns 1, which is the base
2986 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00002987
Vinay Sajipd31f3632010-06-29 15:31:15 +00002988.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002989
2990SMTPHandler
2991^^^^^^^^^^^
2992
2993The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
2994supports sending logging messages to an email address via SMTP.
2995
2996
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002997.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002998
2999 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3000 initialized with the from and to addresses and subject line of the email. The
3001 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3002 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3003 the standard SMTP port is used. If your SMTP server requires authentication, you
3004 can specify a (username, password) tuple for the *credentials* argument.
3005
Georg Brandl116aa622007-08-15 14:28:22 +00003006
Benjamin Petersone41251e2008-04-25 01:59:09 +00003007 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003008
Benjamin Petersone41251e2008-04-25 01:59:09 +00003009 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003010
3011
Benjamin Petersone41251e2008-04-25 01:59:09 +00003012 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003013
Benjamin Petersone41251e2008-04-25 01:59:09 +00003014 If you want to specify a subject line which is record-dependent, override
3015 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003016
Vinay Sajipd31f3632010-06-29 15:31:15 +00003017.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003018
3019MemoryHandler
3020^^^^^^^^^^^^^
3021
3022The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3023supports buffering of logging records in memory, periodically flushing them to a
3024:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3025event of a certain severity or greater is seen.
3026
3027:class:`MemoryHandler` is a subclass of the more general
3028:class:`BufferingHandler`, which is an abstract class. This buffers logging
3029records in memory. Whenever each record is added to the buffer, a check is made
3030by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3031should, then :meth:`flush` is expected to do the needful.
3032
3033
3034.. class:: BufferingHandler(capacity)
3035
3036 Initializes the handler with a buffer of the specified capacity.
3037
3038
Benjamin Petersone41251e2008-04-25 01:59:09 +00003039 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003040
Benjamin Petersone41251e2008-04-25 01:59:09 +00003041 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3042 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003043
3044
Benjamin Petersone41251e2008-04-25 01:59:09 +00003045 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003046
Benjamin Petersone41251e2008-04-25 01:59:09 +00003047 You can override this to implement custom flushing behavior. This version
3048 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003049
3050
Benjamin Petersone41251e2008-04-25 01:59:09 +00003051 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003052
Benjamin Petersone41251e2008-04-25 01:59:09 +00003053 Returns true if the buffer is up to capacity. This method can be
3054 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003055
3056
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003057.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003058
3059 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3060 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3061 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3062 set using :meth:`setTarget` before this handler does anything useful.
3063
3064
Benjamin Petersone41251e2008-04-25 01:59:09 +00003065 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003066
Benjamin Petersone41251e2008-04-25 01:59:09 +00003067 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3068 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003069
3070
Benjamin Petersone41251e2008-04-25 01:59:09 +00003071 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003072
Benjamin Petersone41251e2008-04-25 01:59:09 +00003073 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003074 records to the target, if there is one. The buffer is also cleared when
3075 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003076
3077
Benjamin Petersone41251e2008-04-25 01:59:09 +00003078 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003079
Benjamin Petersone41251e2008-04-25 01:59:09 +00003080 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003081
3082
Benjamin Petersone41251e2008-04-25 01:59:09 +00003083 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003084
Benjamin Petersone41251e2008-04-25 01:59:09 +00003085 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003086
3087
Vinay Sajipd31f3632010-06-29 15:31:15 +00003088.. _http-handler:
3089
Georg Brandl116aa622007-08-15 14:28:22 +00003090HTTPHandler
3091^^^^^^^^^^^
3092
3093The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3094supports sending logging messages to a Web server, using either ``GET`` or
3095``POST`` semantics.
3096
3097
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003098.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003099
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003100 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3101 of the form ``host:port``, should you need to use a specific port number.
3102 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3103 connection will be used. If *credentials* is specified, it should be a
3104 2-tuple consisting of userid and password, which will be placed in an HTTP
3105 'Authorization' header using Basic authentication. If you specify
3106 credentials, you should also specify secure=True so that your userid and
3107 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003108
3109
Benjamin Petersone41251e2008-04-25 01:59:09 +00003110 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003111
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003112 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003113
3114
Vinay Sajip121a1c42010-09-08 10:46:15 +00003115.. _queue-handler:
3116
3117
3118QueueHandler
3119^^^^^^^^^^^^
3120
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003121.. versionadded:: 3.2
3122
Vinay Sajip121a1c42010-09-08 10:46:15 +00003123The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3124supports sending logging messages to a queue, such as those implemented in the
3125:mod:`queue` or :mod:`multiprocessing` modules.
3126
Vinay Sajip0637d492010-09-23 08:15:54 +00003127Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3128to let handlers do their work on a separate thread from the one which does the
3129logging. This is important in Web applications and also other service
3130applications where threads servicing clients need to respond as quickly as
3131possible, while any potentially slow operations (such as sending an email via
3132:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003133
3134.. class:: QueueHandler(queue)
3135
3136 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003137 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003138 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003139 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003140
3141
3142 .. method:: emit(record)
3143
Vinay Sajip0258ce82010-09-22 20:34:53 +00003144 Enqueues the result of preparing the LogRecord.
3145
3146 .. method:: prepare(record)
3147
3148 Prepares a record for queuing. The object returned by this
3149 method is enqueued.
3150
3151 The base implementation formats the record to merge the message
3152 and arguments, and removes unpickleable items from the record
3153 in-place.
3154
3155 You might want to override this method if you want to convert
3156 the record to a dict or JSON string, or send a modified copy
3157 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003158
3159 .. method:: enqueue(record)
3160
3161 Enqueues the record on the queue using ``put_nowait()``; you may
3162 want to override this if you want to use blocking behaviour, or a
3163 timeout, or a customised queue implementation.
3164
3165
Vinay Sajip121a1c42010-09-08 10:46:15 +00003166
Vinay Sajip0637d492010-09-23 08:15:54 +00003167.. queue-listener:
3168
3169QueueListener
3170^^^^^^^^^^^^^
3171
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003172.. versionadded:: 3.2
3173
Vinay Sajip0637d492010-09-23 08:15:54 +00003174The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3175module, supports receiving logging messages from a queue, such as those
3176implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3177messages are received from a queue in an internal thread and passed, on
3178the same thread, to one or more handlers for processing.
3179
3180Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3181to let handlers do their work on a separate thread from the one which does the
3182logging. This is important in Web applications and also other service
3183applications where threads servicing clients need to respond as quickly as
3184possible, while any potentially slow operations (such as sending an email via
3185:class:`SMTPHandler`) are done on a separate thread.
3186
3187.. class:: QueueListener(queue, *handlers)
3188
3189 Returns a new instance of the :class:`QueueListener` class. The instance is
3190 initialized with the queue to send messages to and a list of handlers which
3191 will handle entries placed on the queue. The queue can be any queue-
3192 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3193 to know how to get messages from it.
3194
3195 .. method:: dequeue(block)
3196
3197 Dequeues a record and return it, optionally blocking.
3198
3199 The base implementation uses ``get()``. You may want to override this
3200 method if you want to use timeouts or work with custom queue
3201 implementations.
3202
3203 .. method:: prepare(record)
3204
3205 Prepare a record for handling.
3206
3207 This implementation just returns the passed-in record. You may want to
3208 override this method if you need to do any custom marshalling or
3209 manipulation of the record before passing it to the handlers.
3210
3211 .. method:: handle(record)
3212
3213 Handle a record.
3214
3215 This just loops through the handlers offering them the record
3216 to handle. The actual object passed to the handlers is that which
3217 is returned from :meth:`prepare`.
3218
3219 .. method:: start()
3220
3221 Starts the listener.
3222
3223 This starts up a background thread to monitor the queue for
3224 LogRecords to process.
3225
3226 .. method:: stop()
3227
3228 Stops the listener.
3229
3230 This asks the thread to terminate, and then waits for it to do so.
3231 Note that if you don't call this before your application exits, there
3232 may be some records still left on the queue, which won't be processed.
3233
Vinay Sajip0637d492010-09-23 08:15:54 +00003234
Vinay Sajip63891ed2010-09-13 20:02:39 +00003235.. _zeromq-handlers:
3236
Vinay Sajip0637d492010-09-23 08:15:54 +00003237Subclassing QueueHandler
3238^^^^^^^^^^^^^^^^^^^^^^^^
3239
Vinay Sajip63891ed2010-09-13 20:02:39 +00003240You can use a :class:`QueueHandler` subclass to send messages to other kinds
3241of queues, for example a ZeroMQ "publish" socket. In the example below,the
3242socket is created separately and passed to the handler (as its 'queue')::
3243
3244 import zmq # using pyzmq, the Python binding for ZeroMQ
3245 import json # for serializing records portably
3246
3247 ctx = zmq.Context()
3248 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3249 sock.bind('tcp://*:5556') # or wherever
3250
3251 class ZeroMQSocketHandler(QueueHandler):
3252 def enqueue(self, record):
3253 data = json.dumps(record.__dict__)
3254 self.queue.send(data)
3255
Vinay Sajip0055c422010-09-14 09:42:39 +00003256 handler = ZeroMQSocketHandler(sock)
3257
3258
Vinay Sajip63891ed2010-09-13 20:02:39 +00003259Of course there are other ways of organizing this, for example passing in the
3260data needed by the handler to create the socket::
3261
3262 class ZeroMQSocketHandler(QueueHandler):
3263 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3264 self.ctx = ctx or zmq.Context()
3265 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003266 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003267 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003268
3269 def enqueue(self, record):
3270 data = json.dumps(record.__dict__)
3271 self.queue.send(data)
3272
Vinay Sajipde726922010-09-14 06:59:24 +00003273 def close(self):
3274 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003275
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003276
Vinay Sajip0637d492010-09-23 08:15:54 +00003277Subclassing QueueListener
3278^^^^^^^^^^^^^^^^^^^^^^^^^
3279
3280You can also subclass :class:`QueueListener` to get messages from other kinds
3281of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
3282
3283 class ZeroMQSocketListener(QueueListener):
3284 def __init__(self, uri, *handlers, **kwargs):
3285 self.ctx = kwargs.get('ctx') or zmq.Context()
3286 socket = zmq.Socket(self.ctx, zmq.SUB)
3287 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3288 socket.connect(uri)
3289
3290 def dequeue(self):
3291 msg = self.queue.recv()
3292 return logging.makeLogRecord(json.loads(msg))
3293
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003294
Christian Heimes8b0facf2007-12-04 19:30:01 +00003295.. _formatter-objects:
3296
Georg Brandl116aa622007-08-15 14:28:22 +00003297Formatter Objects
3298-----------------
3299
Benjamin Peterson75edad02009-01-01 15:05:06 +00003300.. currentmodule:: logging
3301
Georg Brandl116aa622007-08-15 14:28:22 +00003302:class:`Formatter`\ s have the following attributes and methods. They are
3303responsible for converting a :class:`LogRecord` to (usually) a string which can
3304be interpreted by either a human or an external system. The base
3305:class:`Formatter` allows a formatting string to be specified. If none is
3306supplied, the default value of ``'%(message)s'`` is used.
3307
3308A Formatter can be initialized with a format string which makes use of knowledge
3309of the :class:`LogRecord` attributes - such as the default value mentioned above
3310making use of the fact that the user's message and arguments are pre-formatted
3311into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003312standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003313for more information on string formatting.
3314
3315Currently, the useful mapping keys in a :class:`LogRecord` are:
3316
3317+-------------------------+-----------------------------------------------+
3318| Format | Description |
3319+=========================+===============================================+
3320| ``%(name)s`` | Name of the logger (logging channel). |
3321+-------------------------+-----------------------------------------------+
3322| ``%(levelno)s`` | Numeric logging level for the message |
3323| | (:const:`DEBUG`, :const:`INFO`, |
3324| | :const:`WARNING`, :const:`ERROR`, |
3325| | :const:`CRITICAL`). |
3326+-------------------------+-----------------------------------------------+
3327| ``%(levelname)s`` | Text logging level for the message |
3328| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3329| | ``'ERROR'``, ``'CRITICAL'``). |
3330+-------------------------+-----------------------------------------------+
3331| ``%(pathname)s`` | Full pathname of the source file where the |
3332| | logging call was issued (if available). |
3333+-------------------------+-----------------------------------------------+
3334| ``%(filename)s`` | Filename portion of pathname. |
3335+-------------------------+-----------------------------------------------+
3336| ``%(module)s`` | Module (name portion of filename). |
3337+-------------------------+-----------------------------------------------+
3338| ``%(funcName)s`` | Name of function containing the logging call. |
3339+-------------------------+-----------------------------------------------+
3340| ``%(lineno)d`` | Source line number where the logging call was |
3341| | issued (if available). |
3342+-------------------------+-----------------------------------------------+
3343| ``%(created)f`` | Time when the :class:`LogRecord` was created |
3344| | (as returned by :func:`time.time`). |
3345+-------------------------+-----------------------------------------------+
3346| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3347| | created, relative to the time the logging |
3348| | module was loaded. |
3349+-------------------------+-----------------------------------------------+
3350| ``%(asctime)s`` | Human-readable time when the |
3351| | :class:`LogRecord` was created. By default |
3352| | this is of the form "2003-07-08 16:49:45,896" |
3353| | (the numbers after the comma are millisecond |
3354| | portion of the time). |
3355+-------------------------+-----------------------------------------------+
3356| ``%(msecs)d`` | Millisecond portion of the time when the |
3357| | :class:`LogRecord` was created. |
3358+-------------------------+-----------------------------------------------+
3359| ``%(thread)d`` | Thread ID (if available). |
3360+-------------------------+-----------------------------------------------+
3361| ``%(threadName)s`` | Thread name (if available). |
3362+-------------------------+-----------------------------------------------+
3363| ``%(process)d`` | Process ID (if available). |
3364+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003365| ``%(processName)s`` | Process name (if available). |
3366+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003367| ``%(message)s`` | The logged message, computed as ``msg % |
3368| | args``. |
3369+-------------------------+-----------------------------------------------+
3370
Georg Brandl116aa622007-08-15 14:28:22 +00003371
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003372.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003373
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003374 Returns a new instance of the :class:`Formatter` class. The instance is
3375 initialized with a format string for the message as a whole, as well as a
3376 format string for the date/time portion of a message. If no *fmt* is
3377 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3378 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003379
Benjamin Petersone41251e2008-04-25 01:59:09 +00003380 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003381
Benjamin Petersone41251e2008-04-25 01:59:09 +00003382 The record's attribute dictionary is used as the operand to a string
3383 formatting operation. Returns the resulting string. Before formatting the
3384 dictionary, a couple of preparatory steps are carried out. The *message*
3385 attribute of the record is computed using *msg* % *args*. If the
3386 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3387 to format the event time. If there is exception information, it is
3388 formatted using :meth:`formatException` and appended to the message. Note
3389 that the formatted exception information is cached in attribute
3390 *exc_text*. This is useful because the exception information can be
3391 pickled and sent across the wire, but you should be careful if you have
3392 more than one :class:`Formatter` subclass which customizes the formatting
3393 of exception information. In this case, you will have to clear the cached
3394 value after a formatter has done its formatting, so that the next
3395 formatter to handle the event doesn't use the cached value but
3396 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003397
Vinay Sajip8593ae62010-11-14 21:33:04 +00003398 If stack information is available, it's appended after the exception
3399 information, using :meth:`formatStack` to transform it if necessary.
3400
Georg Brandl116aa622007-08-15 14:28:22 +00003401
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003402 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003403
Benjamin Petersone41251e2008-04-25 01:59:09 +00003404 This method should be called from :meth:`format` by a formatter which
3405 wants to make use of a formatted time. This method can be overridden in
3406 formatters to provide for any specific requirement, but the basic behavior
3407 is as follows: if *datefmt* (a string) is specified, it is used with
3408 :func:`time.strftime` to format the creation time of the
3409 record. Otherwise, the ISO8601 format is used. The resulting string is
3410 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003411
3412
Benjamin Petersone41251e2008-04-25 01:59:09 +00003413 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003414
Benjamin Petersone41251e2008-04-25 01:59:09 +00003415 Formats the specified exception information (a standard exception tuple as
3416 returned by :func:`sys.exc_info`) as a string. This default implementation
3417 just uses :func:`traceback.print_exception`. The resulting string is
3418 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003419
Vinay Sajip8593ae62010-11-14 21:33:04 +00003420 .. method:: formatStack(stack_info)
3421
3422 Formats the specified stack information (a string as returned by
3423 :func:`traceback.print_stack`, but with the last newline removed) as a
3424 string. This default implementation just returns the input value.
3425
Vinay Sajipd31f3632010-06-29 15:31:15 +00003426.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003427
3428Filter Objects
3429--------------
3430
Georg Brandl5c66bca2010-10-29 05:36:28 +00003431``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003432filtering than is provided by levels. The base filter class only allows events
3433which are below a certain point in the logger hierarchy. For example, a filter
3434initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3435"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3436empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003437
3438
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003439.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003440
3441 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3442 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003443 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003444
3445
Benjamin Petersone41251e2008-04-25 01:59:09 +00003446 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003447
Benjamin Petersone41251e2008-04-25 01:59:09 +00003448 Is the specified record to be logged? Returns zero for no, nonzero for
3449 yes. If deemed appropriate, the record may be modified in-place by this
3450 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003451
Vinay Sajip81010212010-08-19 19:17:41 +00003452Note that filters attached to handlers are consulted whenever an event is
3453emitted by the handler, whereas filters attached to loggers are consulted
3454whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3455etc.) This means that events which have been generated by descendant loggers
3456will not be filtered by a logger's filter setting, unless the filter has also
3457been applied to those descendant loggers.
3458
Vinay Sajip22246fd2010-10-20 11:40:02 +00003459You don't actually need to subclass ``Filter``: you can pass any instance
3460which has a ``filter`` method with the same semantics.
3461
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003462.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003463 You don't need to create specialized ``Filter`` classes, or use other
3464 classes with a ``filter`` method: you can use a function (or other
3465 callable) as a filter. The filtering logic will check to see if the filter
3466 object has a ``filter`` attribute: if it does, it's assumed to be a
3467 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3468 assumed to be a callable and called with the record as the single
3469 parameter. The returned value should conform to that returned by
3470 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003471
Vinay Sajipac007992010-09-17 12:45:26 +00003472Other uses for filters
3473^^^^^^^^^^^^^^^^^^^^^^
3474
3475Although filters are used primarily to filter records based on more
3476sophisticated criteria than levels, they get to see every record which is
3477processed by the handler or logger they're attached to: this can be useful if
3478you want to do things like counting how many records were processed by a
3479particular logger or handler, or adding, changing or removing attributes in
3480the LogRecord being processed. Obviously changing the LogRecord needs to be
3481done with some care, but it does allow the injection of contextual information
3482into logs (see :ref:`filters-contextual`).
3483
Vinay Sajipd31f3632010-06-29 15:31:15 +00003484.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003485
3486LogRecord Objects
3487-----------------
3488
Vinay Sajip4039aff2010-09-11 10:25:28 +00003489:class:`LogRecord` instances are created automatically by the :class:`Logger`
3490every time something is logged, and can be created manually via
3491:func:`makeLogRecord` (for example, from a pickled event received over the
3492wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003493
3494
Vinay Sajipa18b9592010-12-12 13:20:55 +00003495.. class:: LogRecord(name, levelno, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003496
Vinay Sajip4039aff2010-09-11 10:25:28 +00003497 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003498
Vinay Sajip4039aff2010-09-11 10:25:28 +00003499 The primary information is passed in :attr:`msg` and :attr:`args`, which
3500 are combined using ``msg % args`` to create the :attr:`message` field of the
3501 record.
3502
3503 .. attribute:: args
3504
3505 Tuple of arguments to be used in formatting :attr:`msg`.
3506
3507 .. attribute:: exc_info
3508
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003509 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003510 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003511
3512 .. attribute:: func
3513
3514 Name of the function of origin (i.e. in which the logging call was made).
3515
3516 .. attribute:: lineno
3517
3518 Line number in the source file of origin.
3519
Vinay Sajipa18b9592010-12-12 13:20:55 +00003520 .. attribute:: levelno
Vinay Sajip4039aff2010-09-11 10:25:28 +00003521
3522 Numeric logging level.
3523
3524 .. attribute:: message
3525
3526 Bound to the result of :meth:`getMessage` when
3527 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3528
3529 .. attribute:: msg
3530
3531 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3532 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3533
3534 .. attribute:: name
3535
3536 Name of the logger that emitted the record.
3537
3538 .. attribute:: pathname
3539
3540 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003541
Vinay Sajip8593ae62010-11-14 21:33:04 +00003542 .. attribute:: stack_info
3543
3544 Stack frame information (where available) from the bottom of the stack
3545 in the current thread, up to and including the stack frame of the
3546 logging call which resulted in the creation of this record.
3547
Benjamin Petersone41251e2008-04-25 01:59:09 +00003548 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003549
Benjamin Petersone41251e2008-04-25 01:59:09 +00003550 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003551 user-supplied arguments with the message. If the user-supplied message
3552 argument to the logging call is not a string, :func:`str` is called on it to
3553 convert it to a string. This allows use of user-defined classes as
3554 messages, whose ``__str__`` method can return the actual format string to
3555 be used.
3556
Vinay Sajip61561522010-12-03 11:50:38 +00003557 .. versionchanged:: 3.2
3558 The creation of a ``LogRecord`` has been made more configurable by
3559 providing a factory which is used to create the record. The factory can be
3560 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3561 (see this for the factory's signature).
3562
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003563 This functionality can be used to inject your own values into a
3564 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003565
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003566 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003567
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003568 def record_factory(*args, **kwargs):
3569 record = old_factory(*args, **kwargs)
3570 record.custom_attribute = 0xdecafbad
3571 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003572
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003573 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003574
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003575 With this pattern, multiple factories could be chained, and as long
3576 as they don't overwrite each other's attributes or unintentionally
3577 overwrite the standard attributes listed above, there should be no
3578 surprises.
3579
Vinay Sajip61561522010-12-03 11:50:38 +00003580
Vinay Sajipd31f3632010-06-29 15:31:15 +00003581.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003582
Christian Heimes04c420f2008-01-18 18:40:46 +00003583LoggerAdapter Objects
3584---------------------
3585
Christian Heimes04c420f2008-01-18 18:40:46 +00003586:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003587information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003588:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003589
Christian Heimes04c420f2008-01-18 18:40:46 +00003590
3591.. class:: LoggerAdapter(logger, extra)
3592
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003593 Returns an instance of :class:`LoggerAdapter` initialized with an
3594 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003595
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003596 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003597
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003598 Modifies the message and/or keyword arguments passed to a logging call in
3599 order to insert contextual information. This implementation takes the object
3600 passed as *extra* to the constructor and adds it to *kwargs* using key
3601 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3602 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003603
Vinay Sajipc84f0162010-09-21 11:25:39 +00003604In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003605methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003606:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3607:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3608:meth:`hasHandlers`. These methods have the same signatures as their
3609counterparts in :class:`Logger`, so you can use the two types of instances
3610interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003611
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003612.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003613 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3614 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3615 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003616
Georg Brandl116aa622007-08-15 14:28:22 +00003617
3618Thread Safety
3619-------------
3620
3621The logging module is intended to be thread-safe without any special work
3622needing to be done by its clients. It achieves this though using threading
3623locks; there is one lock to serialize access to the module's shared data, and
3624each handler also creates a lock to serialize access to its underlying I/O.
3625
Benjamin Petersond23f8222009-04-05 19:13:16 +00003626If you are implementing asynchronous signal handlers using the :mod:`signal`
3627module, you may not be able to use logging from within such handlers. This is
3628because lock implementations in the :mod:`threading` module are not always
3629re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003630
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003631
3632Integration with the warnings module
3633------------------------------------
3634
3635The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3636with the :mod:`warnings` module.
3637
3638.. function:: captureWarnings(capture)
3639
3640 This function is used to turn the capture of warnings by logging on and
3641 off.
3642
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003643 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3644 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003645 formatted using :func:`warnings.formatwarning` and the resulting string
3646 logged to a logger named "py.warnings" with a severity of `WARNING`.
3647
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003648 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003649 will stop, and warnings will be redirected to their original destinations
3650 (i.e. those in effect before `captureWarnings(True)` was called).
3651
3652
Georg Brandl116aa622007-08-15 14:28:22 +00003653Configuration
3654-------------
3655
3656
3657.. _logging-config-api:
3658
3659Configuration functions
3660^^^^^^^^^^^^^^^^^^^^^^^
3661
Georg Brandl116aa622007-08-15 14:28:22 +00003662The following functions configure the logging module. They are located in the
3663:mod:`logging.config` module. Their use is optional --- you can configure the
3664logging module using these functions or by making calls to the main API (defined
3665in :mod:`logging` itself) and defining handlers which are declared either in
3666:mod:`logging` or :mod:`logging.handlers`.
3667
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003668.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003669
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003670 Takes the logging configuration from a dictionary. The contents of
3671 this dictionary are described in :ref:`logging-config-dictschema`
3672 below.
3673
3674 If an error is encountered during configuration, this function will
3675 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3676 or :exc:`ImportError` with a suitably descriptive message. The
3677 following is a (possibly incomplete) list of conditions which will
3678 raise an error:
3679
3680 * A ``level`` which is not a string or which is a string not
3681 corresponding to an actual logging level.
3682 * A ``propagate`` value which is not a boolean.
3683 * An id which does not have a corresponding destination.
3684 * A non-existent handler id found during an incremental call.
3685 * An invalid logger name.
3686 * Inability to resolve to an internal or external object.
3687
3688 Parsing is performed by the :class:`DictConfigurator` class, whose
3689 constructor is passed the dictionary used for configuration, and
3690 has a :meth:`configure` method. The :mod:`logging.config` module
3691 has a callable attribute :attr:`dictConfigClass`
3692 which is initially set to :class:`DictConfigurator`.
3693 You can replace the value of :attr:`dictConfigClass` with a
3694 suitable implementation of your own.
3695
3696 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3697 the specified dictionary, and then calls the :meth:`configure` method on
3698 the returned object to put the configuration into effect::
3699
3700 def dictConfig(config):
3701 dictConfigClass(config).configure()
3702
3703 For example, a subclass of :class:`DictConfigurator` could call
3704 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3705 set up custom prefixes which would be usable in the subsequent
3706 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3707 this new subclass, and then :func:`dictConfig` could be called exactly as
3708 in the default, uncustomized state.
3709
3710.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003711
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003712 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003713 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003714 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003715 configurations (if the developer provides a mechanism to present the choices
3716 and load the chosen configuration). Defaults to be passed to the ConfigParser
3717 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003718
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003719
3720.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003721
3722 Starts up a socket server on the specified port, and listens for new
3723 configurations. If no port is specified, the module's default
3724 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3725 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3726 :class:`Thread` instance on which you can call :meth:`start` to start the
3727 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003728 call :func:`stopListening`.
3729
3730 To send a configuration to the socket, read in the configuration file and
3731 send it to the socket as a string of bytes preceded by a four-byte length
3732 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003733
3734
3735.. function:: stopListening()
3736
Christian Heimes8b0facf2007-12-04 19:30:01 +00003737 Stops the listening server which was created with a call to :func:`listen`.
3738 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003739 :func:`listen`.
3740
3741
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003742.. _logging-config-dictschema:
3743
3744Configuration dictionary schema
3745^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3746
3747Describing a logging configuration requires listing the various
3748objects to create and the connections between them; for example, you
3749may create a handler named "console" and then say that the logger
3750named "startup" will send its messages to the "console" handler.
3751These objects aren't limited to those provided by the :mod:`logging`
3752module because you might write your own formatter or handler class.
3753The parameters to these classes may also need to include external
3754objects such as ``sys.stderr``. The syntax for describing these
3755objects and connections is defined in :ref:`logging-config-dict-connections`
3756below.
3757
3758Dictionary Schema Details
3759"""""""""""""""""""""""""
3760
3761The dictionary passed to :func:`dictConfig` must contain the following
3762keys:
3763
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003764* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003765 version. The only valid value at present is 1, but having this key
3766 allows the schema to evolve while still preserving backwards
3767 compatibility.
3768
3769All other keys are optional, but if present they will be interpreted
3770as described below. In all cases below where a 'configuring dict' is
3771mentioned, it will be checked for the special ``'()'`` key to see if a
3772custom instantiation is required. If so, the mechanism described in
3773:ref:`logging-config-dict-userdef` below is used to create an instance;
3774otherwise, the context is used to determine what to instantiate.
3775
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003776* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003777 key is a formatter id and each value is a dict describing how to
3778 configure the corresponding Formatter instance.
3779
3780 The configuring dict is searched for keys ``format`` and ``datefmt``
3781 (with defaults of ``None``) and these are used to construct a
3782 :class:`logging.Formatter` instance.
3783
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003784* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003785 is a filter id and each value is a dict describing how to configure
3786 the corresponding Filter instance.
3787
3788 The configuring dict is searched for the key ``name`` (defaulting to the
3789 empty string) and this is used to construct a :class:`logging.Filter`
3790 instance.
3791
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003792* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003793 key is a handler id and each value is a dict describing how to
3794 configure the corresponding Handler instance.
3795
3796 The configuring dict is searched for the following keys:
3797
3798 * ``class`` (mandatory). This is the fully qualified name of the
3799 handler class.
3800
3801 * ``level`` (optional). The level of the handler.
3802
3803 * ``formatter`` (optional). The id of the formatter for this
3804 handler.
3805
3806 * ``filters`` (optional). A list of ids of the filters for this
3807 handler.
3808
3809 All *other* keys are passed through as keyword arguments to the
3810 handler's constructor. For example, given the snippet::
3811
3812 handlers:
3813 console:
3814 class : logging.StreamHandler
3815 formatter: brief
3816 level : INFO
3817 filters: [allow_foo]
3818 stream : ext://sys.stdout
3819 file:
3820 class : logging.handlers.RotatingFileHandler
3821 formatter: precise
3822 filename: logconfig.log
3823 maxBytes: 1024
3824 backupCount: 3
3825
3826 the handler with id ``console`` is instantiated as a
3827 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3828 stream. The handler with id ``file`` is instantiated as a
3829 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3830 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3831
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003832* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003833 is a logger name and each value is a dict describing how to
3834 configure the corresponding Logger instance.
3835
3836 The configuring dict is searched for the following keys:
3837
3838 * ``level`` (optional). The level of the logger.
3839
3840 * ``propagate`` (optional). The propagation setting of the logger.
3841
3842 * ``filters`` (optional). A list of ids of the filters for this
3843 logger.
3844
3845 * ``handlers`` (optional). A list of ids of the handlers for this
3846 logger.
3847
3848 The specified loggers will be configured according to the level,
3849 propagation, filters and handlers specified.
3850
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003851* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003852 Processing of the configuration will be as for any logger, except
3853 that the ``propagate`` setting will not be applicable.
3854
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003855* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003856 incremental to the existing configuration. This value defaults to
3857 ``False``, which means that the specified configuration replaces the
3858 existing configuration with the same semantics as used by the
3859 existing :func:`fileConfig` API.
3860
3861 If the specified value is ``True``, the configuration is processed
3862 as described in the section on :ref:`logging-config-dict-incremental`.
3863
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003864* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003865 disabled. This setting mirrors the parameter of the same name in
3866 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003867 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003868
3869.. _logging-config-dict-incremental:
3870
3871Incremental Configuration
3872"""""""""""""""""""""""""
3873
3874It is difficult to provide complete flexibility for incremental
3875configuration. For example, because objects such as filters
3876and formatters are anonymous, once a configuration is set up, it is
3877not possible to refer to such anonymous objects when augmenting a
3878configuration.
3879
3880Furthermore, there is not a compelling case for arbitrarily altering
3881the object graph of loggers, handlers, filters, formatters at
3882run-time, once a configuration is set up; the verbosity of loggers and
3883handlers can be controlled just by setting levels (and, in the case of
3884loggers, propagation flags). Changing the object graph arbitrarily in
3885a safe way is problematic in a multi-threaded environment; while not
3886impossible, the benefits are not worth the complexity it adds to the
3887implementation.
3888
3889Thus, when the ``incremental`` key of a configuration dict is present
3890and is ``True``, the system will completely ignore any ``formatters`` and
3891``filters`` entries, and process only the ``level``
3892settings in the ``handlers`` entries, and the ``level`` and
3893``propagate`` settings in the ``loggers`` and ``root`` entries.
3894
3895Using a value in the configuration dict lets configurations to be sent
3896over the wire as pickled dicts to a socket listener. Thus, the logging
3897verbosity of a long-running application can be altered over time with
3898no need to stop and restart the application.
3899
3900.. _logging-config-dict-connections:
3901
3902Object connections
3903""""""""""""""""""
3904
3905The schema describes a set of logging objects - loggers,
3906handlers, formatters, filters - which are connected to each other in
3907an object graph. Thus, the schema needs to represent connections
3908between the objects. For example, say that, once configured, a
3909particular logger has attached to it a particular handler. For the
3910purposes of this discussion, we can say that the logger represents the
3911source, and the handler the destination, of a connection between the
3912two. Of course in the configured objects this is represented by the
3913logger holding a reference to the handler. In the configuration dict,
3914this is done by giving each destination object an id which identifies
3915it unambiguously, and then using the id in the source object's
3916configuration to indicate that a connection exists between the source
3917and the destination object with that id.
3918
3919So, for example, consider the following YAML snippet::
3920
3921 formatters:
3922 brief:
3923 # configuration for formatter with id 'brief' goes here
3924 precise:
3925 # configuration for formatter with id 'precise' goes here
3926 handlers:
3927 h1: #This is an id
3928 # configuration of handler with id 'h1' goes here
3929 formatter: brief
3930 h2: #This is another id
3931 # configuration of handler with id 'h2' goes here
3932 formatter: precise
3933 loggers:
3934 foo.bar.baz:
3935 # other configuration for logger 'foo.bar.baz'
3936 handlers: [h1, h2]
3937
3938(Note: YAML used here because it's a little more readable than the
3939equivalent Python source form for the dictionary.)
3940
3941The ids for loggers are the logger names which would be used
3942programmatically to obtain a reference to those loggers, e.g.
3943``foo.bar.baz``. The ids for Formatters and Filters can be any string
3944value (such as ``brief``, ``precise`` above) and they are transient,
3945in that they are only meaningful for processing the configuration
3946dictionary and used to determine connections between objects, and are
3947not persisted anywhere when the configuration call is complete.
3948
3949The above snippet indicates that logger named ``foo.bar.baz`` should
3950have two handlers attached to it, which are described by the handler
3951ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
3952``brief``, and the formatter for ``h2`` is that described by id
3953``precise``.
3954
3955
3956.. _logging-config-dict-userdef:
3957
3958User-defined objects
3959""""""""""""""""""""
3960
3961The schema supports user-defined objects for handlers, filters and
3962formatters. (Loggers do not need to have different types for
3963different instances, so there is no support in this configuration
3964schema for user-defined logger classes.)
3965
3966Objects to be configured are described by dictionaries
3967which detail their configuration. In some places, the logging system
3968will be able to infer from the context how an object is to be
3969instantiated, but when a user-defined object is to be instantiated,
3970the system will not know how to do this. In order to provide complete
3971flexibility for user-defined object instantiation, the user needs
3972to provide a 'factory' - a callable which is called with a
3973configuration dictionary and which returns the instantiated object.
3974This is signalled by an absolute import path to the factory being
3975made available under the special key ``'()'``. Here's a concrete
3976example::
3977
3978 formatters:
3979 brief:
3980 format: '%(message)s'
3981 default:
3982 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
3983 datefmt: '%Y-%m-%d %H:%M:%S'
3984 custom:
3985 (): my.package.customFormatterFactory
3986 bar: baz
3987 spam: 99.9
3988 answer: 42
3989
3990The above YAML snippet defines three formatters. The first, with id
3991``brief``, is a standard :class:`logging.Formatter` instance with the
3992specified format string. The second, with id ``default``, has a
3993longer format and also defines the time format explicitly, and will
3994result in a :class:`logging.Formatter` initialized with those two format
3995strings. Shown in Python source form, the ``brief`` and ``default``
3996formatters have configuration sub-dictionaries::
3997
3998 {
3999 'format' : '%(message)s'
4000 }
4001
4002and::
4003
4004 {
4005 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4006 'datefmt' : '%Y-%m-%d %H:%M:%S'
4007 }
4008
4009respectively, and as these dictionaries do not contain the special key
4010``'()'``, the instantiation is inferred from the context: as a result,
4011standard :class:`logging.Formatter` instances are created. The
4012configuration sub-dictionary for the third formatter, with id
4013``custom``, is::
4014
4015 {
4016 '()' : 'my.package.customFormatterFactory',
4017 'bar' : 'baz',
4018 'spam' : 99.9,
4019 'answer' : 42
4020 }
4021
4022and this contains the special key ``'()'``, which means that
4023user-defined instantiation is wanted. In this case, the specified
4024factory callable will be used. If it is an actual callable it will be
4025used directly - otherwise, if you specify a string (as in the example)
4026the actual callable will be located using normal import mechanisms.
4027The callable will be called with the **remaining** items in the
4028configuration sub-dictionary as keyword arguments. In the above
4029example, the formatter with id ``custom`` will be assumed to be
4030returned by the call::
4031
4032 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4033
4034The key ``'()'`` has been used as the special key because it is not a
4035valid keyword parameter name, and so will not clash with the names of
4036the keyword arguments used in the call. The ``'()'`` also serves as a
4037mnemonic that the corresponding value is a callable.
4038
4039
4040.. _logging-config-dict-externalobj:
4041
4042Access to external objects
4043""""""""""""""""""""""""""
4044
4045There are times where a configuration needs to refer to objects
4046external to the configuration, for example ``sys.stderr``. If the
4047configuration dict is constructed using Python code, this is
4048straightforward, but a problem arises when the configuration is
4049provided via a text file (e.g. JSON, YAML). In a text file, there is
4050no standard way to distinguish ``sys.stderr`` from the literal string
4051``'sys.stderr'``. To facilitate this distinction, the configuration
4052system looks for certain special prefixes in string values and
4053treat them specially. For example, if the literal string
4054``'ext://sys.stderr'`` is provided as a value in the configuration,
4055then the ``ext://`` will be stripped off and the remainder of the
4056value processed using normal import mechanisms.
4057
4058The handling of such prefixes is done in a way analogous to protocol
4059handling: there is a generic mechanism to look for prefixes which
4060match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4061whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4062in a prefix-dependent manner and the result of the processing replaces
4063the string value. If the prefix is not recognised, then the string
4064value will be left as-is.
4065
4066
4067.. _logging-config-dict-internalobj:
4068
4069Access to internal objects
4070""""""""""""""""""""""""""
4071
4072As well as external objects, there is sometimes also a need to refer
4073to objects in the configuration. This will be done implicitly by the
4074configuration system for things that it knows about. For example, the
4075string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4076automatically be converted to the value ``logging.DEBUG``, and the
4077``handlers``, ``filters`` and ``formatter`` entries will take an
4078object id and resolve to the appropriate destination object.
4079
4080However, a more generic mechanism is needed for user-defined
4081objects which are not known to the :mod:`logging` module. For
4082example, consider :class:`logging.handlers.MemoryHandler`, which takes
4083a ``target`` argument which is another handler to delegate to. Since
4084the system already knows about this class, then in the configuration,
4085the given ``target`` just needs to be the object id of the relevant
4086target handler, and the system will resolve to the handler from the
4087id. If, however, a user defines a ``my.package.MyHandler`` which has
4088an ``alternate`` handler, the configuration system would not know that
4089the ``alternate`` referred to a handler. To cater for this, a generic
4090resolution system allows the user to specify::
4091
4092 handlers:
4093 file:
4094 # configuration of file handler goes here
4095
4096 custom:
4097 (): my.package.MyHandler
4098 alternate: cfg://handlers.file
4099
4100The literal string ``'cfg://handlers.file'`` will be resolved in an
4101analogous way to strings with the ``ext://`` prefix, but looking
4102in the configuration itself rather than the import namespace. The
4103mechanism allows access by dot or by index, in a similar way to
4104that provided by ``str.format``. Thus, given the following snippet::
4105
4106 handlers:
4107 email:
4108 class: logging.handlers.SMTPHandler
4109 mailhost: localhost
4110 fromaddr: my_app@domain.tld
4111 toaddrs:
4112 - support_team@domain.tld
4113 - dev_team@domain.tld
4114 subject: Houston, we have a problem.
4115
4116in the configuration, the string ``'cfg://handlers'`` would resolve to
4117the dict with key ``handlers``, the string ``'cfg://handlers.email``
4118would resolve to the dict with key ``email`` in the ``handlers`` dict,
4119and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4120resolve to ``'dev_team.domain.tld'`` and the string
4121``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4122``'support_team@domain.tld'``. The ``subject`` value could be accessed
4123using either ``'cfg://handlers.email.subject'`` or, equivalently,
4124``'cfg://handlers.email[subject]'``. The latter form only needs to be
4125used if the key contains spaces or non-alphanumeric characters. If an
4126index value consists only of decimal digits, access will be attempted
4127using the corresponding integer value, falling back to the string
4128value if needed.
4129
4130Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4131resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4132If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4133the system will attempt to retrieve the value from
4134``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4135to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4136fails.
4137
Georg Brandl116aa622007-08-15 14:28:22 +00004138.. _logging-config-fileformat:
4139
4140Configuration file format
4141^^^^^^^^^^^^^^^^^^^^^^^^^
4142
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004143The configuration file format understood by :func:`fileConfig` is based on
4144:mod:`configparser` functionality. The file must contain sections called
4145``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4146entities of each type which are defined in the file. For each such entity, there
4147is a separate section which identifies how that entity is configured. Thus, for
4148a logger named ``log01`` in the ``[loggers]`` section, the relevant
4149configuration details are held in a section ``[logger_log01]``. Similarly, a
4150handler called ``hand01`` in the ``[handlers]`` section will have its
4151configuration held in a section called ``[handler_hand01]``, while a formatter
4152called ``form01`` in the ``[formatters]`` section will have its configuration
4153specified in a section called ``[formatter_form01]``. The root logger
4154configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004155
4156Examples of these sections in the file are given below. ::
4157
4158 [loggers]
4159 keys=root,log02,log03,log04,log05,log06,log07
4160
4161 [handlers]
4162 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4163
4164 [formatters]
4165 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4166
4167The root logger must specify a level and a list of handlers. An example of a
4168root logger section is given below. ::
4169
4170 [logger_root]
4171 level=NOTSET
4172 handlers=hand01
4173
4174The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4175``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4176logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4177package's namespace.
4178
4179The ``handlers`` entry is a comma-separated list of handler names, which must
4180appear in the ``[handlers]`` section. These names must appear in the
4181``[handlers]`` section and have corresponding sections in the configuration
4182file.
4183
4184For loggers other than the root logger, some additional information is required.
4185This is illustrated by the following example. ::
4186
4187 [logger_parser]
4188 level=DEBUG
4189 handlers=hand01
4190 propagate=1
4191 qualname=compiler.parser
4192
4193The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4194except that if a non-root logger's level is specified as ``NOTSET``, the system
4195consults loggers higher up the hierarchy to determine the effective level of the
4196logger. The ``propagate`` entry is set to 1 to indicate that messages must
4197propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4198indicate that messages are **not** propagated to handlers up the hierarchy. The
4199``qualname`` entry is the hierarchical channel name of the logger, that is to
4200say the name used by the application to get the logger.
4201
4202Sections which specify handler configuration are exemplified by the following.
4203::
4204
4205 [handler_hand01]
4206 class=StreamHandler
4207 level=NOTSET
4208 formatter=form01
4209 args=(sys.stdout,)
4210
4211The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4212in the ``logging`` package's namespace). The ``level`` is interpreted as for
4213loggers, and ``NOTSET`` is taken to mean "log everything".
4214
4215The ``formatter`` entry indicates the key name of the formatter for this
4216handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4217If a name is specified, it must appear in the ``[formatters]`` section and have
4218a corresponding section in the configuration file.
4219
4220The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4221package's namespace, is the list of arguments to the constructor for the handler
4222class. Refer to the constructors for the relevant handlers, or to the examples
4223below, to see how typical entries are constructed. ::
4224
4225 [handler_hand02]
4226 class=FileHandler
4227 level=DEBUG
4228 formatter=form02
4229 args=('python.log', 'w')
4230
4231 [handler_hand03]
4232 class=handlers.SocketHandler
4233 level=INFO
4234 formatter=form03
4235 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4236
4237 [handler_hand04]
4238 class=handlers.DatagramHandler
4239 level=WARN
4240 formatter=form04
4241 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4242
4243 [handler_hand05]
4244 class=handlers.SysLogHandler
4245 level=ERROR
4246 formatter=form05
4247 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4248
4249 [handler_hand06]
4250 class=handlers.NTEventLogHandler
4251 level=CRITICAL
4252 formatter=form06
4253 args=('Python Application', '', 'Application')
4254
4255 [handler_hand07]
4256 class=handlers.SMTPHandler
4257 level=WARN
4258 formatter=form07
4259 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4260
4261 [handler_hand08]
4262 class=handlers.MemoryHandler
4263 level=NOTSET
4264 formatter=form08
4265 target=
4266 args=(10, ERROR)
4267
4268 [handler_hand09]
4269 class=handlers.HTTPHandler
4270 level=NOTSET
4271 formatter=form09
4272 args=('localhost:9022', '/log', 'GET')
4273
4274Sections which specify formatter configuration are typified by the following. ::
4275
4276 [formatter_form01]
4277 format=F1 %(asctime)s %(levelname)s %(message)s
4278 datefmt=
4279 class=logging.Formatter
4280
4281The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004282the :func:`strftime`\ -compatible date/time format string. If empty, the
4283package substitutes ISO8601 format date/times, which is almost equivalent to
4284specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
4285also specifies milliseconds, which are appended to the result of using the above
4286format string, with a comma separator. An example time in ISO8601 format is
4287``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004288
4289The ``class`` entry is optional. It indicates the name of the formatter's class
4290(as a dotted module and class name.) This option is useful for instantiating a
4291:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4292exception tracebacks in an expanded or condensed format.
4293
Christian Heimes8b0facf2007-12-04 19:30:01 +00004294
4295Configuration server example
4296^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4297
4298Here is an example of a module using the logging configuration server::
4299
4300 import logging
4301 import logging.config
4302 import time
4303 import os
4304
4305 # read initial config file
4306 logging.config.fileConfig("logging.conf")
4307
4308 # create and start listener on port 9999
4309 t = logging.config.listen(9999)
4310 t.start()
4311
4312 logger = logging.getLogger("simpleExample")
4313
4314 try:
4315 # loop through logging calls to see the difference
4316 # new configurations make, until Ctrl+C is pressed
4317 while True:
4318 logger.debug("debug message")
4319 logger.info("info message")
4320 logger.warn("warn message")
4321 logger.error("error message")
4322 logger.critical("critical message")
4323 time.sleep(5)
4324 except KeyboardInterrupt:
4325 # cleanup
4326 logging.config.stopListening()
4327 t.join()
4328
4329And here is a script that takes a filename and sends that file to the server,
4330properly preceded with the binary-encoded length, as the new logging
4331configuration::
4332
4333 #!/usr/bin/env python
4334 import socket, sys, struct
4335
4336 data_to_send = open(sys.argv[1], "r").read()
4337
4338 HOST = 'localhost'
4339 PORT = 9999
4340 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00004341 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004342 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00004343 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004344 s.send(struct.pack(">L", len(data_to_send)))
4345 s.send(data_to_send)
4346 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00004347 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004348
4349
4350More examples
4351-------------
4352
4353Multiple handlers and formatters
4354^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4355
4356Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4357or maximum quota for the number of handlers you may add. Sometimes it will be
4358beneficial for an application to log all messages of all severities to a text
4359file while simultaneously logging errors or above to the console. To set this
4360up, simply configure the appropriate handlers. The logging calls in the
4361application code will remain unchanged. Here is a slight modification to the
4362previous simple module-based configuration example::
4363
4364 import logging
4365
4366 logger = logging.getLogger("simple_example")
4367 logger.setLevel(logging.DEBUG)
4368 # create file handler which logs even debug messages
4369 fh = logging.FileHandler("spam.log")
4370 fh.setLevel(logging.DEBUG)
4371 # create console handler with a higher log level
4372 ch = logging.StreamHandler()
4373 ch.setLevel(logging.ERROR)
4374 # create formatter and add it to the handlers
4375 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4376 ch.setFormatter(formatter)
4377 fh.setFormatter(formatter)
4378 # add the handlers to logger
4379 logger.addHandler(ch)
4380 logger.addHandler(fh)
4381
4382 # "application" code
4383 logger.debug("debug message")
4384 logger.info("info message")
4385 logger.warn("warn message")
4386 logger.error("error message")
4387 logger.critical("critical message")
4388
4389Notice that the "application" code does not care about multiple handlers. All
4390that changed was the addition and configuration of a new handler named *fh*.
4391
4392The ability to create new handlers with higher- or lower-severity filters can be
4393very helpful when writing and testing an application. Instead of using many
4394``print`` statements for debugging, use ``logger.debug``: Unlike the print
4395statements, which you will have to delete or comment out later, the logger.debug
4396statements can remain intact in the source code and remain dormant until you
4397need them again. At that time, the only change that needs to happen is to
4398modify the severity level of the logger and/or handler to debug.
4399
4400
4401Using logging in multiple modules
4402^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4403
4404It was mentioned above that multiple calls to
4405``logging.getLogger('someLogger')`` return a reference to the same logger
4406object. This is true not only within the same module, but also across modules
4407as long as it is in the same Python interpreter process. It is true for
4408references to the same object; additionally, application code can define and
4409configure a parent logger in one module and create (but not configure) a child
4410logger in a separate module, and all logger calls to the child will pass up to
4411the parent. Here is a main module::
4412
4413 import logging
4414 import auxiliary_module
4415
4416 # create logger with "spam_application"
4417 logger = logging.getLogger("spam_application")
4418 logger.setLevel(logging.DEBUG)
4419 # create file handler which logs even debug messages
4420 fh = logging.FileHandler("spam.log")
4421 fh.setLevel(logging.DEBUG)
4422 # create console handler with a higher log level
4423 ch = logging.StreamHandler()
4424 ch.setLevel(logging.ERROR)
4425 # create formatter and add it to the handlers
4426 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4427 fh.setFormatter(formatter)
4428 ch.setFormatter(formatter)
4429 # add the handlers to the logger
4430 logger.addHandler(fh)
4431 logger.addHandler(ch)
4432
4433 logger.info("creating an instance of auxiliary_module.Auxiliary")
4434 a = auxiliary_module.Auxiliary()
4435 logger.info("created an instance of auxiliary_module.Auxiliary")
4436 logger.info("calling auxiliary_module.Auxiliary.do_something")
4437 a.do_something()
4438 logger.info("finished auxiliary_module.Auxiliary.do_something")
4439 logger.info("calling auxiliary_module.some_function()")
4440 auxiliary_module.some_function()
4441 logger.info("done with auxiliary_module.some_function()")
4442
4443Here is the auxiliary module::
4444
4445 import logging
4446
4447 # create logger
4448 module_logger = logging.getLogger("spam_application.auxiliary")
4449
4450 class Auxiliary:
4451 def __init__(self):
4452 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4453 self.logger.info("creating an instance of Auxiliary")
4454 def do_something(self):
4455 self.logger.info("doing something")
4456 a = 1 + 1
4457 self.logger.info("done doing something")
4458
4459 def some_function():
4460 module_logger.info("received a call to \"some_function\"")
4461
4462The output looks like this::
4463
Christian Heimes043d6f62008-01-07 17:19:16 +00004464 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004465 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004466 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004467 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004468 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004469 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004470 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004471 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004472 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004473 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004474 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004475 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004476 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004477 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004478 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004479 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004480 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004481 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004482 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004483 done with auxiliary_module.some_function()
4484