blob: b11dbc5f6271ab7aeb8041d370087aadaf174cfd [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
Vinay Sajip36675b62010-12-12 22:30:17 +000015logging system for applications and libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000016
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 |
Vinay Sajipf234eb92010-12-12 17:37:27 +000051| for status monitoring or fault | diagnostic purposes) |
Vinay Sajipa18b9592010-12-12 13:20:55 +000052| 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
Vinay Sajip0e65cf02010-12-12 13:49:39 +0000149The call to :func:`basicConfig` should come *before* any calls to :func:`debug`,
150:func:`info` etc. As it's intended as a one-off simple configuration facility,
151only the first call will actually do anything: subsequent calls are effectively
152no-ops.
153
Vinay Sajipa18b9592010-12-12 13:20:55 +0000154This example also shows how you can set the logging level which acts as the
155threshold for tracking. In this case, because we set the threshold to
156``DEBUG``, all of the messages were printed.
157
158If you run the above script several times, the messages from successive runs
159are appended to the file *example.log*. If you want each run to start afresh,
160not remembering the messages from earlier runs, you can specify the *filemode*
161argument, by changing the call in the above example to::
162
163 logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
164
165The output will be the same as before, but the log file is no longer appended
166to, so the messages from earlier runs are lost.
167
168
169Logging from multiple modules
170^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
171
172If your program consists of multiple modules, here's an example of how you
173could organize logging in it::
174
175 # myapp.py
176 import logging
177 import mylib
178
179 def main():
180 logging.basicConfig(filename='myapp.log', level=logging.INFO)
181 logging.info('Started')
182 mylib.do_something()
183 logging.info('Finished')
184
185 if __name__ == '__main__':
186 main()
187
188::
189
190 # mylib.py
191 import logging
192
193 def do_something():
194 logging.info('Doing something')
195
196If you run myapp.py, you should see this in myapp.log::
197
198 INFO:root:Started
199 INFO:root:Doing something
200 INFO:root:Finished
201
202which is hopefully what you were expecting to see. You can generalize this to
203multiple modules, using the pattern in *mylib.py*. Note that for this simple
204usage pattern, you won't know, by looking in the log file, *where* in your
205application your messages came from, apart from looking at the event
206description. If you want to track the location of your messages, you'll need
207to refer to the documentation beyond the tutorial level - see
208:ref:`more-advanced-logging`.
209
210
211Logging variable data
212^^^^^^^^^^^^^^^^^^^^^
213
214To log variable data, use a format string for the event description message and
215append the variable data as arguments. For example::
216
217 import logging
218 logging.warning('%s before you %s', 'Look', 'leap!')
219
220will display::
221
222 WARNING:root:Look before you leap!
223
224As you can see, merging of variable data into the event description message
225uses the old, %-style of string formatting. This is for backwards
226compatibility: the logging package pre-dates newer formatting options such as
Vinay Sajip36675b62010-12-12 22:30:17 +0000227:meth:`str.format` and :class:`string.Template`. These newer formatting
228options *are* supported, but exploring them is outside the scope of this
229tutorial.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000230
231
232Changing the format of displayed messages
233^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
234
235To change the format which is used to display messages, you need to
236specify the format you want to use::
237
238 import logging
239 logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
240 logging.debug('This message should appear on the console')
241 logging.info('So should this')
242 logging.warning('And this, too')
243
244which would print::
245
246 DEBUG:This message should appear on the console
247 INFO:So should this
248 WARNING:And this, too
249
250Notice that the 'root' which appeared in earlier examples has disappeared. For
251a full set of things that can appear in format strings, you can refer to the
252documentation for :ref:`formatter-objects`, but for simple usage, you just need
253the *levelname* (severity), *message* (event description, including variable
254data) and perhaps to display when the event occurred. This is described in the
255next section.
256
257Displaying the date/time in messages
258^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
259
260To display the date and time of an event, you would place "%(asctime)s" in
261your format string::
262
263 import logging
264 logging.basicConfig(format='%(asctime)s %(message)s')
265 logging.warning('is when this event was logged.')
266
267which should print something like this::
268
269 2010-12-12 11:41:42,612 is when this event was logged.
270
271The default format for date/time display (shown above) is ISO8601. If you need
272more control over the formatting of the date/time, provide a *datefmt*
273argument to ``basicConfig``, as in this example::
274
275 import logging
276 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
277 logging.warning('is when this event was logged.')
278
279which would display something like this::
280
281 12/12/2010 11:46:36 AM is when this event was logged.
282
283The format of the *datefmt* argument is the same as supported by
284:func:`time.strftime`.
285
286
Vinay Sajipf234eb92010-12-12 17:37:27 +0000287Er...that's it for the basics
288^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Vinay Sajipa18b9592010-12-12 13:20:55 +0000289
Vinay Sajipf234eb92010-12-12 17:37:27 +0000290That concludes the basic tutorial. It should be enough to get you up and
291running with logging. There's a lot more that the logging package offers, but
292to get the best out of it, you'll need to invest a little more of your time in
Vinay Sajipa18b9592010-12-12 13:20:55 +0000293reading the following sections. If you're ready for that, grab some of your
294favourite beverage and carry on.
295
296If your logging needs are simple, then use the above examples to incorporate
297logging into your own scripts, and if you run into problems or don't
298understand something, please post a question on the comp.lang.python Usenet
299group (available at http://groups.google.com/group/comp.lang.python) and you
300should receive help before too long.
301
Vinay Sajipf234eb92010-12-12 17:37:27 +0000302Still here? There's no need to read the whole of the logging documentation in
303linear fashion, top to bottom (there's quite a lot of it still to come). You
304can carry on reading the next few sections, which provide a slightly more
305advanced/in-depth tutorial than the basic one above. After that, you can
306take a look at the topics in the sidebar to see if there's something that
307especially interests you, and click on a topic to see more detail. Although
308some of the topics do follow on from each other, there are a few that can just
309stand alone.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000310
311
312.. _more-advanced-logging:
313
314More advanced logging
315---------------------
316
317The logging library takes a modular approach and offers several categories
318of components: loggers, handlers, filters, and formatters. Loggers expose the
319interface that application code directly uses. Handlers send the log records
320(created by loggers) to the appropriate destination. Filters provide a finer
321grained facility for determining which log records to output. Formatters
322specify the layout of the resultant log record in the final output.
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324Logging is performed by calling methods on instances of the :class:`Logger`
325class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +0000326conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +0000327separators. For example, a logger named "scan" is the parent of loggers
328"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
329and indicate the area of an application in which a logged message originates.
330
Vinay Sajip5286ccf2010-12-12 13:25:29 +0000331A good convention to use when naming loggers is to use a module-level logger,
332in each module which uses logging, named as follows::
333
334 logger = logging.getLogger(__name__)
335
336This means that logger names track the package/module hierarchy, and it's
337intuitively obvious where events are logged just from the logger name.
338
Vinay Sajipa18b9592010-12-12 13:20:55 +0000339The root of the hierarchy of loggers is called the root logger. That's the
340logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
341:func:`error` and :func:`critical`, which just call the same-named method of
342the root logger. The functions and the methods have the same signatures. The
343root logger's name is printed as 'root' in the logged output.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Vinay Sajipa18b9592010-12-12 13:20:55 +0000345It is, of course, possible to log messages to different destinations. Support
346for writing log messages to files, HTTP GET/POST locations, email via SMTP,
347generic sockets, or OS-specific logging mechanisms is included in the package.
348Destinations are served by :dfn:`handler` classes. You can create your own log
Vinay Sajipdfa0a2a2010-12-10 08:17:05 +0000349destination class if you have special requirements not met by any of the
Vinay Sajipa18b9592010-12-12 13:20:55 +0000350built-in handler classes.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000351
Vinay Sajipa18b9592010-12-12 13:20:55 +0000352By default, no destination is set for any logging messages. You can specify
353a destination (such as console or file) by using :func:`basicConfig` as in the
354tutorial examples. If you call the functions :func:`debug`, :func:`info`,
355:func:`warning`, :func:`error` and :func:`critical`, they will check to see
356if no destination is set; and if one is not set, they will set a destination
357of the console (``sys.stderr``) and a default format for the displayed
358message before delegating to the root logger to do the actual message output.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000359
Vinay Sajipa18b9592010-12-12 13:20:55 +0000360The default format set by :func:`basicConfig` for messages is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000361
Vinay Sajipa18b9592010-12-12 13:20:55 +0000362 severity:logger name:message
Christian Heimes8b0facf2007-12-04 19:30:01 +0000363
Vinay Sajipa18b9592010-12-12 13:20:55 +0000364You can change this by passing a format string to :func:`basicConfig` with the
365*format* keyword argument. For all options regarding how a format string is
366constructed, see :ref:`formatter-objects`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000367
Christian Heimes8b0facf2007-12-04 19:30:01 +0000368
369Loggers
370^^^^^^^
371
Christian Heimes8b0facf2007-12-04 19:30:01 +0000372:class:`Logger` objects have a threefold job. First, they expose several
373methods to application code so that applications can log messages at runtime.
374Second, logger objects determine which log messages to act upon based upon
375severity (the default filtering facility) or filter objects. Third, logger
376objects pass along relevant log messages to all interested log handlers.
377
378The most widely used methods on logger objects fall into two categories:
379configuration and message sending.
380
Vinay Sajipf234eb92010-12-12 17:37:27 +0000381These are the most common configuration methods:
382
Christian Heimes8b0facf2007-12-04 19:30:01 +0000383* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
Vinay Sajipf234eb92010-12-12 17:37:27 +0000384 will handle, where debug is the lowest built-in severity level and critical
385 is the highest built-in severity. For example, if the severity level is
386 INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
387 and will ignore DEBUG messages.
388
389* :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove
390 handler objects from the logger object. Handlers are covered in more detail
391 in :ref:`handler-basic`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000392
393* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
Vinay Sajipf234eb92010-12-12 17:37:27 +0000394 objects from the logger object. Filters are covered in more detail in
395 :ref:`filter`.
396
397You don't need to always call these methods on every logger you create. See the
398last two paragraphs in this section.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000399
400With the logger object configured, the following methods create log messages:
401
402* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
403 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
404 a message and a level that corresponds to their respective method names. The
405 message is actually a format string, which may contain the standard string
406 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
407 rest of their arguments is a list of objects that correspond with the
408 substitution fields in the message. With regard to :const:`**kwargs`, the
409 logging methods care only about a keyword of :const:`exc_info` and use it to
410 determine whether to log exception information.
411
412* :meth:`Logger.exception` creates a log message similar to
413 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
414 stack trace along with it. Call this method only from an exception handler.
415
416* :meth:`Logger.log` takes a log level as an explicit argument. This is a
417 little more verbose for logging messages than using the log level convenience
418 methods listed above, but this is how to log at custom log levels.
419
Christian Heimesdcca98d2008-02-25 13:19:43 +0000420:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000421name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000422hierarchical structures. Multiple calls to :func:`getLogger` with the same name
423will return a reference to the same logger object. Loggers that are further
424down in the hierarchical list are children of loggers higher up in the list.
425For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000426``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000427
428Loggers have a concept of *effective level*. If a level is not explicitly set
429on a logger, the level of its parent is used instead as its effective level.
430If the parent has no explicit level set, *its* parent is examined, and so on -
431all ancestors are searched until an explicitly set level is found. The root
432logger always has an explicit level set (``WARNING`` by default). When deciding
433whether to process an event, the effective level of the logger is used to
434determine whether the event is passed to the logger's handlers.
435
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000436Child loggers propagate messages up to the handlers associated with their
Vinay Sajipf234eb92010-12-12 17:37:27 +0000437ancestor loggers. Because of this, it is unnecessary to define and configure
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000438handlers for all the loggers an application uses. It is sufficient to
439configure handlers for a top-level logger and create child loggers as needed.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000440(You can, however, turn off propagation by setting the *propagate*
441attribute of a logger to *False*.)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000442
443
Vinay Sajipf234eb92010-12-12 17:37:27 +0000444.. _handler-basic:
445
Christian Heimes8b0facf2007-12-04 19:30:01 +0000446Handlers
447^^^^^^^^
448
449:class:`Handler` objects are responsible for dispatching the appropriate log
450messages (based on the log messages' severity) to the handler's specified
451destination. Logger objects can add zero or more handler objects to themselves
452with an :func:`addHandler` method. As an example scenario, an application may
453want to send all log messages to a log file, all log messages of error or higher
454to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000455requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000456messages of a specific severity to a specific location.
457
Vinay Sajipf234eb92010-12-12 17:37:27 +0000458The standard library includes quite a few handler types (see
459:ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and
460:class:`FileHandler` in its examples.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000461
462There are very few methods in a handler for application developers to concern
463themselves with. The only handler methods that seem relevant for application
464developers who are using the built-in handler objects (that is, not creating
465custom handlers) are the following configuration methods:
466
467* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
468 lowest severity that will be dispatched to the appropriate destination. Why
469 are there two :func:`setLevel` methods? The level set in the logger
470 determines which severity of messages it will pass to its handlers. The level
471 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000472
473* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000474
475* :func:`addFilter` and :func:`removeFilter` respectively configure and
476 deconfigure filter objects on handlers.
477
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000478Application code should not directly instantiate and use instances of
479:class:`Handler`. Instead, the :class:`Handler` class is a base class that
480defines the interface that all handlers should have and establishes some
481default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000482
483
484Formatters
485^^^^^^^^^^
486
487Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000488message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000489instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000490if your application needs special behavior. The constructor takes three
491optional arguments -- a message format string, a date format string and a style
492indicator.
493
494.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
495
496If there is no message format string, the default is to use the
497raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000498
499 %Y-%m-%d %H:%M:%S
500
Vinay Sajipa39c5712010-10-25 13:57:39 +0000501with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
502or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000503
Vinay Sajipa39c5712010-10-25 13:57:39 +0000504If the ``style`` is '%', the message format string uses
505``%(<dictionary key>)s`` styled string substitution; the possible keys are
506documented in :ref:`formatter-objects`. If the style is '{', the message format
507string is assumed to be compatible with :meth:`str.format` (using keyword
508arguments), while if the style is '$' then the message format string should
509conform to what is expected by :meth:`string.Template.substitute`.
510
511.. versionchanged:: 3.2
512 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000513
514The following message format string will log the time in a human-readable
515format, the severity of the message, and the contents of the message, in that
516order::
517
518 "%(asctime)s - %(levelname)s - %(message)s"
519
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000520Formatters use a user-configurable function to convert the creation time of a
521record to a tuple. By default, :func:`time.localtime` is used; to change this
522for a particular formatter instance, set the ``converter`` attribute of the
523instance to a function with the same signature as :func:`time.localtime` or
524:func:`time.gmtime`. To change it for all formatters, for example if you want
525all logging times to be shown in GMT, set the ``converter`` attribute in the
526Formatter class (to ``time.gmtime`` for GMT display).
527
Christian Heimes8b0facf2007-12-04 19:30:01 +0000528
529Configuring Logging
530^^^^^^^^^^^^^^^^^^^
531
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000532Programmers can configure logging in three ways:
533
5341. Creating loggers, handlers, and formatters explicitly using Python
535 code that calls the configuration methods listed above.
5362. Creating a logging config file and reading it using the :func:`fileConfig`
537 function.
5383. Creating a dictionary of configuration information and passing it
539 to the :func:`dictConfig` function.
540
541The following example configures a very simple logger, a console
542handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000543
544 import logging
545
546 # create logger
547 logger = logging.getLogger("simple_example")
548 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000549
Christian Heimes8b0facf2007-12-04 19:30:01 +0000550 # create console handler and set level to debug
551 ch = logging.StreamHandler()
552 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000553
Christian Heimes8b0facf2007-12-04 19:30:01 +0000554 # create formatter
555 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000556
Christian Heimes8b0facf2007-12-04 19:30:01 +0000557 # add formatter to ch
558 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000559
Christian Heimes8b0facf2007-12-04 19:30:01 +0000560 # add ch to logger
561 logger.addHandler(ch)
562
563 # "application" code
564 logger.debug("debug message")
565 logger.info("info message")
566 logger.warn("warn message")
567 logger.error("error message")
568 logger.critical("critical message")
569
570Running this module from the command line produces the following output::
571
572 $ python simple_logging_module.py
573 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
574 2005-03-19 15:10:26,620 - simple_example - INFO - info message
575 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
576 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
577 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
578
579The following Python module creates a logger, handler, and formatter nearly
580identical to those in the example listed above, with the only difference being
581the names of the objects::
582
583 import logging
584 import logging.config
585
586 logging.config.fileConfig("logging.conf")
587
588 # create logger
589 logger = logging.getLogger("simpleExample")
590
591 # "application" code
592 logger.debug("debug message")
593 logger.info("info message")
594 logger.warn("warn message")
595 logger.error("error message")
596 logger.critical("critical message")
597
598Here is the logging.conf file::
599
600 [loggers]
601 keys=root,simpleExample
602
603 [handlers]
604 keys=consoleHandler
605
606 [formatters]
607 keys=simpleFormatter
608
609 [logger_root]
610 level=DEBUG
611 handlers=consoleHandler
612
613 [logger_simpleExample]
614 level=DEBUG
615 handlers=consoleHandler
616 qualname=simpleExample
617 propagate=0
618
619 [handler_consoleHandler]
620 class=StreamHandler
621 level=DEBUG
622 formatter=simpleFormatter
623 args=(sys.stdout,)
624
625 [formatter_simpleFormatter]
626 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
627 datefmt=
628
629The output is nearly identical to that of the non-config-file-based example::
630
631 $ python simple_logging_config.py
632 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
633 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
634 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
635 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
636 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
637
638You can see that the config file approach has a few advantages over the Python
639code approach, mainly separation of configuration and code and the ability of
640noncoders to easily modify the logging properties.
641
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000642Note that the class names referenced in config files need to be either relative
643to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000644import mechanisms. Thus, you could use either
645:class:`handlers.WatchedFileHandler` (relative to the logging module) or
646``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
647and module ``mymodule``, where ``mypackage`` is available on the Python import
648path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000649
Benjamin Peterson56894b52010-06-28 00:16:12 +0000650In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000651dictionaries to hold configuration information. This provides a superset of the
652functionality of the config-file-based approach outlined above, and is the
653recommended configuration method for new applications and deployments. Because
654a Python dictionary is used to hold configuration information, and since you
655can populate that dictionary using different means, you have more options for
656configuration. For example, you can use a configuration file in JSON format,
657or, if you have access to YAML processing functionality, a file in YAML
658format, to populate the configuration dictionary. Or, of course, you can
659construct the dictionary in Python code, receive it in pickled form over a
660socket, or use whatever approach makes sense for your application.
661
662Here's an example of the same configuration as above, in YAML format for
663the new dictionary-based approach::
664
665 version: 1
666 formatters:
667 simple:
668 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
669 handlers:
670 console:
671 class: logging.StreamHandler
672 level: DEBUG
673 formatter: simple
674 stream: ext://sys.stdout
675 loggers:
676 simpleExample:
677 level: DEBUG
678 handlers: [console]
679 propagate: no
680 root:
681 level: DEBUG
682 handlers: [console]
683
684For more information about logging using a dictionary, see
685:ref:`logging-config-api`.
686
Vinay Sajipf234eb92010-12-12 17:37:27 +0000687What happens if no configuration is provided
688^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
689
690If no logging configuration is provided, it is possible to have a situation
691where a logging event needs to be output, but no handlers can be found to
692output the event. The behaviour of the logging package in these
693circumstances is dependent on the Python version.
694
695For versions of Python prior to 3.2, the behaviour is as follows:
696
697* If *logging.raiseExceptions* is *False* (production mode), the event is
698 silently dropped.
699
700* If *logging.raiseExceptions* is *True* (development mode), a message
701 "No handlers could be found for logger X.Y.Z" is printed once.
702
703In Python 3.2 and later, the behaviour is as follows:
704
705* The event is output using a 'handler of last resort", stored in
706 ``logging.lastResort``. This internal handler is not associated with any
707 logger, and acts like a :class:`StreamHandler` which writes the event
708 description message to the current value of ``sys.stderr`` (therefore
709 respecting any redirections which may be in effect). No formatting is
710 done on the message - just the bare event description message is printed.
711 The handler's level is set to ``WARNING``, so all events at this and
712 greater severities will be output.
713
714To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*.
715
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000716.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000717
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000718Configuring Logging for a Library
719^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
720
Vinay Sajipf234eb92010-12-12 17:37:27 +0000721When developing a library which uses logging, you should take care to
722document how the library uses logging - for example, the names of loggers
723used. Some consideration also needs to be given to its logging configuration.
724If the using application does not use logging, and library code makes logging
725calls, then (as described in the previous section) events of severity
726``WARNING`` and greater will be printed to ``sys.stderr``. This is regarded as
727the best default behaviour.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000728
Vinay Sajipf234eb92010-12-12 17:37:27 +0000729If for some reason you *don't* want these messages printed in the absence of
730any logging configuration, you can attach a do-nothing handler to the top-level
731logger for your library. This avoids the message being printed, since a handler
732will be always be found for the library's events: it just doesn't produce any
733output. If the library user configures logging for application use, presumably
734that configuration will add some handlers, and if levels are suitably
735configured then logging calls made in library code will send output to those
736handlers, as normal.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000737
Vinay Sajipf234eb92010-12-12 17:37:27 +0000738A do-nothing handler is included in the logging package: :class:`NullHandler`
739(since Python 3.1). An instance of this handler could be added to the top-level
740logger of the logging namespace used by the library (*if* you want to prevent
741your library's logged events being output to ``sys.stderr`` in the absence of
742logging configuration). If all logging by a library *foo* is done using loggers
743with names matching 'foo.x', 'foo.x.y', etc. then the code::
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000744
745 import logging
Vinay Sajipf234eb92010-12-12 17:37:27 +0000746 logging.getLogger('foo').addHandler(logging.NullHandler())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000747
748should have the desired effect. If an organisation produces a number of
Vinay Sajipf234eb92010-12-12 17:37:27 +0000749libraries, then the logger name specified can be 'orgname.foo' rather than
750just 'foo'.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000751
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000752**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
753than* :class:`NullHandler` *to your library's loggers*. This is because the
754configuration of handlers is the prerogative of the application developer who
755uses your library. The application developer knows their target audience and
756what handlers are most appropriate for their application: if you add handlers
757"under the hood", you might well interfere with their ability to carry out
758unit tests and deliver logs which suit their requirements.
759
Christian Heimes8b0facf2007-12-04 19:30:01 +0000760
761Logging Levels
762--------------
763
Georg Brandl116aa622007-08-15 14:28:22 +0000764The numeric values of logging levels are given in the following table. These are
765primarily of interest if you want to define your own levels, and need them to
766have specific values relative to the predefined levels. If you define a level
767with the same numeric value, it overwrites the predefined value; the predefined
768name is lost.
769
770+--------------+---------------+
771| Level | Numeric value |
772+==============+===============+
773| ``CRITICAL`` | 50 |
774+--------------+---------------+
775| ``ERROR`` | 40 |
776+--------------+---------------+
777| ``WARNING`` | 30 |
778+--------------+---------------+
779| ``INFO`` | 20 |
780+--------------+---------------+
781| ``DEBUG`` | 10 |
782+--------------+---------------+
783| ``NOTSET`` | 0 |
784+--------------+---------------+
785
786Levels can also be associated with loggers, being set either by the developer or
787through loading a saved logging configuration. When a logging method is called
788on a logger, the logger compares its own level with the level associated with
789the method call. If the logger's level is higher than the method call's, no
790logging message is actually generated. This is the basic mechanism controlling
791the verbosity of logging output.
792
793Logging messages are encoded as instances of the :class:`LogRecord` class. When
794a logger decides to actually log an event, a :class:`LogRecord` instance is
795created from the logging message.
796
797Logging messages are subjected to a dispatch mechanism through the use of
798:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
799class. Handlers are responsible for ensuring that a logged message (in the form
800of a :class:`LogRecord`) ends up in a particular location (or set of locations)
801which is useful for the target audience for that message (such as end users,
802support desk staff, system administrators, developers). Handlers are passed
803:class:`LogRecord` instances intended for particular destinations. Each logger
804can have zero, one or more handlers associated with it (via the
805:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
806directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000807of the logger* are called to dispatch the message (unless the *propagate* flag
808for a logger is set to a false value, at which point the passing to ancestor
809handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811Just as for loggers, handlers can have levels associated with them. A handler's
812level acts as a filter in the same way as a logger's level does. If a handler
813decides to actually dispatch an event, the :meth:`emit` method is used to send
814the message to its destination. Most user-defined subclasses of :class:`Handler`
815will need to override this :meth:`emit`.
816
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000817.. _custom-levels:
818
819Custom Levels
820^^^^^^^^^^^^^
821
822Defining your own levels is possible, but should not be necessary, as the
823existing levels have been chosen on the basis of practical experience.
824However, if you are convinced that you need custom levels, great care should
825be exercised when doing this, and it is possibly *a very bad idea to define
826custom levels if you are developing a library*. That's because if multiple
827library authors all define their own custom levels, there is a chance that
828the logging output from such multiple libraries used together will be
829difficult for the using developer to control and/or interpret, because a
830given numeric value might mean different things for different libraries.
831
832
Vinay Sajipf234eb92010-12-12 17:37:27 +0000833.. _useful-handlers:
834
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000835Useful Handlers
836---------------
837
Georg Brandl116aa622007-08-15 14:28:22 +0000838In addition to the base :class:`Handler` class, many useful subclasses are
839provided:
840
Vinay Sajip121a1c42010-09-08 10:46:15 +0000841#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000842 objects).
843
Vinay Sajip121a1c42010-09-08 10:46:15 +0000844#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000846.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000847
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000848#. :class:`BaseRotatingHandler` is the base class for handlers that
849 rotate log files at a certain point. It is not meant to be instantiated
850 directly. Instead, use :class:`RotatingFileHandler` or
851 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Vinay Sajip121a1c42010-09-08 10:46:15 +0000853#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000854 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Vinay Sajip121a1c42010-09-08 10:46:15 +0000856#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000857 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Vinay Sajip121a1c42010-09-08 10:46:15 +0000859#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000860 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000861
Vinay Sajip121a1c42010-09-08 10:46:15 +0000862#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000863 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000864
Vinay Sajip121a1c42010-09-08 10:46:15 +0000865#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000866 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000867
Vinay Sajip121a1c42010-09-08 10:46:15 +0000868#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000869 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000870
Vinay Sajip121a1c42010-09-08 10:46:15 +0000871#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000872 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
Vinay Sajip121a1c42010-09-08 10:46:15 +0000874#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000875 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000876
Vinay Sajip121a1c42010-09-08 10:46:15 +0000877#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000878 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000879
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000880#. :class:`WatchedFileHandler` instances watch the file they are
881 logging to. If the file changes, it is closed and reopened using the file
882 name. This handler is only useful on Unix-like systems; Windows does not
883 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000884
Vinay Sajip121a1c42010-09-08 10:46:15 +0000885#. :class:`QueueHandler` instances send messages to a queue, such as
886 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
887
Vinay Sajip30bf1222009-01-10 19:23:34 +0000888.. currentmodule:: logging
889
Georg Brandlf9734072008-12-07 15:30:06 +0000890#. :class:`NullHandler` instances do nothing with error messages. They are used
891 by library developers who want to use logging, but want to avoid the "No
892 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000893 the library user has not configured logging. See :ref:`library-config` for
894 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000895
896.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000897 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000898
Vinay Sajip121a1c42010-09-08 10:46:15 +0000899.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000900 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000901
Vinay Sajipa17775f2008-12-30 07:32:59 +0000902The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
903classes are defined in the core logging package. The other handlers are
904defined in a sub- module, :mod:`logging.handlers`. (There is also another
905sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000906
907Logged messages are formatted for presentation through instances of the
908:class:`Formatter` class. They are initialized with a format string suitable for
909use with the % operator and a dictionary.
910
911For formatting multiple messages in a batch, instances of
912:class:`BufferingFormatter` can be used. In addition to the format string (which
913is applied to each message in the batch), there is provision for header and
914trailer format strings.
915
916When filtering based on logger level and/or handler level is not enough,
917instances of :class:`Filter` can be added to both :class:`Logger` and
918:class:`Handler` instances (through their :meth:`addFilter` method). Before
919deciding to process a message further, both loggers and handlers consult all
920their filters for permission. If any filter returns a false value, the message
921is not processed further.
922
923The basic :class:`Filter` functionality allows filtering by specific logger
924name. If this feature is used, messages sent to the named logger and its
925children are allowed through the filter, and all others dropped.
926
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000927Module-Level Functions
928----------------------
929
Georg Brandl116aa622007-08-15 14:28:22 +0000930In addition to the classes described above, there are a number of module- level
931functions.
932
933
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000934.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000936 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000937 logger which is the root logger of the hierarchy. If specified, the name is
938 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
939 Choice of these names is entirely up to the developer who is using logging.
940
941 All calls to this function with a given name return the same logger instance.
942 This means that logger instances never need to be passed between different parts
943 of an application.
944
945
946.. function:: getLoggerClass()
947
948 Return either the standard :class:`Logger` class, or the last class passed to
949 :func:`setLoggerClass`. This function may be called from within a new class
950 definition, to ensure that installing a customised :class:`Logger` class will
951 not undo customisations already applied by other code. For example::
952
953 class MyLogger(logging.getLoggerClass()):
954 # ... override behaviour here
955
956
Vinay Sajip61561522010-12-03 11:50:38 +0000957.. function:: getLogRecordFactory()
958
959 Return a callable which is used to create a :class:`LogRecord`.
960
961 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000962 This function has been provided, along with :func:`setLogRecordFactory`,
963 to allow developers more control over how the :class:`LogRecord`
964 representing a logging event is constructed.
965
966 See :func:`setLogRecordFactory` for more information about the how the
967 factory is called.
968
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000969.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000970
971 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
972 message format string, and the *args* are the arguments which are merged into
973 *msg* using the string formatting operator. (Note that this means that you can
974 use keywords in the format string, together with a single dictionary argument.)
975
Vinay Sajip8593ae62010-11-14 21:33:04 +0000976 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +0000977 which, if it does not evaluate as false, causes exception information to be
978 added to the logging message. If an exception tuple (in the format returned by
979 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
980 is called to get the exception information.
981
Vinay Sajip8593ae62010-11-14 21:33:04 +0000982 The second optional keyword argument is *stack_info*, which defaults to
983 False. If specified as True, stack information is added to the logging
984 message, including the actual logging call. Note that this is not the same
985 stack information as that displayed through specifying *exc_info*: The
986 former is stack frames from the bottom of the stack up to the logging call
987 in the current thread, whereas the latter is information about stack frames
988 which have been unwound, following an exception, while searching for
989 exception handlers.
990
991 You can specify *stack_info* independently of *exc_info*, e.g. to just show
992 how you got to a certain point in your code, even when no exceptions were
993 raised. The stack frames are printed following a header line which says::
994
995 Stack (most recent call last):
996
997 This mimics the `Traceback (most recent call last):` which is used when
998 displaying exception frames.
999
1000 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001001 dictionary which is used to populate the __dict__ of the LogRecord created for
1002 the logging event with user-defined attributes. These custom attributes can then
1003 be used as you like. For example, they could be incorporated into logged
1004 messages. For example::
1005
1006 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1007 logging.basicConfig(format=FORMAT)
1008 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
1009 logging.warning("Protocol problem: %s", "connection reset", extra=d)
1010
Vinay Sajip4039aff2010-09-11 10:25:28 +00001011 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1014
1015 The keys in the dictionary passed in *extra* should not clash with the keys used
1016 by the logging system. (See the :class:`Formatter` documentation for more
1017 information on which keys are used by the logging system.)
1018
1019 If you choose to use these attributes in logged messages, you need to exercise
1020 some care. In the above example, for instance, the :class:`Formatter` has been
1021 set up with a format string which expects 'clientip' and 'user' in the attribute
1022 dictionary of the LogRecord. If these are missing, the message will not be
1023 logged because a string formatting exception will occur. So in this case, you
1024 always need to pass the *extra* dictionary with these keys.
1025
1026 While this might be annoying, this feature is intended for use in specialized
1027 circumstances, such as multi-threaded servers where the same code executes in
1028 many contexts, and interesting conditions which arise are dependent on this
1029 context (such as remote client IP address and authenticated user name, in the
1030 above example). In such circumstances, it is likely that specialized
1031 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1032
Vinay Sajip8593ae62010-11-14 21:33:04 +00001033 .. versionadded:: 3.2
1034 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +00001035
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001036.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001037
1038 Logs a message with level :const:`INFO` on the root logger. The arguments are
1039 interpreted as for :func:`debug`.
1040
1041
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001042.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001043
1044 Logs a message with level :const:`WARNING` on the root logger. The arguments are
1045 interpreted as for :func:`debug`.
1046
1047
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001048.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001049
1050 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1051 interpreted as for :func:`debug`.
1052
1053
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001054.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001055
1056 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1057 are interpreted as for :func:`debug`.
1058
1059
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001060.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001061
1062 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1063 interpreted as for :func:`debug`. Exception info is added to the logging
1064 message. This function should only be called from an exception handler.
1065
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001066.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068 Logs a message with level *level* on the root logger. The other arguments are
1069 interpreted as for :func:`debug`.
1070
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001071 PLEASE NOTE: The above module-level functions which delegate to the root
1072 logger should *not* be used in threads, in versions of Python earlier than
1073 2.7.1 and 3.2, unless at least one handler has been added to the root
1074 logger *before* the threads are started. These convenience functions call
1075 :func:`basicConfig` to ensure that at least one handler is available; in
1076 earlier versions of Python, this can (under rare circumstances) lead to
1077 handlers being added multiple times to the root logger, which can in turn
1078 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001079
1080.. function:: disable(lvl)
1081
1082 Provides an overriding level *lvl* for all loggers which takes precedence over
1083 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001084 output down across the whole application, this function can be useful. Its
1085 effect is to disable all logging calls of severity *lvl* and below, so that
1086 if you call it with a value of INFO, then all INFO and DEBUG events would be
1087 discarded, whereas those of severity WARNING and above would be processed
1088 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001089
1090
1091.. function:: addLevelName(lvl, levelName)
1092
1093 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1094 used to map numeric levels to a textual representation, for example when a
1095 :class:`Formatter` formats a message. This function can also be used to define
1096 your own levels. The only constraints are that all levels used must be
1097 registered using this function, levels should be positive integers and they
1098 should increase in increasing order of severity.
1099
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001100 NOTE: If you are thinking of defining your own levels, please see the section
1101 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
1103.. function:: getLevelName(lvl)
1104
1105 Returns the textual representation of logging level *lvl*. If the level is one
1106 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1107 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1108 have associated levels with names using :func:`addLevelName` then the name you
1109 have associated with *lvl* is returned. If a numeric value corresponding to one
1110 of the defined levels is passed in, the corresponding string representation is
1111 returned. Otherwise, the string "Level %s" % lvl is returned.
1112
1113
1114.. function:: makeLogRecord(attrdict)
1115
1116 Creates and returns a new :class:`LogRecord` instance whose attributes are
1117 defined by *attrdict*. This function is useful for taking a pickled
1118 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1119 it as a :class:`LogRecord` instance at the receiving end.
1120
1121
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001122.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001123
1124 Does basic configuration for the logging system by creating a
1125 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001126 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001127 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1128 if no handlers are defined for the root logger.
1129
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001130 This function does nothing if the root logger already has handlers
1131 configured for it.
1132
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001133 PLEASE NOTE: This function should be called from the main thread
1134 before other threads are started. In versions of Python prior to
1135 2.7.1 and 3.2, if this function is called from multiple threads,
1136 it is possible (in rare circumstances) that a handler will be added
1137 to the root logger more than once, leading to unexpected results
1138 such as messages being duplicated in the log.
1139
Georg Brandl116aa622007-08-15 14:28:22 +00001140 The following keyword arguments are supported.
1141
1142 +--------------+---------------------------------------------+
1143 | Format | Description |
1144 +==============+=============================================+
1145 | ``filename`` | Specifies that a FileHandler be created, |
1146 | | using the specified filename, rather than a |
1147 | | StreamHandler. |
1148 +--------------+---------------------------------------------+
1149 | ``filemode`` | Specifies the mode to open the file, if |
1150 | | filename is specified (if filemode is |
1151 | | unspecified, it defaults to 'a'). |
1152 +--------------+---------------------------------------------+
1153 | ``format`` | Use the specified format string for the |
1154 | | handler. |
1155 +--------------+---------------------------------------------+
1156 | ``datefmt`` | Use the specified date/time format. |
1157 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001158 | ``style`` | If ``format`` is specified, use this style |
1159 | | for the format string. One of '%', '{' or |
1160 | | '$' for %-formatting, :meth:`str.format` or |
1161 | | :class:`string.Template` respectively, and |
1162 | | defaulting to '%' if not specified. |
1163 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001164 | ``level`` | Set the root logger level to the specified |
1165 | | level. |
1166 +--------------+---------------------------------------------+
1167 | ``stream`` | Use the specified stream to initialize the |
1168 | | StreamHandler. Note that this argument is |
1169 | | incompatible with 'filename' - if both are |
1170 | | present, 'stream' is ignored. |
1171 +--------------+---------------------------------------------+
1172
Vinay Sajipc5b27302010-10-31 14:59:16 +00001173 .. versionchanged:: 3.2
1174 The ``style`` argument was added.
1175
1176
Georg Brandl116aa622007-08-15 14:28:22 +00001177.. function:: shutdown()
1178
1179 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001180 closing all handlers. This should be called at application exit and no
1181 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001182
1183
1184.. function:: setLoggerClass(klass)
1185
1186 Tells the logging system to use the class *klass* when instantiating a logger.
1187 The class should define :meth:`__init__` such that only a name argument is
1188 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1189 function is typically called before any loggers are instantiated by applications
1190 which need to use custom logger behavior.
1191
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001192
Vinay Sajip61561522010-12-03 11:50:38 +00001193.. function:: setLogRecordFactory(factory)
1194
1195 Set a callable which is used to create a :class:`LogRecord`.
1196
1197 :param factory: The factory callable to be used to instantiate a log record.
1198
1199 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001200 This function has been provided, along with :func:`getLogRecordFactory`, to
1201 allow developers more control over how the :class:`LogRecord` representing
1202 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001203
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001204 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001205
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001206 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, \*\*kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001207
1208 :name: The logger name.
1209 :level: The logging level (numeric).
1210 :fn: The full pathname of the file where the logging call was made.
1211 :lno: The line number in the file where the logging call was made.
1212 :msg: The logging message.
1213 :args: The arguments for the logging message.
1214 :exc_info: An exception tuple, or None.
1215 :func: The name of the function or method which invoked the logging
1216 call.
1217 :sinfo: A stack traceback such as is provided by
1218 :func:`traceback.print_stack`, showing the call hierarchy.
1219 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001220
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001221
Georg Brandl116aa622007-08-15 14:28:22 +00001222.. seealso::
1223
1224 :pep:`282` - A Logging System
1225 The proposal which described this feature for inclusion in the Python standard
1226 library.
1227
Christian Heimes255f53b2007-12-08 15:33:56 +00001228 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001229 This is the original source for the :mod:`logging` package. The version of the
1230 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1231 and 2.2.x, which do not include the :mod:`logging` package in the standard
1232 library.
1233
Vinay Sajip4039aff2010-09-11 10:25:28 +00001234.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001235
1236Logger Objects
1237--------------
1238
1239Loggers have the following attributes and methods. Note that Loggers are never
1240instantiated directly, but always through the module-level function
1241``logging.getLogger(name)``.
1242
Vinay Sajip0258ce82010-09-22 20:34:53 +00001243.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001244
1245.. attribute:: Logger.propagate
1246
1247 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001248 its child loggers to the handlers of higher level (ancestor) loggers. The
1249 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251
1252.. method:: Logger.setLevel(lvl)
1253
1254 Sets the threshold for this logger to *lvl*. Logging messages which are less
1255 severe than *lvl* will be ignored. When a logger is created, the level is set to
1256 :const:`NOTSET` (which causes all messages to be processed when the logger is
1257 the root logger, or delegation to the parent when the logger is a non-root
1258 logger). Note that the root logger is created with level :const:`WARNING`.
1259
1260 The term "delegation to the parent" means that if a logger has a level of
1261 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1262 a level other than NOTSET is found, or the root is reached.
1263
1264 If an ancestor is found with a level other than NOTSET, then that ancestor's
1265 level is treated as the effective level of the logger where the ancestor search
1266 began, and is used to determine how a logging event is handled.
1267
1268 If the root is reached, and it has a level of NOTSET, then all messages will be
1269 processed. Otherwise, the root's level will be used as the effective level.
1270
1271
1272.. method:: Logger.isEnabledFor(lvl)
1273
1274 Indicates if a message of severity *lvl* would be processed by this logger.
1275 This method checks first the module-level level set by
1276 ``logging.disable(lvl)`` and then the logger's effective level as determined
1277 by :meth:`getEffectiveLevel`.
1278
1279
1280.. method:: Logger.getEffectiveLevel()
1281
1282 Indicates the effective level for this logger. If a value other than
1283 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1284 the hierarchy is traversed towards the root until a value other than
1285 :const:`NOTSET` is found, and that value is returned.
1286
1287
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001288.. method:: Logger.getChild(suffix)
1289
1290 Returns a logger which is a descendant to this logger, as determined by the suffix.
1291 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1292 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1293 convenience method, useful when the parent logger is named using e.g. ``__name__``
1294 rather than a literal string.
1295
1296 .. versionadded:: 3.2
1297
Georg Brandl67b21b72010-08-17 15:07:14 +00001298
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001299.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1302 message format string, and the *args* are the arguments which are merged into
1303 *msg* using the string formatting operator. (Note that this means that you can
1304 use keywords in the format string, together with a single dictionary argument.)
1305
Vinay Sajip8593ae62010-11-14 21:33:04 +00001306 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001307 which, if it does not evaluate as false, causes exception information to be
1308 added to the logging message. If an exception tuple (in the format returned by
1309 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1310 is called to get the exception information.
1311
Vinay Sajip8593ae62010-11-14 21:33:04 +00001312 The second optional keyword argument is *stack_info*, which defaults to
1313 False. If specified as True, stack information is added to the logging
1314 message, including the actual logging call. Note that this is not the same
1315 stack information as that displayed through specifying *exc_info*: The
1316 former is stack frames from the bottom of the stack up to the logging call
1317 in the current thread, whereas the latter is information about stack frames
1318 which have been unwound, following an exception, while searching for
1319 exception handlers.
1320
1321 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1322 how you got to a certain point in your code, even when no exceptions were
1323 raised. The stack frames are printed following a header line which says::
1324
1325 Stack (most recent call last):
1326
1327 This mimics the `Traceback (most recent call last):` which is used when
1328 displaying exception frames.
1329
1330 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001331 dictionary which is used to populate the __dict__ of the LogRecord created for
1332 the logging event with user-defined attributes. These custom attributes can then
1333 be used as you like. For example, they could be incorporated into logged
1334 messages. For example::
1335
1336 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1337 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001338 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001339 logger = logging.getLogger("tcpserver")
1340 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1341
1342 would print something like ::
1343
1344 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1345
1346 The keys in the dictionary passed in *extra* should not clash with the keys used
1347 by the logging system. (See the :class:`Formatter` documentation for more
1348 information on which keys are used by the logging system.)
1349
1350 If you choose to use these attributes in logged messages, you need to exercise
1351 some care. In the above example, for instance, the :class:`Formatter` has been
1352 set up with a format string which expects 'clientip' and 'user' in the attribute
1353 dictionary of the LogRecord. If these are missing, the message will not be
1354 logged because a string formatting exception will occur. So in this case, you
1355 always need to pass the *extra* dictionary with these keys.
1356
1357 While this might be annoying, this feature is intended for use in specialized
1358 circumstances, such as multi-threaded servers where the same code executes in
1359 many contexts, and interesting conditions which arise are dependent on this
1360 context (such as remote client IP address and authenticated user name, in the
1361 above example). In such circumstances, it is likely that specialized
1362 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1363
Vinay Sajip8593ae62010-11-14 21:33:04 +00001364 .. versionadded:: 3.2
1365 The *stack_info* parameter was added.
1366
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001368.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001369
1370 Logs a message with level :const:`INFO` on this logger. The arguments are
1371 interpreted as for :meth:`debug`.
1372
1373
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001374.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001375
1376 Logs a message with level :const:`WARNING` on this logger. The arguments are
1377 interpreted as for :meth:`debug`.
1378
1379
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001380.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001381
1382 Logs a message with level :const:`ERROR` on this logger. The arguments are
1383 interpreted as for :meth:`debug`.
1384
1385
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001386.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001387
1388 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1389 interpreted as for :meth:`debug`.
1390
1391
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001392.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001393
1394 Logs a message with integer level *lvl* on this logger. The other arguments are
1395 interpreted as for :meth:`debug`.
1396
1397
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001398.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001399
1400 Logs a message with level :const:`ERROR` on this logger. The arguments are
1401 interpreted as for :meth:`debug`. Exception info is added to the logging
1402 message. This method should only be called from an exception handler.
1403
1404
1405.. method:: Logger.addFilter(filt)
1406
1407 Adds the specified filter *filt* to this logger.
1408
1409
1410.. method:: Logger.removeFilter(filt)
1411
1412 Removes the specified filter *filt* from this logger.
1413
1414
1415.. method:: Logger.filter(record)
1416
1417 Applies this logger's filters to the record and returns a true value if the
1418 record is to be processed.
1419
1420
1421.. method:: Logger.addHandler(hdlr)
1422
1423 Adds the specified handler *hdlr* to this logger.
1424
1425
1426.. method:: Logger.removeHandler(hdlr)
1427
1428 Removes the specified handler *hdlr* from this logger.
1429
1430
Vinay Sajip8593ae62010-11-14 21:33:04 +00001431.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001432
1433 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001434 number, function name and stack information as a 4-element tuple. The stack
1435 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001436
Georg Brandl116aa622007-08-15 14:28:22 +00001437
1438.. method:: Logger.handle(record)
1439
1440 Handles a record by passing it to all handlers associated with this logger and
1441 its ancestors (until a false value of *propagate* is found). This method is used
1442 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001443 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001444
1445
Vinay Sajip8593ae62010-11-14 21:33:04 +00001446.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001447
1448 This is a factory method which can be overridden in subclasses to create
1449 specialized :class:`LogRecord` instances.
1450
Vinay Sajip83eadd12010-09-20 10:31:18 +00001451.. method:: Logger.hasHandlers()
1452
1453 Checks to see if this logger has any handlers configured. This is done by
1454 looking for handlers in this logger and its parents in the logger hierarchy.
1455 Returns True if a handler was found, else False. The method stops searching
1456 up the hierarchy whenever a logger with the "propagate" attribute set to
1457 False is found - that will be the last logger which is checked for the
1458 existence of handlers.
1459
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001460 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001461
Vinay Sajipa18b9592010-12-12 13:20:55 +00001462.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001463
1464Basic example
1465-------------
1466
Georg Brandl116aa622007-08-15 14:28:22 +00001467The :mod:`logging` package provides a lot of flexibility, and its configuration
1468can appear daunting. This section demonstrates that simple use of the logging
1469package is possible.
1470
1471The simplest example shows logging to the console::
1472
1473 import logging
1474
1475 logging.debug('A debug message')
1476 logging.info('Some information')
1477 logging.warning('A shot across the bows')
1478
1479If you run the above script, you'll see this::
1480
1481 WARNING:root:A shot across the bows
1482
1483Because no particular logger was specified, the system used the root logger. The
1484debug and info messages didn't appear because by default, the root logger is
1485configured to only handle messages with a severity of WARNING or above. The
1486message format is also a configuration default, as is the output destination of
1487the messages - ``sys.stderr``. The severity level, the message format and
1488destination can be easily changed, as shown in the example below::
1489
1490 import logging
1491
1492 logging.basicConfig(level=logging.DEBUG,
1493 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001494 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001495 filemode='w')
1496 logging.debug('A debug message')
1497 logging.info('Some information')
1498 logging.warning('A shot across the bows')
1499
1500The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001501which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001502something like the following::
1503
1504 2004-07-02 13:00:08,743 DEBUG A debug message
1505 2004-07-02 13:00:08,743 INFO Some information
1506 2004-07-02 13:00:08,743 WARNING A shot across the bows
1507
1508This time, all messages with a severity of DEBUG or above were handled, and the
1509format of the messages was also changed, and output went to the specified file
1510rather than the console.
1511
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001512.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001513
1514Formatting uses the old Python string formatting - see section
1515:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001516specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1517documentation.
1518
1519+-------------------+-----------------------------------------------+
1520| Format | Description |
1521+===================+===============================================+
1522| ``%(name)s`` | Name of the logger (logging channel). |
1523+-------------------+-----------------------------------------------+
1524| ``%(levelname)s`` | Text logging level for the message |
1525| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1526| | ``'ERROR'``, ``'CRITICAL'``). |
1527+-------------------+-----------------------------------------------+
1528| ``%(asctime)s`` | Human-readable time when the |
1529| | :class:`LogRecord` was created. By default |
1530| | this is of the form "2003-07-08 16:49:45,896" |
1531| | (the numbers after the comma are millisecond |
1532| | portion of the time). |
1533+-------------------+-----------------------------------------------+
1534| ``%(message)s`` | The logged message. |
1535+-------------------+-----------------------------------------------+
1536
1537To change the date/time format, you can pass an additional keyword parameter,
1538*datefmt*, as in the following::
1539
1540 import logging
1541
1542 logging.basicConfig(level=logging.DEBUG,
1543 format='%(asctime)s %(levelname)-8s %(message)s',
1544 datefmt='%a, %d %b %Y %H:%M:%S',
1545 filename='/temp/myapp.log',
1546 filemode='w')
1547 logging.debug('A debug message')
1548 logging.info('Some information')
1549 logging.warning('A shot across the bows')
1550
1551which would result in output like ::
1552
1553 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1554 Fri, 02 Jul 2004 13:06:18 INFO Some information
1555 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1556
1557The date format string follows the requirements of :func:`strftime` - see the
1558documentation for the :mod:`time` module.
1559
1560If, instead of sending logging output to the console or a file, you'd rather use
1561a file-like object which you have created separately, you can pass it to
1562:func:`basicConfig` using the *stream* keyword argument. Note that if both
1563*stream* and *filename* keyword arguments are passed, the *stream* argument is
1564ignored.
1565
1566Of course, you can put variable information in your output. To do this, simply
1567have the message be a format string and pass in additional arguments containing
1568the variable information, as in the following example::
1569
1570 import logging
1571
1572 logging.basicConfig(level=logging.DEBUG,
1573 format='%(asctime)s %(levelname)-8s %(message)s',
1574 datefmt='%a, %d %b %Y %H:%M:%S',
1575 filename='/temp/myapp.log',
1576 filemode='w')
1577 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1578
1579which would result in ::
1580
1581 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1582
1583
Vinay Sajipa18b9592010-12-12 13:20:55 +00001584Using file rotation
1585^^^^^^^^^^^^^^^^^^^
1586
1587.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1588.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1589
1590Sometimes you want to let a log file grow to a certain size, then open a new
1591file and log to that. You may want to keep a certain number of these files, and
1592when that many files have been created, rotate the files so that the number of
1593files and the size of the files both remin bounded. For this usage pattern, the
1594logging package provides a :class:`RotatingFileHandler`::
1595
1596 import glob
1597 import logging
1598 import logging.handlers
1599
1600 LOG_FILENAME = 'logging_rotatingfile_example.out'
1601
1602 # Set up a specific logger with our desired output level
1603 my_logger = logging.getLogger('MyLogger')
1604 my_logger.setLevel(logging.DEBUG)
1605
1606 # Add the log message handler to the logger
1607 handler = logging.handlers.RotatingFileHandler(
1608 LOG_FILENAME, maxBytes=20, backupCount=5)
1609
1610 my_logger.addHandler(handler)
1611
1612 # Log some messages
1613 for i in range(20):
1614 my_logger.debug('i = %d' % i)
1615
1616 # See what files are created
1617 logfiles = glob.glob('%s*' % LOG_FILENAME)
1618
1619 for filename in logfiles:
1620 print(filename)
1621
1622The result should be 6 separate files, each with part of the log history for the
1623application::
1624
1625 logging_rotatingfile_example.out
1626 logging_rotatingfile_example.out.1
1627 logging_rotatingfile_example.out.2
1628 logging_rotatingfile_example.out.3
1629 logging_rotatingfile_example.out.4
1630 logging_rotatingfile_example.out.5
1631
1632The most current file is always :file:`logging_rotatingfile_example.out`,
1633and each time it reaches the size limit it is renamed with the suffix
1634``.1``. Each of the existing backup files is renamed to increment the suffix
1635(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1636
1637Obviously this example sets the log length much much too small as an extreme
1638example. You would want to set *maxBytes* to an appropriate value.
1639
1640
1641The logger, handler, and log message call each specify a level. The log message
1642is only emitted if the handler and logger are configured to emit messages of
1643that level or lower. For example, if a message is ``CRITICAL``, and the logger
1644is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1645the logger is set to produce only ``ERROR``\s, the message is not emitted::
1646
1647 import logging
1648 import sys
1649
1650 LEVELS = {'debug': logging.DEBUG,
1651 'info': logging.INFO,
1652 'warning': logging.WARNING,
1653 'error': logging.ERROR,
1654 'critical': logging.CRITICAL}
1655
1656 if len(sys.argv) > 1:
1657 level_name = sys.argv[1]
1658 level = LEVELS.get(level_name, logging.NOTSET)
1659 logging.basicConfig(level=level)
1660
1661 logging.debug('This is a debug message')
1662 logging.info('This is an info message')
1663 logging.warning('This is a warning message')
1664 logging.error('This is an error message')
1665 logging.critical('This is a critical error message')
1666
1667Run the script with an argument like 'debug' or 'warning' to see which messages
1668show up at different levels::
1669
1670 $ python logging_level_example.py debug
1671 DEBUG:root:This is a debug message
1672 INFO:root:This is an info message
1673 WARNING:root:This is a warning message
1674 ERROR:root:This is an error message
1675 CRITICAL:root:This is a critical error message
1676
1677 $ python logging_level_example.py info
1678 INFO:root:This is an info message
1679 WARNING:root:This is a warning message
1680 ERROR:root:This is an error message
1681 CRITICAL:root:This is a critical error message
1682
1683You will notice that these log messages all have ``root`` embedded in them. The
1684logging module supports a hierarchy of loggers with different names. An easy
1685way to tell where a specific log message comes from is to use a separate logger
1686object for each of your modules. Each new logger "inherits" the configuration
1687of its parent, and log messages sent to a logger include the name of that
1688logger. Optionally, each logger can be configured differently, so that messages
1689from different modules are handled in different ways. Let's look at a simple
1690example of how to log from different modules so it is easy to trace the source
1691of the message::
1692
1693 import logging
1694
1695 logging.basicConfig(level=logging.WARNING)
1696
1697 logger1 = logging.getLogger('package1.module1')
1698 logger2 = logging.getLogger('package2.module2')
1699
1700 logger1.warning('This message comes from one module')
1701 logger2.warning('And this message comes from another module')
1702
1703And the output::
1704
1705 $ python logging_modules_example.py
1706 WARNING:package1.module1:This message comes from one module
1707 WARNING:package2.module2:And this message comes from another module
1708
1709There are many more options for configuring logging, including different log
1710message formatting options, having messages delivered to multiple destinations,
1711and changing the configuration of a long-running application on the fly using a
1712socket interface. All of these options are covered in depth in the library
1713module documentation.
1714
1715
Georg Brandl116aa622007-08-15 14:28:22 +00001716.. _multiple-destinations:
1717
1718Logging to multiple destinations
1719--------------------------------
1720
1721Let's say you want to log to console and file with different message formats and
1722in differing circumstances. Say you want to log messages with levels of DEBUG
1723and higher to file, and those messages at level INFO and higher to the console.
1724Let's also assume that the file should contain timestamps, but the console
1725messages should not. Here's how you can achieve this::
1726
1727 import logging
1728
1729 # set up logging to file - see previous section for more details
1730 logging.basicConfig(level=logging.DEBUG,
1731 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1732 datefmt='%m-%d %H:%M',
1733 filename='/temp/myapp.log',
1734 filemode='w')
1735 # define a Handler which writes INFO messages or higher to the sys.stderr
1736 console = logging.StreamHandler()
1737 console.setLevel(logging.INFO)
1738 # set a format which is simpler for console use
1739 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1740 # tell the handler to use this format
1741 console.setFormatter(formatter)
1742 # add the handler to the root logger
1743 logging.getLogger('').addHandler(console)
1744
1745 # Now, we can log to the root logger, or any other logger. First the root...
1746 logging.info('Jackdaws love my big sphinx of quartz.')
1747
1748 # Now, define a couple of other loggers which might represent areas in your
1749 # application:
1750
1751 logger1 = logging.getLogger('myapp.area1')
1752 logger2 = logging.getLogger('myapp.area2')
1753
1754 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1755 logger1.info('How quickly daft jumping zebras vex.')
1756 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1757 logger2.error('The five boxing wizards jump quickly.')
1758
1759When you run this, on the console you will see ::
1760
1761 root : INFO Jackdaws love my big sphinx of quartz.
1762 myapp.area1 : INFO How quickly daft jumping zebras vex.
1763 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1764 myapp.area2 : ERROR The five boxing wizards jump quickly.
1765
1766and in the file you will see something like ::
1767
1768 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1769 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1770 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1771 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1772 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1773
1774As you can see, the DEBUG message only shows up in the file. The other messages
1775are sent to both destinations.
1776
1777This example uses console and file handlers, but you can use any number and
1778combination of handlers you choose.
1779
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001780.. _logging-exceptions:
1781
1782Exceptions raised during logging
1783--------------------------------
1784
1785The logging package is designed to swallow exceptions which occur while logging
1786in production. This is so that errors which occur while handling logging events
1787- such as logging misconfiguration, network or other similar errors - do not
1788cause the application using logging to terminate prematurely.
1789
1790:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1791swallowed. Other exceptions which occur during the :meth:`emit` method of a
1792:class:`Handler` subclass are passed to its :meth:`handleError` method.
1793
1794The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001795to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1796traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001797
Georg Brandlef871f62010-03-12 10:06:40 +00001798**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001799during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001800occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001801usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001802
Christian Heimes790c8232008-01-07 21:14:23 +00001803.. _context-info:
1804
1805Adding contextual information to your logging output
1806----------------------------------------------------
1807
1808Sometimes you want logging output to contain contextual information in
1809addition to the parameters passed to the logging call. For example, in a
1810networked application, it may be desirable to log client-specific information
1811in the log (e.g. remote client's username, or IP address). Although you could
1812use the *extra* parameter to achieve this, it's not always convenient to pass
1813the information in this way. While it might be tempting to create
1814:class:`Logger` instances on a per-connection basis, this is not a good idea
1815because these instances are not garbage collected. While this is not a problem
1816in practice, when the number of :class:`Logger` instances is dependent on the
1817level of granularity you want to use in logging an application, it could
1818be hard to manage if the number of :class:`Logger` instances becomes
1819effectively unbounded.
1820
Vinay Sajipc31be632010-09-06 22:18:20 +00001821
1822Using LoggerAdapters to impart contextual information
1823^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1824
Christian Heimes04c420f2008-01-18 18:40:46 +00001825An easy way in which you can pass contextual information to be output along
1826with logging event information is to use the :class:`LoggerAdapter` class.
1827This class is designed to look like a :class:`Logger`, so that you can call
1828:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1829:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1830same signatures as their counterparts in :class:`Logger`, so you can use the
1831two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001832
Christian Heimes04c420f2008-01-18 18:40:46 +00001833When you create an instance of :class:`LoggerAdapter`, you pass it a
1834:class:`Logger` instance and a dict-like object which contains your contextual
1835information. When you call one of the logging methods on an instance of
1836:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1837:class:`Logger` passed to its constructor, and arranges to pass the contextual
1838information in the delegated call. Here's a snippet from the code of
1839:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001840
Christian Heimes04c420f2008-01-18 18:40:46 +00001841 def debug(self, msg, *args, **kwargs):
1842 """
1843 Delegate a debug call to the underlying logger, after adding
1844 contextual information from this adapter instance.
1845 """
1846 msg, kwargs = self.process(msg, kwargs)
1847 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001848
Christian Heimes04c420f2008-01-18 18:40:46 +00001849The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1850information is added to the logging output. It's passed the message and
1851keyword arguments of the logging call, and it passes back (potentially)
1852modified versions of these to use in the call to the underlying logger. The
1853default implementation of this method leaves the message alone, but inserts
1854an "extra" key in the keyword argument whose value is the dict-like object
1855passed to the constructor. Of course, if you had passed an "extra" keyword
1856argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001857
Christian Heimes04c420f2008-01-18 18:40:46 +00001858The advantage of using "extra" is that the values in the dict-like object are
1859merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1860customized strings with your :class:`Formatter` instances which know about
1861the keys of the dict-like object. If you need a different method, e.g. if you
1862want to prepend or append the contextual information to the message string,
1863you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1864to do what you need. Here's an example script which uses this class, which
1865also illustrates what dict-like behaviour is needed from an arbitrary
1866"dict-like" object for use in the constructor::
1867
Christian Heimes587c2bf2008-01-19 16:21:02 +00001868 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001869
Christian Heimes587c2bf2008-01-19 16:21:02 +00001870 class ConnInfo:
1871 """
1872 An example class which shows how an arbitrary class can be used as
1873 the 'extra' context information repository passed to a LoggerAdapter.
1874 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001875
Christian Heimes587c2bf2008-01-19 16:21:02 +00001876 def __getitem__(self, name):
1877 """
1878 To allow this instance to look like a dict.
1879 """
1880 from random import choice
1881 if name == "ip":
1882 result = choice(["127.0.0.1", "192.168.0.1"])
1883 elif name == "user":
1884 result = choice(["jim", "fred", "sheila"])
1885 else:
1886 result = self.__dict__.get(name, "?")
1887 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001888
Christian Heimes587c2bf2008-01-19 16:21:02 +00001889 def __iter__(self):
1890 """
1891 To allow iteration over keys, which will be merged into
1892 the LogRecord dict before formatting and output.
1893 """
1894 keys = ["ip", "user"]
1895 keys.extend(self.__dict__.keys())
1896 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001897
Christian Heimes587c2bf2008-01-19 16:21:02 +00001898 if __name__ == "__main__":
1899 from random import choice
1900 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1901 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1902 { "ip" : "123.231.231.123", "user" : "sheila" })
1903 logging.basicConfig(level=logging.DEBUG,
1904 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1905 a1.debug("A debug message")
1906 a1.info("An info message with %s", "some parameters")
1907 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1908 for x in range(10):
1909 lvl = choice(levels)
1910 lvlname = logging.getLevelName(lvl)
1911 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001912
1913When this script is run, the output should look something like this::
1914
Christian Heimes587c2bf2008-01-19 16:21:02 +00001915 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1916 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1917 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
1918 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
1919 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
1920 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
1921 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
1922 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
1923 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
1924 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
1925 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
1926 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 +00001927
Christian Heimes790c8232008-01-07 21:14:23 +00001928
Vinay Sajipac007992010-09-17 12:45:26 +00001929.. _filters-contextual:
1930
Vinay Sajipc31be632010-09-06 22:18:20 +00001931Using Filters to impart contextual information
1932^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1933
1934You can also add contextual information to log output using a user-defined
1935:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1936passed to them, including adding additional attributes which can then be output
1937using a suitable format string, or if needed a custom :class:`Formatter`.
1938
1939For example in a web application, the request being processed (or at least,
1940the interesting parts of it) can be stored in a threadlocal
1941(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1942add, say, information from the request - say, the remote IP address and remote
1943user's username - to the ``LogRecord``, using the attribute names 'ip' and
1944'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1945string can be used to get similar output to that shown above. Here's an example
1946script::
1947
1948 import logging
1949 from random import choice
1950
1951 class ContextFilter(logging.Filter):
1952 """
1953 This is a filter which injects contextual information into the log.
1954
1955 Rather than use actual contextual information, we just use random
1956 data in this demo.
1957 """
1958
1959 USERS = ['jim', 'fred', 'sheila']
1960 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1961
1962 def filter(self, record):
1963
1964 record.ip = choice(ContextFilter.IPS)
1965 record.user = choice(ContextFilter.USERS)
1966 return True
1967
1968 if __name__ == "__main__":
1969 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1970 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1971 { "ip" : "123.231.231.123", "user" : "sheila" })
1972 logging.basicConfig(level=logging.DEBUG,
1973 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1974 a1 = logging.getLogger("a.b.c")
1975 a2 = logging.getLogger("d.e.f")
1976
1977 f = ContextFilter()
1978 a1.addFilter(f)
1979 a2.addFilter(f)
1980 a1.debug("A debug message")
1981 a1.info("An info message with %s", "some parameters")
1982 for x in range(10):
1983 lvl = choice(levels)
1984 lvlname = logging.getLevelName(lvl)
1985 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1986
1987which, when run, produces something like::
1988
1989 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1990 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1991 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
1992 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
1993 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
1994 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
1995 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
1996 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
1997 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
1998 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
1999 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
2000 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
2001
2002
Vinay Sajipd31f3632010-06-29 15:31:15 +00002003.. _multiple-processes:
2004
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002005Logging to a single file from multiple processes
2006------------------------------------------------
2007
2008Although logging is thread-safe, and logging to a single file from multiple
2009threads in a single process *is* supported, logging to a single file from
2010*multiple processes* is *not* supported, because there is no standard way to
2011serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00002012need to log to a single file from multiple processes, one way of doing this is
2013to have all the processes log to a :class:`SocketHandler`, and have a separate
2014process which implements a socket server which reads from the socket and logs
2015to file. (If you prefer, you can dedicate one thread in one of the existing
2016processes to perform this function.) The following section documents this
2017approach in more detail and includes a working socket receiver which can be
2018used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002019
Vinay Sajip5a92b132009-08-15 23:35:08 +00002020If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00002021:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00002022:class:`Lock` class from this module to serialize access to the file from
2023your processes. The existing :class:`FileHandler` and subclasses do not make
2024use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00002025Note that at present, the :mod:`multiprocessing` module does not provide
2026working lock functionality on all platforms (see
2027http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00002028
Vinay Sajip121a1c42010-09-08 10:46:15 +00002029.. currentmodule:: logging.handlers
2030
2031Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
2032all logging events to one of the processes in your multi-process application.
2033The following example script demonstrates how you can do this; in the example
2034a separate listener process listens for events sent by other processes and logs
2035them according to its own logging configuration. Although the example only
2036demonstrates one way of doing it (for example, you may want to use a listener
2037thread rather than a separate listener process - the implementation would be
2038analogous) it does allow for completely different logging configurations for
2039the listener and the other processes in your application, and can be used as
2040the basis for code meeting your own specific requirements::
2041
2042 # You'll need these imports in your own code
2043 import logging
2044 import logging.handlers
2045 import multiprocessing
2046
2047 # Next two import lines for this demo only
2048 from random import choice, random
2049 import time
2050
2051 #
2052 # Because you'll want to define the logging configurations for listener and workers, the
2053 # listener and worker process functions take a configurer parameter which is a callable
2054 # for configuring logging for that process. These functions are also passed the queue,
2055 # which they use for communication.
2056 #
2057 # In practice, you can configure the listener however you want, but note that in this
2058 # simple example, the listener does not apply level or filter logic to received records.
2059 # In practice, you would probably want to do ths logic in the worker processes, to avoid
2060 # sending events which would be filtered out between processes.
2061 #
2062 # The size of the rotated files is made small so you can see the results easily.
2063 def listener_configurer():
2064 root = logging.getLogger()
2065 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2066 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2067 h.setFormatter(f)
2068 root.addHandler(h)
2069
2070 # This is the listener process top-level loop: wait for logging events
2071 # (LogRecords)on the queue and handle them, quit when you get a None for a
2072 # LogRecord.
2073 def listener_process(queue, configurer):
2074 configurer()
2075 while True:
2076 try:
2077 record = queue.get()
2078 if record is None: # We send this as a sentinel to tell the listener to quit.
2079 break
2080 logger = logging.getLogger(record.name)
2081 logger.handle(record) # No level or filter logic applied - just do it!
2082 except (KeyboardInterrupt, SystemExit):
2083 raise
2084 except:
2085 import sys, traceback
2086 print >> sys.stderr, 'Whoops! Problem:'
2087 traceback.print_exc(file=sys.stderr)
2088
2089 # Arrays used for random selections in this demo
2090
2091 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2092 logging.ERROR, logging.CRITICAL]
2093
2094 LOGGERS = ['a.b.c', 'd.e.f']
2095
2096 MESSAGES = [
2097 'Random message #1',
2098 'Random message #2',
2099 'Random message #3',
2100 ]
2101
2102 # The worker configuration is done at the start of the worker process run.
2103 # Note that on Windows you can't rely on fork semantics, so each process
2104 # will run the logging configuration code when it starts.
2105 def worker_configurer(queue):
2106 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2107 root = logging.getLogger()
2108 root.addHandler(h)
2109 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2110
2111 # This is the worker process top-level loop, which just logs ten events with
2112 # random intervening delays before terminating.
2113 # The print messages are just so you know it's doing something!
2114 def worker_process(queue, configurer):
2115 configurer(queue)
2116 name = multiprocessing.current_process().name
2117 print('Worker started: %s' % name)
2118 for i in range(10):
2119 time.sleep(random())
2120 logger = logging.getLogger(choice(LOGGERS))
2121 level = choice(LEVELS)
2122 message = choice(MESSAGES)
2123 logger.log(level, message)
2124 print('Worker finished: %s' % name)
2125
2126 # Here's where the demo gets orchestrated. Create the queue, create and start
2127 # the listener, create ten workers and start them, wait for them to finish,
2128 # then send a None to the queue to tell the listener to finish.
2129 def main():
2130 queue = multiprocessing.Queue(-1)
2131 listener = multiprocessing.Process(target=listener_process,
2132 args=(queue, listener_configurer))
2133 listener.start()
2134 workers = []
2135 for i in range(10):
2136 worker = multiprocessing.Process(target=worker_process,
2137 args=(queue, worker_configurer))
2138 workers.append(worker)
2139 worker.start()
2140 for w in workers:
2141 w.join()
2142 queue.put_nowait(None)
2143 listener.join()
2144
2145 if __name__ == '__main__':
2146 main()
2147
2148
2149.. currentmodule:: logging
2150
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002151
Georg Brandl116aa622007-08-15 14:28:22 +00002152.. _network-logging:
2153
2154Sending and receiving logging events across a network
2155-----------------------------------------------------
2156
2157Let's say you want to send logging events across a network, and handle them at
2158the receiving end. A simple way of doing this is attaching a
2159:class:`SocketHandler` instance to the root logger at the sending end::
2160
2161 import logging, logging.handlers
2162
2163 rootLogger = logging.getLogger('')
2164 rootLogger.setLevel(logging.DEBUG)
2165 socketHandler = logging.handlers.SocketHandler('localhost',
2166 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2167 # don't bother with a formatter, since a socket handler sends the event as
2168 # an unformatted pickle
2169 rootLogger.addHandler(socketHandler)
2170
2171 # Now, we can log to the root logger, or any other logger. First the root...
2172 logging.info('Jackdaws love my big sphinx of quartz.')
2173
2174 # Now, define a couple of other loggers which might represent areas in your
2175 # application:
2176
2177 logger1 = logging.getLogger('myapp.area1')
2178 logger2 = logging.getLogger('myapp.area2')
2179
2180 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2181 logger1.info('How quickly daft jumping zebras vex.')
2182 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2183 logger2.error('The five boxing wizards jump quickly.')
2184
Alexandre Vassalottice261952008-05-12 02:31:37 +00002185At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002186module. Here is a basic working example::
2187
Georg Brandla35f4b92009-05-31 16:41:59 +00002188 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002189 import logging
2190 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002191 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002192 import struct
2193
2194
Alexandre Vassalottice261952008-05-12 02:31:37 +00002195 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002196 """Handler for a streaming logging request.
2197
2198 This basically logs the record using whatever logging policy is
2199 configured locally.
2200 """
2201
2202 def handle(self):
2203 """
2204 Handle multiple requests - each expected to be a 4-byte length,
2205 followed by the LogRecord in pickle format. Logs the record
2206 according to whatever policy is configured locally.
2207 """
Collin Winter46334482007-09-10 00:49:57 +00002208 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002209 chunk = self.connection.recv(4)
2210 if len(chunk) < 4:
2211 break
2212 slen = struct.unpack(">L", chunk)[0]
2213 chunk = self.connection.recv(slen)
2214 while len(chunk) < slen:
2215 chunk = chunk + self.connection.recv(slen - len(chunk))
2216 obj = self.unPickle(chunk)
2217 record = logging.makeLogRecord(obj)
2218 self.handleLogRecord(record)
2219
2220 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002221 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002222
2223 def handleLogRecord(self, record):
2224 # if a name is specified, we use the named logger rather than the one
2225 # implied by the record.
2226 if self.server.logname is not None:
2227 name = self.server.logname
2228 else:
2229 name = record.name
2230 logger = logging.getLogger(name)
2231 # N.B. EVERY record gets logged. This is because Logger.handle
2232 # is normally called AFTER logger-level filtering. If you want
2233 # to do filtering, do it at the client end to save wasting
2234 # cycles and network bandwidth!
2235 logger.handle(record)
2236
Alexandre Vassalottice261952008-05-12 02:31:37 +00002237 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00002238 """simple TCP socket-based logging receiver suitable for testing.
2239 """
2240
2241 allow_reuse_address = 1
2242
2243 def __init__(self, host='localhost',
2244 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2245 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002246 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002247 self.abort = 0
2248 self.timeout = 1
2249 self.logname = None
2250
2251 def serve_until_stopped(self):
2252 import select
2253 abort = 0
2254 while not abort:
2255 rd, wr, ex = select.select([self.socket.fileno()],
2256 [], [],
2257 self.timeout)
2258 if rd:
2259 self.handle_request()
2260 abort = self.abort
2261
2262 def main():
2263 logging.basicConfig(
2264 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
2265 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00002266 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00002267 tcpserver.serve_until_stopped()
2268
2269 if __name__ == "__main__":
2270 main()
2271
2272First run the server, and then the client. On the client side, nothing is
2273printed on the console; on the server side, you should see something like::
2274
2275 About to start TCP server...
2276 59 root INFO Jackdaws love my big sphinx of quartz.
2277 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2278 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2279 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2280 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2281
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002282Note that there are some security issues with pickle in some scenarios. If
2283these affect you, you can use an alternative serialization scheme by overriding
2284the :meth:`makePickle` method and implementing your alternative there, as
2285well as adapting the above script to use your alternative serialization.
2286
Vinay Sajip4039aff2010-09-11 10:25:28 +00002287.. _arbitrary-object-messages:
2288
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002289Using arbitrary objects as messages
2290-----------------------------------
2291
2292In the preceding sections and examples, it has been assumed that the message
2293passed when logging the event is a string. However, this is not the only
2294possibility. You can pass an arbitrary object as a message, and its
2295:meth:`__str__` method will be called when the logging system needs to convert
2296it to a string representation. In fact, if you want to, you can avoid
2297computing a string representation altogether - for example, the
2298:class:`SocketHandler` emits an event by pickling it and sending it over the
2299wire.
2300
Vinay Sajip55778922010-09-23 09:09:15 +00002301Dealing with handlers that block
2302--------------------------------
2303
2304.. currentmodule:: logging.handlers
2305
2306Sometimes you have to get your logging handlers to do their work without
2307blocking the thread you’re logging from. This is common in Web applications,
2308though of course it also occurs in other scenarios.
2309
2310A common culprit which demonstrates sluggish behaviour is the
2311:class:`SMTPHandler`: sending emails can take a long time, for a
2312number of reasons outside the developer’s control (for example, a poorly
2313performing mail or network infrastructure). But almost any network-based
2314handler can block: Even a :class:`SocketHandler` operation may do a
2315DNS query under the hood which is too slow (and this query can be deep in the
2316socket library code, below the Python layer, and outside your control).
2317
2318One solution is to use a two-part approach. For the first part, attach only a
2319:class:`QueueHandler` to those loggers which are accessed from
2320performance-critical threads. They simply write to their queue, which can be
2321sized to a large enough capacity or initialized with no upper bound to their
2322size. The write to the queue will typically be accepted quickly, though you
2323will probably need to catch the :ref:`queue.Full` exception as a precaution
2324in your code. If you are a library developer who has performance-critical
2325threads in their code, be sure to document this (together with a suggestion to
2326attach only ``QueueHandlers`` to your loggers) for the benefit of other
2327developers who will use your code.
2328
2329The second part of the solution is :class:`QueueListener`, which has been
2330designed as the counterpart to :class:`QueueHandler`. A
2331:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2332and it fires up an internal thread which listens to its queue for LogRecords
2333sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2334matter). The ``LogRecords`` are removed from the queue and passed to the
2335handlers for processing.
2336
2337The advantage of having a separate :class:`QueueListener` class is that you
2338can use the same instance to service multiple ``QueueHandlers``. This is more
2339resource-friendly than, say, having threaded versions of the existing handler
2340classes, which would eat up one thread per handler for no particular benefit.
2341
2342An example of using these two classes follows (imports omitted)::
2343
2344 que = queue.Queue(-1) # no limit on size
2345 queue_handler = QueueHandler(que)
2346 handler = logging.StreamHandler()
2347 listener = QueueListener(que, handler)
2348 root = logging.getLogger()
2349 root.addHandler(queue_handler)
2350 formatter = logging.Formatter('%(threadName)s: %(message)s')
2351 handler.setFormatter(formatter)
2352 listener.start()
2353 # The log output will display the thread which generated
2354 # the event (the main thread) rather than the internal
2355 # thread which monitors the internal queue. This is what
2356 # you want to happen.
2357 root.warning('Look out!')
2358 listener.stop()
2359
2360which, when run, will produce::
2361
2362 MainThread: Look out!
2363
2364
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002365Optimization
2366------------
2367
2368Formatting of message arguments is deferred until it cannot be avoided.
2369However, computing the arguments passed to the logging method can also be
2370expensive, and you may want to avoid doing it if the logger will just throw
2371away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2372method which takes a level argument and returns true if the event would be
2373created by the Logger for that level of call. You can write code like this::
2374
2375 if logger.isEnabledFor(logging.DEBUG):
2376 logger.debug("Message with %s, %s", expensive_func1(),
2377 expensive_func2())
2378
2379so that if the logger's threshold is set above ``DEBUG``, the calls to
2380:func:`expensive_func1` and :func:`expensive_func2` are never made.
2381
2382There are other optimizations which can be made for specific applications which
2383need more precise control over what logging information is collected. Here's a
2384list of things you can do to avoid processing during logging which you don't
2385need:
2386
2387+-----------------------------------------------+----------------------------------------+
2388| What you don't want to collect | How to avoid collecting it |
2389+===============================================+========================================+
2390| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2391+-----------------------------------------------+----------------------------------------+
2392| Threading information. | Set ``logging.logThreads`` to ``0``. |
2393+-----------------------------------------------+----------------------------------------+
2394| Process information. | Set ``logging.logProcesses`` to ``0``. |
2395+-----------------------------------------------+----------------------------------------+
2396
2397Also note that the core logging module only includes the basic handlers. If
2398you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2399take up any memory.
2400
2401.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002402
2403Handler Objects
2404---------------
2405
2406Handlers have the following attributes and methods. Note that :class:`Handler`
2407is never instantiated directly; this class acts as a base for more useful
2408subclasses. However, the :meth:`__init__` method in subclasses needs to call
2409:meth:`Handler.__init__`.
2410
2411
2412.. method:: Handler.__init__(level=NOTSET)
2413
2414 Initializes the :class:`Handler` instance by setting its level, setting the list
2415 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2416 serializing access to an I/O mechanism.
2417
2418
2419.. method:: Handler.createLock()
2420
2421 Initializes a thread lock which can be used to serialize access to underlying
2422 I/O functionality which may not be threadsafe.
2423
2424
2425.. method:: Handler.acquire()
2426
2427 Acquires the thread lock created with :meth:`createLock`.
2428
2429
2430.. method:: Handler.release()
2431
2432 Releases the thread lock acquired with :meth:`acquire`.
2433
2434
2435.. method:: Handler.setLevel(lvl)
2436
2437 Sets the threshold for this handler to *lvl*. Logging messages which are less
2438 severe than *lvl* will be ignored. When a handler is created, the level is set
2439 to :const:`NOTSET` (which causes all messages to be processed).
2440
2441
2442.. method:: Handler.setFormatter(form)
2443
2444 Sets the :class:`Formatter` for this handler to *form*.
2445
2446
2447.. method:: Handler.addFilter(filt)
2448
2449 Adds the specified filter *filt* to this handler.
2450
2451
2452.. method:: Handler.removeFilter(filt)
2453
2454 Removes the specified filter *filt* from this handler.
2455
2456
2457.. method:: Handler.filter(record)
2458
2459 Applies this handler's filters to the record and returns a true value if the
2460 record is to be processed.
2461
2462
2463.. method:: Handler.flush()
2464
2465 Ensure all logging output has been flushed. This version does nothing and is
2466 intended to be implemented by subclasses.
2467
2468
2469.. method:: Handler.close()
2470
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002471 Tidy up any resources used by the handler. This version does no output but
2472 removes the handler from an internal list of handlers which is closed when
2473 :func:`shutdown` is called. Subclasses should ensure that this gets called
2474 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002475
2476
2477.. method:: Handler.handle(record)
2478
2479 Conditionally emits the specified logging record, depending on filters which may
2480 have been added to the handler. Wraps the actual emission of the record with
2481 acquisition/release of the I/O thread lock.
2482
2483
2484.. method:: Handler.handleError(record)
2485
2486 This method should be called from handlers when an exception is encountered
2487 during an :meth:`emit` call. By default it does nothing, which means that
2488 exceptions get silently ignored. This is what is mostly wanted for a logging
2489 system - most users will not care about errors in the logging system, they are
2490 more interested in application errors. You could, however, replace this with a
2491 custom handler if you wish. The specified record is the one which was being
2492 processed when the exception occurred.
2493
2494
2495.. method:: Handler.format(record)
2496
2497 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2498 default formatter for the module.
2499
2500
2501.. method:: Handler.emit(record)
2502
2503 Do whatever it takes to actually log the specified logging record. This version
2504 is intended to be implemented by subclasses and so raises a
2505 :exc:`NotImplementedError`.
2506
2507
Vinay Sajipd31f3632010-06-29 15:31:15 +00002508.. _stream-handler:
2509
Georg Brandl116aa622007-08-15 14:28:22 +00002510StreamHandler
2511^^^^^^^^^^^^^
2512
2513The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2514sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2515file-like object (or, more precisely, any object which supports :meth:`write`
2516and :meth:`flush` methods).
2517
2518
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002519.. currentmodule:: logging
2520
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002521.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002522
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002523 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002524 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2525 will be used.
2526
2527
Benjamin Petersone41251e2008-04-25 01:59:09 +00002528 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002529
Benjamin Petersone41251e2008-04-25 01:59:09 +00002530 If a formatter is specified, it is used to format the record. The record
2531 is then written to the stream with a trailing newline. If exception
2532 information is present, it is formatted using
2533 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002534
2535
Benjamin Petersone41251e2008-04-25 01:59:09 +00002536 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002537
Benjamin Petersone41251e2008-04-25 01:59:09 +00002538 Flushes the stream by calling its :meth:`flush` method. Note that the
2539 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002540 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002541
Vinay Sajip05ed6952010-10-20 20:34:09 +00002542.. versionchanged:: 3.2
2543 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2544 value ``"\n"``, which is used as the terminator when writing a formatted
2545 record to a stream. If you don't want this newline termination, you can
2546 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002547
Vinay Sajipd31f3632010-06-29 15:31:15 +00002548.. _file-handler:
2549
Georg Brandl116aa622007-08-15 14:28:22 +00002550FileHandler
2551^^^^^^^^^^^
2552
2553The :class:`FileHandler` class, located in the core :mod:`logging` package,
2554sends logging output to a disk file. It inherits the output functionality from
2555:class:`StreamHandler`.
2556
2557
Vinay Sajipd31f3632010-06-29 15:31:15 +00002558.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002559
2560 Returns a new instance of the :class:`FileHandler` class. The specified file is
2561 opened and used as the stream for logging. If *mode* is not specified,
2562 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002563 with that encoding. If *delay* is true, then file opening is deferred until the
2564 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002565
2566
Benjamin Petersone41251e2008-04-25 01:59:09 +00002567 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002568
Benjamin Petersone41251e2008-04-25 01:59:09 +00002569 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002570
2571
Benjamin Petersone41251e2008-04-25 01:59:09 +00002572 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002573
Benjamin Petersone41251e2008-04-25 01:59:09 +00002574 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002575
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002576
Vinay Sajipd31f3632010-06-29 15:31:15 +00002577.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002578
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002579NullHandler
2580^^^^^^^^^^^
2581
2582.. versionadded:: 3.1
2583
2584The :class:`NullHandler` class, located in the core :mod:`logging` package,
2585does not do any formatting or output. It is essentially a "no-op" handler
2586for use by library developers.
2587
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002588.. class:: NullHandler()
2589
2590 Returns a new instance of the :class:`NullHandler` class.
2591
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002592 .. method:: emit(record)
2593
2594 This method does nothing.
2595
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002596 .. method:: handle(record)
2597
2598 This method does nothing.
2599
2600 .. method:: createLock()
2601
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002602 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002603 underlying I/O to which access needs to be serialized.
2604
2605
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002606See :ref:`library-config` for more information on how to use
2607:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002608
Vinay Sajipd31f3632010-06-29 15:31:15 +00002609.. _watched-file-handler:
2610
Georg Brandl116aa622007-08-15 14:28:22 +00002611WatchedFileHandler
2612^^^^^^^^^^^^^^^^^^
2613
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002614.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002615
Georg Brandl116aa622007-08-15 14:28:22 +00002616The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2617module, is a :class:`FileHandler` which watches the file it is logging to. If
2618the file changes, it is closed and reopened using the file name.
2619
2620A file change can happen because of usage of programs such as *newsyslog* and
2621*logrotate* which perform log file rotation. This handler, intended for use
2622under Unix/Linux, watches the file to see if it has changed since the last emit.
2623(A file is deemed to have changed if its device or inode have changed.) If the
2624file has changed, the old file stream is closed, and the file opened to get a
2625new stream.
2626
2627This handler is not appropriate for use under Windows, because under Windows
2628open log files cannot be moved or renamed - logging opens the files with
2629exclusive locks - and so there is no need for such a handler. Furthermore,
2630*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2631this value.
2632
2633
Christian Heimese7a15bb2008-01-24 16:21:45 +00002634.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002635
2636 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2637 file is opened and used as the stream for logging. If *mode* is not specified,
2638 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002639 with that encoding. If *delay* is true, then file opening is deferred until the
2640 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002641
2642
Benjamin Petersone41251e2008-04-25 01:59:09 +00002643 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002644
Benjamin Petersone41251e2008-04-25 01:59:09 +00002645 Outputs the record to the file, but first checks to see if the file has
2646 changed. If it has, the existing stream is flushed and closed and the
2647 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002648
Vinay Sajipd31f3632010-06-29 15:31:15 +00002649.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002650
2651RotatingFileHandler
2652^^^^^^^^^^^^^^^^^^^
2653
2654The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2655module, supports rotation of disk log files.
2656
2657
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002658.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002659
2660 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2661 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002662 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2663 with that encoding. If *delay* is true, then file opening is deferred until the
2664 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002665
2666 You can use the *maxBytes* and *backupCount* values to allow the file to
2667 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2668 the file is closed and a new file is silently opened for output. Rollover occurs
2669 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2670 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2671 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2672 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2673 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2674 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2675 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2676 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2677 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2678
2679
Benjamin Petersone41251e2008-04-25 01:59:09 +00002680 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002681
Benjamin Petersone41251e2008-04-25 01:59:09 +00002682 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002683
2684
Benjamin Petersone41251e2008-04-25 01:59:09 +00002685 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002686
Benjamin Petersone41251e2008-04-25 01:59:09 +00002687 Outputs the record to the file, catering for rollover as described
2688 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002689
Vinay Sajipd31f3632010-06-29 15:31:15 +00002690.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002691
2692TimedRotatingFileHandler
2693^^^^^^^^^^^^^^^^^^^^^^^^
2694
2695The :class:`TimedRotatingFileHandler` class, located in the
2696:mod:`logging.handlers` module, supports rotation of disk log files at certain
2697timed intervals.
2698
2699
Vinay Sajipd31f3632010-06-29 15:31:15 +00002700.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002701
2702 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2703 specified file is opened and used as the stream for logging. On rotating it also
2704 sets the filename suffix. Rotating happens based on the product of *when* and
2705 *interval*.
2706
2707 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002708 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002709
Christian Heimesb558a2e2008-03-02 22:46:37 +00002710 +----------------+-----------------------+
2711 | Value | Type of interval |
2712 +================+=======================+
2713 | ``'S'`` | Seconds |
2714 +----------------+-----------------------+
2715 | ``'M'`` | Minutes |
2716 +----------------+-----------------------+
2717 | ``'H'`` | Hours |
2718 +----------------+-----------------------+
2719 | ``'D'`` | Days |
2720 +----------------+-----------------------+
2721 | ``'W'`` | Week day (0=Monday) |
2722 +----------------+-----------------------+
2723 | ``'midnight'`` | Roll over at midnight |
2724 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002725
Christian Heimesb558a2e2008-03-02 22:46:37 +00002726 The system will save old log files by appending extensions to the filename.
2727 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002728 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002729 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002730
2731 When computing the next rollover time for the first time (when the handler
2732 is created), the last modification time of an existing log file, or else
2733 the current time, is used to compute when the next rotation will occur.
2734
Georg Brandl0c77a822008-06-10 16:37:50 +00002735 If the *utc* argument is true, times in UTC will be used; otherwise
2736 local time is used.
2737
2738 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002739 will be kept, and if more would be created when rollover occurs, the oldest
2740 one is deleted. The deletion logic uses the interval to determine which
2741 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002742
Vinay Sajipd31f3632010-06-29 15:31:15 +00002743 If *delay* is true, then file opening is deferred until the first call to
2744 :meth:`emit`.
2745
Georg Brandl116aa622007-08-15 14:28:22 +00002746
Benjamin Petersone41251e2008-04-25 01:59:09 +00002747 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002748
Benjamin Petersone41251e2008-04-25 01:59:09 +00002749 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002750
2751
Benjamin Petersone41251e2008-04-25 01:59:09 +00002752 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002753
Benjamin Petersone41251e2008-04-25 01:59:09 +00002754 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002755
2756
Vinay Sajipd31f3632010-06-29 15:31:15 +00002757.. _socket-handler:
2758
Georg Brandl116aa622007-08-15 14:28:22 +00002759SocketHandler
2760^^^^^^^^^^^^^
2761
2762The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2763sends logging output to a network socket. The base class uses a TCP socket.
2764
2765
2766.. class:: SocketHandler(host, port)
2767
2768 Returns a new instance of the :class:`SocketHandler` class intended to
2769 communicate with a remote machine whose address is given by *host* and *port*.
2770
2771
Benjamin Petersone41251e2008-04-25 01:59:09 +00002772 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002773
Benjamin Petersone41251e2008-04-25 01:59:09 +00002774 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002775
2776
Benjamin Petersone41251e2008-04-25 01:59:09 +00002777 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002778
Benjamin Petersone41251e2008-04-25 01:59:09 +00002779 Pickles the record's attribute dictionary and writes it to the socket in
2780 binary format. If there is an error with the socket, silently drops the
2781 packet. If the connection was previously lost, re-establishes the
2782 connection. To unpickle the record at the receiving end into a
2783 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002784
2785
Benjamin Petersone41251e2008-04-25 01:59:09 +00002786 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002787
Benjamin Petersone41251e2008-04-25 01:59:09 +00002788 Handles an error which has occurred during :meth:`emit`. The most likely
2789 cause is a lost connection. Closes the socket so that we can retry on the
2790 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002791
2792
Benjamin Petersone41251e2008-04-25 01:59:09 +00002793 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002794
Benjamin Petersone41251e2008-04-25 01:59:09 +00002795 This is a factory method which allows subclasses to define the precise
2796 type of socket they want. The default implementation creates a TCP socket
2797 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002798
2799
Benjamin Petersone41251e2008-04-25 01:59:09 +00002800 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002801
Benjamin Petersone41251e2008-04-25 01:59:09 +00002802 Pickles the record's attribute dictionary in binary format with a length
2803 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002804
Vinay Sajipd31f3632010-06-29 15:31:15 +00002805 Note that pickles aren't completely secure. If you are concerned about
2806 security, you may want to override this method to implement a more secure
2807 mechanism. For example, you can sign pickles using HMAC and then verify
2808 them on the receiving end, or alternatively you can disable unpickling of
2809 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002810
Benjamin Petersone41251e2008-04-25 01:59:09 +00002811 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002812
Benjamin Petersone41251e2008-04-25 01:59:09 +00002813 Send a pickled string *packet* to the socket. This function allows for
2814 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002815
2816
Vinay Sajipd31f3632010-06-29 15:31:15 +00002817.. _datagram-handler:
2818
Georg Brandl116aa622007-08-15 14:28:22 +00002819DatagramHandler
2820^^^^^^^^^^^^^^^
2821
2822The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2823module, inherits from :class:`SocketHandler` to support sending logging messages
2824over UDP sockets.
2825
2826
2827.. class:: DatagramHandler(host, port)
2828
2829 Returns a new instance of the :class:`DatagramHandler` class intended to
2830 communicate with a remote machine whose address is given by *host* and *port*.
2831
2832
Benjamin Petersone41251e2008-04-25 01:59:09 +00002833 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002834
Benjamin Petersone41251e2008-04-25 01:59:09 +00002835 Pickles the record's attribute dictionary and writes it to the socket in
2836 binary format. If there is an error with the socket, silently drops the
2837 packet. To unpickle the record at the receiving end into a
2838 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002839
2840
Benjamin Petersone41251e2008-04-25 01:59:09 +00002841 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002842
Benjamin Petersone41251e2008-04-25 01:59:09 +00002843 The factory method of :class:`SocketHandler` is here overridden to create
2844 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002845
2846
Benjamin Petersone41251e2008-04-25 01:59:09 +00002847 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002848
Benjamin Petersone41251e2008-04-25 01:59:09 +00002849 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002850
2851
Vinay Sajipd31f3632010-06-29 15:31:15 +00002852.. _syslog-handler:
2853
Georg Brandl116aa622007-08-15 14:28:22 +00002854SysLogHandler
2855^^^^^^^^^^^^^
2856
2857The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2858supports sending logging messages to a remote or local Unix syslog.
2859
2860
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002861.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002862
2863 Returns a new instance of the :class:`SysLogHandler` class intended to
2864 communicate with a remote Unix machine whose address is given by *address* in
2865 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002866 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002867 alternative to providing a ``(host, port)`` tuple is providing an address as a
2868 string, for example "/dev/log". In this case, a Unix domain socket is used to
2869 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002870 :const:`LOG_USER` is used. The type of socket opened depends on the
2871 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2872 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2873 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2874
Vinay Sajip972412d2010-09-23 20:31:24 +00002875 Note that if your server is not listening on UDP port 514,
2876 :class:`SysLogHandler` may appear not to work. In that case, check what
2877 address you should be using for a domain socket - it's system dependent.
2878 For example, on Linux it's usually "/dev/log" but on OS/X it's
2879 "/var/run/syslog". You'll need to check your platform and use the
2880 appropriate address (you may need to do this check at runtime if your
2881 application needs to run on several platforms). On Windows, you pretty
2882 much have to use the UDP option.
2883
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002884 .. versionchanged:: 3.2
2885 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002886
2887
Benjamin Petersone41251e2008-04-25 01:59:09 +00002888 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002889
Benjamin Petersone41251e2008-04-25 01:59:09 +00002890 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002891
2892
Benjamin Petersone41251e2008-04-25 01:59:09 +00002893 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002894
Benjamin Petersone41251e2008-04-25 01:59:09 +00002895 The record is formatted, and then sent to the syslog server. If exception
2896 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002897
2898
Benjamin Petersone41251e2008-04-25 01:59:09 +00002899 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002900
Benjamin Petersone41251e2008-04-25 01:59:09 +00002901 Encodes the facility and priority into an integer. You can pass in strings
2902 or integers - if strings are passed, internal mapping dictionaries are
2903 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002904
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002905 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2906 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002907
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002908 **Priorities**
2909
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002910 +--------------------------+---------------+
2911 | Name (string) | Symbolic value|
2912 +==========================+===============+
2913 | ``alert`` | LOG_ALERT |
2914 +--------------------------+---------------+
2915 | ``crit`` or ``critical`` | LOG_CRIT |
2916 +--------------------------+---------------+
2917 | ``debug`` | LOG_DEBUG |
2918 +--------------------------+---------------+
2919 | ``emerg`` or ``panic`` | LOG_EMERG |
2920 +--------------------------+---------------+
2921 | ``err`` or ``error`` | LOG_ERR |
2922 +--------------------------+---------------+
2923 | ``info`` | LOG_INFO |
2924 +--------------------------+---------------+
2925 | ``notice`` | LOG_NOTICE |
2926 +--------------------------+---------------+
2927 | ``warn`` or ``warning`` | LOG_WARNING |
2928 +--------------------------+---------------+
2929
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002930 **Facilities**
2931
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002932 +---------------+---------------+
2933 | Name (string) | Symbolic value|
2934 +===============+===============+
2935 | ``auth`` | LOG_AUTH |
2936 +---------------+---------------+
2937 | ``authpriv`` | LOG_AUTHPRIV |
2938 +---------------+---------------+
2939 | ``cron`` | LOG_CRON |
2940 +---------------+---------------+
2941 | ``daemon`` | LOG_DAEMON |
2942 +---------------+---------------+
2943 | ``ftp`` | LOG_FTP |
2944 +---------------+---------------+
2945 | ``kern`` | LOG_KERN |
2946 +---------------+---------------+
2947 | ``lpr`` | LOG_LPR |
2948 +---------------+---------------+
2949 | ``mail`` | LOG_MAIL |
2950 +---------------+---------------+
2951 | ``news`` | LOG_NEWS |
2952 +---------------+---------------+
2953 | ``syslog`` | LOG_SYSLOG |
2954 +---------------+---------------+
2955 | ``user`` | LOG_USER |
2956 +---------------+---------------+
2957 | ``uucp`` | LOG_UUCP |
2958 +---------------+---------------+
2959 | ``local0`` | LOG_LOCAL0 |
2960 +---------------+---------------+
2961 | ``local1`` | LOG_LOCAL1 |
2962 +---------------+---------------+
2963 | ``local2`` | LOG_LOCAL2 |
2964 +---------------+---------------+
2965 | ``local3`` | LOG_LOCAL3 |
2966 +---------------+---------------+
2967 | ``local4`` | LOG_LOCAL4 |
2968 +---------------+---------------+
2969 | ``local5`` | LOG_LOCAL5 |
2970 +---------------+---------------+
2971 | ``local6`` | LOG_LOCAL6 |
2972 +---------------+---------------+
2973 | ``local7`` | LOG_LOCAL7 |
2974 +---------------+---------------+
2975
2976 .. method:: mapPriority(levelname)
2977
2978 Maps a logging level name to a syslog priority name.
2979 You may need to override this if you are using custom levels, or
2980 if the default algorithm is not suitable for your needs. The
2981 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2982 ``CRITICAL`` to the equivalent syslog names, and all other level
2983 names to "warning".
2984
2985.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002986
2987NTEventLogHandler
2988^^^^^^^^^^^^^^^^^
2989
2990The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2991module, supports sending logging messages to a local Windows NT, Windows 2000 or
2992Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2993extensions for Python installed.
2994
2995
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002996.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002997
2998 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2999 used to define the application name as it appears in the event log. An
3000 appropriate registry entry is created using this name. The *dllname* should give
3001 the fully qualified pathname of a .dll or .exe which contains message
3002 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
3003 - this is installed with the Win32 extensions and contains some basic
3004 placeholder message definitions. Note that use of these placeholders will make
3005 your event logs big, as the entire message source is held in the log. If you
3006 want slimmer logs, you have to pass in the name of your own .dll or .exe which
3007 contains the message definitions you want to use in the event log). The
3008 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
3009 defaults to ``'Application'``.
3010
3011
Benjamin Petersone41251e2008-04-25 01:59:09 +00003012 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003013
Benjamin Petersone41251e2008-04-25 01:59:09 +00003014 At this point, you can remove the application name from the registry as a
3015 source of event log entries. However, if you do this, you will not be able
3016 to see the events as you intended in the Event Log Viewer - it needs to be
3017 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003018 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00003019
3020
Benjamin Petersone41251e2008-04-25 01:59:09 +00003021 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003022
Benjamin Petersone41251e2008-04-25 01:59:09 +00003023 Determines the message ID, event category and event type, and then logs
3024 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00003025
3026
Benjamin Petersone41251e2008-04-25 01:59:09 +00003027 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003028
Benjamin Petersone41251e2008-04-25 01:59:09 +00003029 Returns the event category for the record. Override this if you want to
3030 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00003031
3032
Benjamin Petersone41251e2008-04-25 01:59:09 +00003033 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003034
Benjamin Petersone41251e2008-04-25 01:59:09 +00003035 Returns the event type for the record. Override this if you want to
3036 specify your own types. This version does a mapping using the handler's
3037 typemap attribute, which is set up in :meth:`__init__` to a dictionary
3038 which contains mappings for :const:`DEBUG`, :const:`INFO`,
3039 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
3040 your own levels, you will either need to override this method or place a
3041 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00003042
3043
Benjamin Petersone41251e2008-04-25 01:59:09 +00003044 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003045
Benjamin Petersone41251e2008-04-25 01:59:09 +00003046 Returns the message ID for the record. If you are using your own messages,
3047 you could do this by having the *msg* passed to the logger being an ID
3048 rather than a format string. Then, in here, you could use a dictionary
3049 lookup to get the message ID. This version returns 1, which is the base
3050 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00003051
Vinay Sajipd31f3632010-06-29 15:31:15 +00003052.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003053
3054SMTPHandler
3055^^^^^^^^^^^
3056
3057The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
3058supports sending logging messages to an email address via SMTP.
3059
3060
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003061.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003062
3063 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3064 initialized with the from and to addresses and subject line of the email. The
3065 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3066 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3067 the standard SMTP port is used. If your SMTP server requires authentication, you
3068 can specify a (username, password) tuple for the *credentials* argument.
3069
Georg Brandl116aa622007-08-15 14:28:22 +00003070
Benjamin Petersone41251e2008-04-25 01:59:09 +00003071 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003072
Benjamin Petersone41251e2008-04-25 01:59:09 +00003073 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003074
3075
Benjamin Petersone41251e2008-04-25 01:59:09 +00003076 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003077
Benjamin Petersone41251e2008-04-25 01:59:09 +00003078 If you want to specify a subject line which is record-dependent, override
3079 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003080
Vinay Sajipd31f3632010-06-29 15:31:15 +00003081.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003082
3083MemoryHandler
3084^^^^^^^^^^^^^
3085
3086The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3087supports buffering of logging records in memory, periodically flushing them to a
3088:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3089event of a certain severity or greater is seen.
3090
3091:class:`MemoryHandler` is a subclass of the more general
3092:class:`BufferingHandler`, which is an abstract class. This buffers logging
3093records in memory. Whenever each record is added to the buffer, a check is made
3094by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3095should, then :meth:`flush` is expected to do the needful.
3096
3097
3098.. class:: BufferingHandler(capacity)
3099
3100 Initializes the handler with a buffer of the specified capacity.
3101
3102
Benjamin Petersone41251e2008-04-25 01:59:09 +00003103 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003104
Benjamin Petersone41251e2008-04-25 01:59:09 +00003105 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3106 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003107
3108
Benjamin Petersone41251e2008-04-25 01:59:09 +00003109 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003110
Benjamin Petersone41251e2008-04-25 01:59:09 +00003111 You can override this to implement custom flushing behavior. This version
3112 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003113
3114
Benjamin Petersone41251e2008-04-25 01:59:09 +00003115 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003116
Benjamin Petersone41251e2008-04-25 01:59:09 +00003117 Returns true if the buffer is up to capacity. This method can be
3118 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003119
3120
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003121.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003122
3123 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3124 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3125 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3126 set using :meth:`setTarget` before this handler does anything useful.
3127
3128
Benjamin Petersone41251e2008-04-25 01:59:09 +00003129 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003130
Benjamin Petersone41251e2008-04-25 01:59:09 +00003131 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3132 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003133
3134
Benjamin Petersone41251e2008-04-25 01:59:09 +00003135 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003136
Benjamin Petersone41251e2008-04-25 01:59:09 +00003137 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003138 records to the target, if there is one. The buffer is also cleared when
3139 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003140
3141
Benjamin Petersone41251e2008-04-25 01:59:09 +00003142 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003143
Benjamin Petersone41251e2008-04-25 01:59:09 +00003144 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003145
3146
Benjamin Petersone41251e2008-04-25 01:59:09 +00003147 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003148
Benjamin Petersone41251e2008-04-25 01:59:09 +00003149 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003150
3151
Vinay Sajipd31f3632010-06-29 15:31:15 +00003152.. _http-handler:
3153
Georg Brandl116aa622007-08-15 14:28:22 +00003154HTTPHandler
3155^^^^^^^^^^^
3156
3157The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3158supports sending logging messages to a Web server, using either ``GET`` or
3159``POST`` semantics.
3160
3161
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003162.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003163
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003164 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3165 of the form ``host:port``, should you need to use a specific port number.
3166 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3167 connection will be used. If *credentials* is specified, it should be a
3168 2-tuple consisting of userid and password, which will be placed in an HTTP
3169 'Authorization' header using Basic authentication. If you specify
3170 credentials, you should also specify secure=True so that your userid and
3171 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003172
3173
Benjamin Petersone41251e2008-04-25 01:59:09 +00003174 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003175
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003176 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003177
3178
Vinay Sajip121a1c42010-09-08 10:46:15 +00003179.. _queue-handler:
3180
3181
3182QueueHandler
3183^^^^^^^^^^^^
3184
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003185.. versionadded:: 3.2
3186
Vinay Sajip121a1c42010-09-08 10:46:15 +00003187The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3188supports sending logging messages to a queue, such as those implemented in the
3189:mod:`queue` or :mod:`multiprocessing` modules.
3190
Vinay Sajip0637d492010-09-23 08:15:54 +00003191Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3192to let handlers do their work on a separate thread from the one which does the
3193logging. This is important in Web applications and also other service
3194applications where threads servicing clients need to respond as quickly as
3195possible, while any potentially slow operations (such as sending an email via
3196:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003197
3198.. class:: QueueHandler(queue)
3199
3200 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003201 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003202 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003203 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003204
3205
3206 .. method:: emit(record)
3207
Vinay Sajip0258ce82010-09-22 20:34:53 +00003208 Enqueues the result of preparing the LogRecord.
3209
3210 .. method:: prepare(record)
3211
3212 Prepares a record for queuing. The object returned by this
3213 method is enqueued.
3214
3215 The base implementation formats the record to merge the message
3216 and arguments, and removes unpickleable items from the record
3217 in-place.
3218
3219 You might want to override this method if you want to convert
3220 the record to a dict or JSON string, or send a modified copy
3221 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003222
3223 .. method:: enqueue(record)
3224
3225 Enqueues the record on the queue using ``put_nowait()``; you may
3226 want to override this if you want to use blocking behaviour, or a
3227 timeout, or a customised queue implementation.
3228
3229
Vinay Sajip121a1c42010-09-08 10:46:15 +00003230
Vinay Sajip0637d492010-09-23 08:15:54 +00003231.. queue-listener:
3232
3233QueueListener
3234^^^^^^^^^^^^^
3235
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003236.. versionadded:: 3.2
3237
Vinay Sajip0637d492010-09-23 08:15:54 +00003238The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3239module, supports receiving logging messages from a queue, such as those
3240implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3241messages are received from a queue in an internal thread and passed, on
3242the same thread, to one or more handlers for processing.
3243
3244Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3245to let handlers do their work on a separate thread from the one which does the
3246logging. This is important in Web applications and also other service
3247applications where threads servicing clients need to respond as quickly as
3248possible, while any potentially slow operations (such as sending an email via
3249:class:`SMTPHandler`) are done on a separate thread.
3250
3251.. class:: QueueListener(queue, *handlers)
3252
3253 Returns a new instance of the :class:`QueueListener` class. The instance is
3254 initialized with the queue to send messages to and a list of handlers which
3255 will handle entries placed on the queue. The queue can be any queue-
3256 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3257 to know how to get messages from it.
3258
3259 .. method:: dequeue(block)
3260
3261 Dequeues a record and return it, optionally blocking.
3262
3263 The base implementation uses ``get()``. You may want to override this
3264 method if you want to use timeouts or work with custom queue
3265 implementations.
3266
3267 .. method:: prepare(record)
3268
3269 Prepare a record for handling.
3270
3271 This implementation just returns the passed-in record. You may want to
3272 override this method if you need to do any custom marshalling or
3273 manipulation of the record before passing it to the handlers.
3274
3275 .. method:: handle(record)
3276
3277 Handle a record.
3278
3279 This just loops through the handlers offering them the record
3280 to handle. The actual object passed to the handlers is that which
3281 is returned from :meth:`prepare`.
3282
3283 .. method:: start()
3284
3285 Starts the listener.
3286
3287 This starts up a background thread to monitor the queue for
3288 LogRecords to process.
3289
3290 .. method:: stop()
3291
3292 Stops the listener.
3293
3294 This asks the thread to terminate, and then waits for it to do so.
3295 Note that if you don't call this before your application exits, there
3296 may be some records still left on the queue, which won't be processed.
3297
Vinay Sajip0637d492010-09-23 08:15:54 +00003298
Vinay Sajip63891ed2010-09-13 20:02:39 +00003299.. _zeromq-handlers:
3300
Vinay Sajip0637d492010-09-23 08:15:54 +00003301Subclassing QueueHandler
3302^^^^^^^^^^^^^^^^^^^^^^^^
3303
Vinay Sajip63891ed2010-09-13 20:02:39 +00003304You can use a :class:`QueueHandler` subclass to send messages to other kinds
3305of queues, for example a ZeroMQ "publish" socket. In the example below,the
3306socket is created separately and passed to the handler (as its 'queue')::
3307
3308 import zmq # using pyzmq, the Python binding for ZeroMQ
3309 import json # for serializing records portably
3310
3311 ctx = zmq.Context()
3312 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3313 sock.bind('tcp://*:5556') # or wherever
3314
3315 class ZeroMQSocketHandler(QueueHandler):
3316 def enqueue(self, record):
3317 data = json.dumps(record.__dict__)
3318 self.queue.send(data)
3319
Vinay Sajip0055c422010-09-14 09:42:39 +00003320 handler = ZeroMQSocketHandler(sock)
3321
3322
Vinay Sajip63891ed2010-09-13 20:02:39 +00003323Of course there are other ways of organizing this, for example passing in the
3324data needed by the handler to create the socket::
3325
3326 class ZeroMQSocketHandler(QueueHandler):
3327 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3328 self.ctx = ctx or zmq.Context()
3329 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003330 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003331 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003332
3333 def enqueue(self, record):
3334 data = json.dumps(record.__dict__)
3335 self.queue.send(data)
3336
Vinay Sajipde726922010-09-14 06:59:24 +00003337 def close(self):
3338 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003339
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003340
Vinay Sajip0637d492010-09-23 08:15:54 +00003341Subclassing QueueListener
3342^^^^^^^^^^^^^^^^^^^^^^^^^
3343
3344You can also subclass :class:`QueueListener` to get messages from other kinds
3345of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
3346
3347 class ZeroMQSocketListener(QueueListener):
3348 def __init__(self, uri, *handlers, **kwargs):
3349 self.ctx = kwargs.get('ctx') or zmq.Context()
3350 socket = zmq.Socket(self.ctx, zmq.SUB)
3351 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3352 socket.connect(uri)
3353
3354 def dequeue(self):
3355 msg = self.queue.recv()
3356 return logging.makeLogRecord(json.loads(msg))
3357
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003358
Christian Heimes8b0facf2007-12-04 19:30:01 +00003359.. _formatter-objects:
3360
Georg Brandl116aa622007-08-15 14:28:22 +00003361Formatter Objects
3362-----------------
3363
Benjamin Peterson75edad02009-01-01 15:05:06 +00003364.. currentmodule:: logging
3365
Georg Brandl116aa622007-08-15 14:28:22 +00003366:class:`Formatter`\ s have the following attributes and methods. They are
3367responsible for converting a :class:`LogRecord` to (usually) a string which can
3368be interpreted by either a human or an external system. The base
3369:class:`Formatter` allows a formatting string to be specified. If none is
3370supplied, the default value of ``'%(message)s'`` is used.
3371
3372A Formatter can be initialized with a format string which makes use of knowledge
3373of the :class:`LogRecord` attributes - such as the default value mentioned above
3374making use of the fact that the user's message and arguments are pre-formatted
3375into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003376standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003377for more information on string formatting.
3378
3379Currently, the useful mapping keys in a :class:`LogRecord` are:
3380
3381+-------------------------+-----------------------------------------------+
3382| Format | Description |
3383+=========================+===============================================+
3384| ``%(name)s`` | Name of the logger (logging channel). |
3385+-------------------------+-----------------------------------------------+
3386| ``%(levelno)s`` | Numeric logging level for the message |
3387| | (:const:`DEBUG`, :const:`INFO`, |
3388| | :const:`WARNING`, :const:`ERROR`, |
3389| | :const:`CRITICAL`). |
3390+-------------------------+-----------------------------------------------+
3391| ``%(levelname)s`` | Text logging level for the message |
3392| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3393| | ``'ERROR'``, ``'CRITICAL'``). |
3394+-------------------------+-----------------------------------------------+
3395| ``%(pathname)s`` | Full pathname of the source file where the |
3396| | logging call was issued (if available). |
3397+-------------------------+-----------------------------------------------+
3398| ``%(filename)s`` | Filename portion of pathname. |
3399+-------------------------+-----------------------------------------------+
3400| ``%(module)s`` | Module (name portion of filename). |
3401+-------------------------+-----------------------------------------------+
3402| ``%(funcName)s`` | Name of function containing the logging call. |
3403+-------------------------+-----------------------------------------------+
3404| ``%(lineno)d`` | Source line number where the logging call was |
3405| | issued (if available). |
3406+-------------------------+-----------------------------------------------+
3407| ``%(created)f`` | Time when the :class:`LogRecord` was created |
3408| | (as returned by :func:`time.time`). |
3409+-------------------------+-----------------------------------------------+
3410| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3411| | created, relative to the time the logging |
3412| | module was loaded. |
3413+-------------------------+-----------------------------------------------+
3414| ``%(asctime)s`` | Human-readable time when the |
3415| | :class:`LogRecord` was created. By default |
3416| | this is of the form "2003-07-08 16:49:45,896" |
3417| | (the numbers after the comma are millisecond |
3418| | portion of the time). |
3419+-------------------------+-----------------------------------------------+
3420| ``%(msecs)d`` | Millisecond portion of the time when the |
3421| | :class:`LogRecord` was created. |
3422+-------------------------+-----------------------------------------------+
3423| ``%(thread)d`` | Thread ID (if available). |
3424+-------------------------+-----------------------------------------------+
3425| ``%(threadName)s`` | Thread name (if available). |
3426+-------------------------+-----------------------------------------------+
3427| ``%(process)d`` | Process ID (if available). |
3428+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003429| ``%(processName)s`` | Process name (if available). |
3430+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003431| ``%(message)s`` | The logged message, computed as ``msg % |
3432| | args``. |
3433+-------------------------+-----------------------------------------------+
3434
Georg Brandl116aa622007-08-15 14:28:22 +00003435
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003436.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003437
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003438 Returns a new instance of the :class:`Formatter` class. The instance is
3439 initialized with a format string for the message as a whole, as well as a
3440 format string for the date/time portion of a message. If no *fmt* is
3441 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3442 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003443
Benjamin Petersone41251e2008-04-25 01:59:09 +00003444 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003445
Benjamin Petersone41251e2008-04-25 01:59:09 +00003446 The record's attribute dictionary is used as the operand to a string
3447 formatting operation. Returns the resulting string. Before formatting the
3448 dictionary, a couple of preparatory steps are carried out. The *message*
3449 attribute of the record is computed using *msg* % *args*. If the
3450 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3451 to format the event time. If there is exception information, it is
3452 formatted using :meth:`formatException` and appended to the message. Note
3453 that the formatted exception information is cached in attribute
3454 *exc_text*. This is useful because the exception information can be
3455 pickled and sent across the wire, but you should be careful if you have
3456 more than one :class:`Formatter` subclass which customizes the formatting
3457 of exception information. In this case, you will have to clear the cached
3458 value after a formatter has done its formatting, so that the next
3459 formatter to handle the event doesn't use the cached value but
3460 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003461
Vinay Sajip8593ae62010-11-14 21:33:04 +00003462 If stack information is available, it's appended after the exception
3463 information, using :meth:`formatStack` to transform it if necessary.
3464
Georg Brandl116aa622007-08-15 14:28:22 +00003465
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003466 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003467
Benjamin Petersone41251e2008-04-25 01:59:09 +00003468 This method should be called from :meth:`format` by a formatter which
3469 wants to make use of a formatted time. This method can be overridden in
3470 formatters to provide for any specific requirement, but the basic behavior
3471 is as follows: if *datefmt* (a string) is specified, it is used with
3472 :func:`time.strftime` to format the creation time of the
3473 record. Otherwise, the ISO8601 format is used. The resulting string is
3474 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003475
3476
Benjamin Petersone41251e2008-04-25 01:59:09 +00003477 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003478
Benjamin Petersone41251e2008-04-25 01:59:09 +00003479 Formats the specified exception information (a standard exception tuple as
3480 returned by :func:`sys.exc_info`) as a string. This default implementation
3481 just uses :func:`traceback.print_exception`. The resulting string is
3482 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003483
Vinay Sajip8593ae62010-11-14 21:33:04 +00003484 .. method:: formatStack(stack_info)
3485
3486 Formats the specified stack information (a string as returned by
3487 :func:`traceback.print_stack`, but with the last newline removed) as a
3488 string. This default implementation just returns the input value.
3489
Vinay Sajipd31f3632010-06-29 15:31:15 +00003490.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003491
3492Filter Objects
3493--------------
3494
Georg Brandl5c66bca2010-10-29 05:36:28 +00003495``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003496filtering than is provided by levels. The base filter class only allows events
3497which are below a certain point in the logger hierarchy. For example, a filter
3498initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3499"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3500empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003501
3502
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003503.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003504
3505 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3506 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003507 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003508
3509
Benjamin Petersone41251e2008-04-25 01:59:09 +00003510 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003511
Benjamin Petersone41251e2008-04-25 01:59:09 +00003512 Is the specified record to be logged? Returns zero for no, nonzero for
3513 yes. If deemed appropriate, the record may be modified in-place by this
3514 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003515
Vinay Sajip81010212010-08-19 19:17:41 +00003516Note that filters attached to handlers are consulted whenever an event is
3517emitted by the handler, whereas filters attached to loggers are consulted
3518whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3519etc.) This means that events which have been generated by descendant loggers
3520will not be filtered by a logger's filter setting, unless the filter has also
3521been applied to those descendant loggers.
3522
Vinay Sajip22246fd2010-10-20 11:40:02 +00003523You don't actually need to subclass ``Filter``: you can pass any instance
3524which has a ``filter`` method with the same semantics.
3525
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003526.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003527 You don't need to create specialized ``Filter`` classes, or use other
3528 classes with a ``filter`` method: you can use a function (or other
3529 callable) as a filter. The filtering logic will check to see if the filter
3530 object has a ``filter`` attribute: if it does, it's assumed to be a
3531 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3532 assumed to be a callable and called with the record as the single
3533 parameter. The returned value should conform to that returned by
3534 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003535
Vinay Sajipac007992010-09-17 12:45:26 +00003536Other uses for filters
3537^^^^^^^^^^^^^^^^^^^^^^
3538
3539Although filters are used primarily to filter records based on more
3540sophisticated criteria than levels, they get to see every record which is
3541processed by the handler or logger they're attached to: this can be useful if
3542you want to do things like counting how many records were processed by a
3543particular logger or handler, or adding, changing or removing attributes in
3544the LogRecord being processed. Obviously changing the LogRecord needs to be
3545done with some care, but it does allow the injection of contextual information
3546into logs (see :ref:`filters-contextual`).
3547
Vinay Sajipd31f3632010-06-29 15:31:15 +00003548.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003549
3550LogRecord Objects
3551-----------------
3552
Vinay Sajip4039aff2010-09-11 10:25:28 +00003553:class:`LogRecord` instances are created automatically by the :class:`Logger`
3554every time something is logged, and can be created manually via
3555:func:`makeLogRecord` (for example, from a pickled event received over the
3556wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003557
3558
Vinay Sajipa18b9592010-12-12 13:20:55 +00003559.. class:: LogRecord(name, levelno, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003560
Vinay Sajip4039aff2010-09-11 10:25:28 +00003561 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003562
Vinay Sajip4039aff2010-09-11 10:25:28 +00003563 The primary information is passed in :attr:`msg` and :attr:`args`, which
3564 are combined using ``msg % args`` to create the :attr:`message` field of the
3565 record.
3566
3567 .. attribute:: args
3568
3569 Tuple of arguments to be used in formatting :attr:`msg`.
3570
3571 .. attribute:: exc_info
3572
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003573 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003574 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003575
3576 .. attribute:: func
3577
3578 Name of the function of origin (i.e. in which the logging call was made).
3579
3580 .. attribute:: lineno
3581
3582 Line number in the source file of origin.
3583
Vinay Sajipa18b9592010-12-12 13:20:55 +00003584 .. attribute:: levelno
Vinay Sajip4039aff2010-09-11 10:25:28 +00003585
3586 Numeric logging level.
3587
3588 .. attribute:: message
3589
3590 Bound to the result of :meth:`getMessage` when
3591 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3592
3593 .. attribute:: msg
3594
3595 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3596 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3597
3598 .. attribute:: name
3599
3600 Name of the logger that emitted the record.
3601
3602 .. attribute:: pathname
3603
3604 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003605
Vinay Sajip8593ae62010-11-14 21:33:04 +00003606 .. attribute:: stack_info
3607
3608 Stack frame information (where available) from the bottom of the stack
3609 in the current thread, up to and including the stack frame of the
3610 logging call which resulted in the creation of this record.
3611
Benjamin Petersone41251e2008-04-25 01:59:09 +00003612 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003613
Benjamin Petersone41251e2008-04-25 01:59:09 +00003614 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003615 user-supplied arguments with the message. If the user-supplied message
3616 argument to the logging call is not a string, :func:`str` is called on it to
3617 convert it to a string. This allows use of user-defined classes as
3618 messages, whose ``__str__`` method can return the actual format string to
3619 be used.
3620
Vinay Sajip61561522010-12-03 11:50:38 +00003621 .. versionchanged:: 3.2
3622 The creation of a ``LogRecord`` has been made more configurable by
3623 providing a factory which is used to create the record. The factory can be
3624 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3625 (see this for the factory's signature).
3626
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003627 This functionality can be used to inject your own values into a
3628 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003629
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003630 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003631
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003632 def record_factory(*args, **kwargs):
3633 record = old_factory(*args, **kwargs)
3634 record.custom_attribute = 0xdecafbad
3635 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003636
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003637 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003638
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003639 With this pattern, multiple factories could be chained, and as long
3640 as they don't overwrite each other's attributes or unintentionally
3641 overwrite the standard attributes listed above, there should be no
3642 surprises.
3643
Vinay Sajip61561522010-12-03 11:50:38 +00003644
Vinay Sajipd31f3632010-06-29 15:31:15 +00003645.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003646
Christian Heimes04c420f2008-01-18 18:40:46 +00003647LoggerAdapter Objects
3648---------------------
3649
Christian Heimes04c420f2008-01-18 18:40:46 +00003650:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003651information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003652:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003653
Christian Heimes04c420f2008-01-18 18:40:46 +00003654
3655.. class:: LoggerAdapter(logger, extra)
3656
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003657 Returns an instance of :class:`LoggerAdapter` initialized with an
3658 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003659
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003660 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003661
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003662 Modifies the message and/or keyword arguments passed to a logging call in
3663 order to insert contextual information. This implementation takes the object
3664 passed as *extra* to the constructor and adds it to *kwargs* using key
3665 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3666 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003667
Vinay Sajipc84f0162010-09-21 11:25:39 +00003668In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003669methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003670:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3671:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3672:meth:`hasHandlers`. These methods have the same signatures as their
3673counterparts in :class:`Logger`, so you can use the two types of instances
3674interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003675
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003676.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003677 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3678 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3679 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003680
Georg Brandl116aa622007-08-15 14:28:22 +00003681
3682Thread Safety
3683-------------
3684
3685The logging module is intended to be thread-safe without any special work
3686needing to be done by its clients. It achieves this though using threading
3687locks; there is one lock to serialize access to the module's shared data, and
3688each handler also creates a lock to serialize access to its underlying I/O.
3689
Benjamin Petersond23f8222009-04-05 19:13:16 +00003690If you are implementing asynchronous signal handlers using the :mod:`signal`
3691module, you may not be able to use logging from within such handlers. This is
3692because lock implementations in the :mod:`threading` module are not always
3693re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003694
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003695
3696Integration with the warnings module
3697------------------------------------
3698
3699The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3700with the :mod:`warnings` module.
3701
3702.. function:: captureWarnings(capture)
3703
3704 This function is used to turn the capture of warnings by logging on and
3705 off.
3706
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003707 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3708 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003709 formatted using :func:`warnings.formatwarning` and the resulting string
3710 logged to a logger named "py.warnings" with a severity of `WARNING`.
3711
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003712 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003713 will stop, and warnings will be redirected to their original destinations
3714 (i.e. those in effect before `captureWarnings(True)` was called).
3715
3716
Georg Brandl116aa622007-08-15 14:28:22 +00003717Configuration
3718-------------
3719
3720
3721.. _logging-config-api:
3722
3723Configuration functions
3724^^^^^^^^^^^^^^^^^^^^^^^
3725
Georg Brandl116aa622007-08-15 14:28:22 +00003726The following functions configure the logging module. They are located in the
3727:mod:`logging.config` module. Their use is optional --- you can configure the
3728logging module using these functions or by making calls to the main API (defined
3729in :mod:`logging` itself) and defining handlers which are declared either in
3730:mod:`logging` or :mod:`logging.handlers`.
3731
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003732.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003733
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003734 Takes the logging configuration from a dictionary. The contents of
3735 this dictionary are described in :ref:`logging-config-dictschema`
3736 below.
3737
3738 If an error is encountered during configuration, this function will
3739 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3740 or :exc:`ImportError` with a suitably descriptive message. The
3741 following is a (possibly incomplete) list of conditions which will
3742 raise an error:
3743
3744 * A ``level`` which is not a string or which is a string not
3745 corresponding to an actual logging level.
3746 * A ``propagate`` value which is not a boolean.
3747 * An id which does not have a corresponding destination.
3748 * A non-existent handler id found during an incremental call.
3749 * An invalid logger name.
3750 * Inability to resolve to an internal or external object.
3751
3752 Parsing is performed by the :class:`DictConfigurator` class, whose
3753 constructor is passed the dictionary used for configuration, and
3754 has a :meth:`configure` method. The :mod:`logging.config` module
3755 has a callable attribute :attr:`dictConfigClass`
3756 which is initially set to :class:`DictConfigurator`.
3757 You can replace the value of :attr:`dictConfigClass` with a
3758 suitable implementation of your own.
3759
3760 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3761 the specified dictionary, and then calls the :meth:`configure` method on
3762 the returned object to put the configuration into effect::
3763
3764 def dictConfig(config):
3765 dictConfigClass(config).configure()
3766
3767 For example, a subclass of :class:`DictConfigurator` could call
3768 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3769 set up custom prefixes which would be usable in the subsequent
3770 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3771 this new subclass, and then :func:`dictConfig` could be called exactly as
3772 in the default, uncustomized state.
3773
3774.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003775
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003776 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003777 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003778 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003779 configurations (if the developer provides a mechanism to present the choices
3780 and load the chosen configuration). Defaults to be passed to the ConfigParser
3781 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003782
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003783
3784.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003785
3786 Starts up a socket server on the specified port, and listens for new
3787 configurations. If no port is specified, the module's default
3788 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3789 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3790 :class:`Thread` instance on which you can call :meth:`start` to start the
3791 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003792 call :func:`stopListening`.
3793
3794 To send a configuration to the socket, read in the configuration file and
3795 send it to the socket as a string of bytes preceded by a four-byte length
3796 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003797
3798
3799.. function:: stopListening()
3800
Christian Heimes8b0facf2007-12-04 19:30:01 +00003801 Stops the listening server which was created with a call to :func:`listen`.
3802 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003803 :func:`listen`.
3804
3805
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003806.. _logging-config-dictschema:
3807
3808Configuration dictionary schema
3809^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3810
3811Describing a logging configuration requires listing the various
3812objects to create and the connections between them; for example, you
3813may create a handler named "console" and then say that the logger
3814named "startup" will send its messages to the "console" handler.
3815These objects aren't limited to those provided by the :mod:`logging`
3816module because you might write your own formatter or handler class.
3817The parameters to these classes may also need to include external
3818objects such as ``sys.stderr``. The syntax for describing these
3819objects and connections is defined in :ref:`logging-config-dict-connections`
3820below.
3821
3822Dictionary Schema Details
3823"""""""""""""""""""""""""
3824
3825The dictionary passed to :func:`dictConfig` must contain the following
3826keys:
3827
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003828* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003829 version. The only valid value at present is 1, but having this key
3830 allows the schema to evolve while still preserving backwards
3831 compatibility.
3832
3833All other keys are optional, but if present they will be interpreted
3834as described below. In all cases below where a 'configuring dict' is
3835mentioned, it will be checked for the special ``'()'`` key to see if a
3836custom instantiation is required. If so, the mechanism described in
3837:ref:`logging-config-dict-userdef` below is used to create an instance;
3838otherwise, the context is used to determine what to instantiate.
3839
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003840* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003841 key is a formatter id and each value is a dict describing how to
3842 configure the corresponding Formatter instance.
3843
3844 The configuring dict is searched for keys ``format`` and ``datefmt``
3845 (with defaults of ``None``) and these are used to construct a
3846 :class:`logging.Formatter` instance.
3847
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003848* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003849 is a filter id and each value is a dict describing how to configure
3850 the corresponding Filter instance.
3851
3852 The configuring dict is searched for the key ``name`` (defaulting to the
3853 empty string) and this is used to construct a :class:`logging.Filter`
3854 instance.
3855
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003856* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003857 key is a handler id and each value is a dict describing how to
3858 configure the corresponding Handler instance.
3859
3860 The configuring dict is searched for the following keys:
3861
3862 * ``class`` (mandatory). This is the fully qualified name of the
3863 handler class.
3864
3865 * ``level`` (optional). The level of the handler.
3866
3867 * ``formatter`` (optional). The id of the formatter for this
3868 handler.
3869
3870 * ``filters`` (optional). A list of ids of the filters for this
3871 handler.
3872
3873 All *other* keys are passed through as keyword arguments to the
3874 handler's constructor. For example, given the snippet::
3875
3876 handlers:
3877 console:
3878 class : logging.StreamHandler
3879 formatter: brief
3880 level : INFO
3881 filters: [allow_foo]
3882 stream : ext://sys.stdout
3883 file:
3884 class : logging.handlers.RotatingFileHandler
3885 formatter: precise
3886 filename: logconfig.log
3887 maxBytes: 1024
3888 backupCount: 3
3889
3890 the handler with id ``console`` is instantiated as a
3891 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3892 stream. The handler with id ``file`` is instantiated as a
3893 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3894 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3895
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003896* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003897 is a logger name and each value is a dict describing how to
3898 configure the corresponding Logger instance.
3899
3900 The configuring dict is searched for the following keys:
3901
3902 * ``level`` (optional). The level of the logger.
3903
3904 * ``propagate`` (optional). The propagation setting of the logger.
3905
3906 * ``filters`` (optional). A list of ids of the filters for this
3907 logger.
3908
3909 * ``handlers`` (optional). A list of ids of the handlers for this
3910 logger.
3911
3912 The specified loggers will be configured according to the level,
3913 propagation, filters and handlers specified.
3914
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003915* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003916 Processing of the configuration will be as for any logger, except
3917 that the ``propagate`` setting will not be applicable.
3918
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003919* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003920 incremental to the existing configuration. This value defaults to
3921 ``False``, which means that the specified configuration replaces the
3922 existing configuration with the same semantics as used by the
3923 existing :func:`fileConfig` API.
3924
3925 If the specified value is ``True``, the configuration is processed
3926 as described in the section on :ref:`logging-config-dict-incremental`.
3927
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003928* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003929 disabled. This setting mirrors the parameter of the same name in
3930 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003931 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003932
3933.. _logging-config-dict-incremental:
3934
3935Incremental Configuration
3936"""""""""""""""""""""""""
3937
3938It is difficult to provide complete flexibility for incremental
3939configuration. For example, because objects such as filters
3940and formatters are anonymous, once a configuration is set up, it is
3941not possible to refer to such anonymous objects when augmenting a
3942configuration.
3943
3944Furthermore, there is not a compelling case for arbitrarily altering
3945the object graph of loggers, handlers, filters, formatters at
3946run-time, once a configuration is set up; the verbosity of loggers and
3947handlers can be controlled just by setting levels (and, in the case of
3948loggers, propagation flags). Changing the object graph arbitrarily in
3949a safe way is problematic in a multi-threaded environment; while not
3950impossible, the benefits are not worth the complexity it adds to the
3951implementation.
3952
3953Thus, when the ``incremental`` key of a configuration dict is present
3954and is ``True``, the system will completely ignore any ``formatters`` and
3955``filters`` entries, and process only the ``level``
3956settings in the ``handlers`` entries, and the ``level`` and
3957``propagate`` settings in the ``loggers`` and ``root`` entries.
3958
3959Using a value in the configuration dict lets configurations to be sent
3960over the wire as pickled dicts to a socket listener. Thus, the logging
3961verbosity of a long-running application can be altered over time with
3962no need to stop and restart the application.
3963
3964.. _logging-config-dict-connections:
3965
3966Object connections
3967""""""""""""""""""
3968
3969The schema describes a set of logging objects - loggers,
3970handlers, formatters, filters - which are connected to each other in
3971an object graph. Thus, the schema needs to represent connections
3972between the objects. For example, say that, once configured, a
3973particular logger has attached to it a particular handler. For the
3974purposes of this discussion, we can say that the logger represents the
3975source, and the handler the destination, of a connection between the
3976two. Of course in the configured objects this is represented by the
3977logger holding a reference to the handler. In the configuration dict,
3978this is done by giving each destination object an id which identifies
3979it unambiguously, and then using the id in the source object's
3980configuration to indicate that a connection exists between the source
3981and the destination object with that id.
3982
3983So, for example, consider the following YAML snippet::
3984
3985 formatters:
3986 brief:
3987 # configuration for formatter with id 'brief' goes here
3988 precise:
3989 # configuration for formatter with id 'precise' goes here
3990 handlers:
3991 h1: #This is an id
3992 # configuration of handler with id 'h1' goes here
3993 formatter: brief
3994 h2: #This is another id
3995 # configuration of handler with id 'h2' goes here
3996 formatter: precise
3997 loggers:
3998 foo.bar.baz:
3999 # other configuration for logger 'foo.bar.baz'
4000 handlers: [h1, h2]
4001
4002(Note: YAML used here because it's a little more readable than the
4003equivalent Python source form for the dictionary.)
4004
4005The ids for loggers are the logger names which would be used
4006programmatically to obtain a reference to those loggers, e.g.
4007``foo.bar.baz``. The ids for Formatters and Filters can be any string
4008value (such as ``brief``, ``precise`` above) and they are transient,
4009in that they are only meaningful for processing the configuration
4010dictionary and used to determine connections between objects, and are
4011not persisted anywhere when the configuration call is complete.
4012
4013The above snippet indicates that logger named ``foo.bar.baz`` should
4014have two handlers attached to it, which are described by the handler
4015ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
4016``brief``, and the formatter for ``h2`` is that described by id
4017``precise``.
4018
4019
4020.. _logging-config-dict-userdef:
4021
4022User-defined objects
4023""""""""""""""""""""
4024
4025The schema supports user-defined objects for handlers, filters and
4026formatters. (Loggers do not need to have different types for
4027different instances, so there is no support in this configuration
4028schema for user-defined logger classes.)
4029
4030Objects to be configured are described by dictionaries
4031which detail their configuration. In some places, the logging system
4032will be able to infer from the context how an object is to be
4033instantiated, but when a user-defined object is to be instantiated,
4034the system will not know how to do this. In order to provide complete
4035flexibility for user-defined object instantiation, the user needs
4036to provide a 'factory' - a callable which is called with a
4037configuration dictionary and which returns the instantiated object.
4038This is signalled by an absolute import path to the factory being
4039made available under the special key ``'()'``. Here's a concrete
4040example::
4041
4042 formatters:
4043 brief:
4044 format: '%(message)s'
4045 default:
4046 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
4047 datefmt: '%Y-%m-%d %H:%M:%S'
4048 custom:
4049 (): my.package.customFormatterFactory
4050 bar: baz
4051 spam: 99.9
4052 answer: 42
4053
4054The above YAML snippet defines three formatters. The first, with id
4055``brief``, is a standard :class:`logging.Formatter` instance with the
4056specified format string. The second, with id ``default``, has a
4057longer format and also defines the time format explicitly, and will
4058result in a :class:`logging.Formatter` initialized with those two format
4059strings. Shown in Python source form, the ``brief`` and ``default``
4060formatters have configuration sub-dictionaries::
4061
4062 {
4063 'format' : '%(message)s'
4064 }
4065
4066and::
4067
4068 {
4069 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4070 'datefmt' : '%Y-%m-%d %H:%M:%S'
4071 }
4072
4073respectively, and as these dictionaries do not contain the special key
4074``'()'``, the instantiation is inferred from the context: as a result,
4075standard :class:`logging.Formatter` instances are created. The
4076configuration sub-dictionary for the third formatter, with id
4077``custom``, is::
4078
4079 {
4080 '()' : 'my.package.customFormatterFactory',
4081 'bar' : 'baz',
4082 'spam' : 99.9,
4083 'answer' : 42
4084 }
4085
4086and this contains the special key ``'()'``, which means that
4087user-defined instantiation is wanted. In this case, the specified
4088factory callable will be used. If it is an actual callable it will be
4089used directly - otherwise, if you specify a string (as in the example)
4090the actual callable will be located using normal import mechanisms.
4091The callable will be called with the **remaining** items in the
4092configuration sub-dictionary as keyword arguments. In the above
4093example, the formatter with id ``custom`` will be assumed to be
4094returned by the call::
4095
4096 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4097
4098The key ``'()'`` has been used as the special key because it is not a
4099valid keyword parameter name, and so will not clash with the names of
4100the keyword arguments used in the call. The ``'()'`` also serves as a
4101mnemonic that the corresponding value is a callable.
4102
4103
4104.. _logging-config-dict-externalobj:
4105
4106Access to external objects
4107""""""""""""""""""""""""""
4108
4109There are times where a configuration needs to refer to objects
4110external to the configuration, for example ``sys.stderr``. If the
4111configuration dict is constructed using Python code, this is
4112straightforward, but a problem arises when the configuration is
4113provided via a text file (e.g. JSON, YAML). In a text file, there is
4114no standard way to distinguish ``sys.stderr`` from the literal string
4115``'sys.stderr'``. To facilitate this distinction, the configuration
4116system looks for certain special prefixes in string values and
4117treat them specially. For example, if the literal string
4118``'ext://sys.stderr'`` is provided as a value in the configuration,
4119then the ``ext://`` will be stripped off and the remainder of the
4120value processed using normal import mechanisms.
4121
4122The handling of such prefixes is done in a way analogous to protocol
4123handling: there is a generic mechanism to look for prefixes which
4124match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4125whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4126in a prefix-dependent manner and the result of the processing replaces
4127the string value. If the prefix is not recognised, then the string
4128value will be left as-is.
4129
4130
4131.. _logging-config-dict-internalobj:
4132
4133Access to internal objects
4134""""""""""""""""""""""""""
4135
4136As well as external objects, there is sometimes also a need to refer
4137to objects in the configuration. This will be done implicitly by the
4138configuration system for things that it knows about. For example, the
4139string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4140automatically be converted to the value ``logging.DEBUG``, and the
4141``handlers``, ``filters`` and ``formatter`` entries will take an
4142object id and resolve to the appropriate destination object.
4143
4144However, a more generic mechanism is needed for user-defined
4145objects which are not known to the :mod:`logging` module. For
4146example, consider :class:`logging.handlers.MemoryHandler`, which takes
4147a ``target`` argument which is another handler to delegate to. Since
4148the system already knows about this class, then in the configuration,
4149the given ``target`` just needs to be the object id of the relevant
4150target handler, and the system will resolve to the handler from the
4151id. If, however, a user defines a ``my.package.MyHandler`` which has
4152an ``alternate`` handler, the configuration system would not know that
4153the ``alternate`` referred to a handler. To cater for this, a generic
4154resolution system allows the user to specify::
4155
4156 handlers:
4157 file:
4158 # configuration of file handler goes here
4159
4160 custom:
4161 (): my.package.MyHandler
4162 alternate: cfg://handlers.file
4163
4164The literal string ``'cfg://handlers.file'`` will be resolved in an
4165analogous way to strings with the ``ext://`` prefix, but looking
4166in the configuration itself rather than the import namespace. The
4167mechanism allows access by dot or by index, in a similar way to
4168that provided by ``str.format``. Thus, given the following snippet::
4169
4170 handlers:
4171 email:
4172 class: logging.handlers.SMTPHandler
4173 mailhost: localhost
4174 fromaddr: my_app@domain.tld
4175 toaddrs:
4176 - support_team@domain.tld
4177 - dev_team@domain.tld
4178 subject: Houston, we have a problem.
4179
4180in the configuration, the string ``'cfg://handlers'`` would resolve to
4181the dict with key ``handlers``, the string ``'cfg://handlers.email``
4182would resolve to the dict with key ``email`` in the ``handlers`` dict,
4183and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4184resolve to ``'dev_team.domain.tld'`` and the string
4185``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4186``'support_team@domain.tld'``. The ``subject`` value could be accessed
4187using either ``'cfg://handlers.email.subject'`` or, equivalently,
4188``'cfg://handlers.email[subject]'``. The latter form only needs to be
4189used if the key contains spaces or non-alphanumeric characters. If an
4190index value consists only of decimal digits, access will be attempted
4191using the corresponding integer value, falling back to the string
4192value if needed.
4193
4194Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4195resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4196If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4197the system will attempt to retrieve the value from
4198``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4199to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4200fails.
4201
Georg Brandl116aa622007-08-15 14:28:22 +00004202.. _logging-config-fileformat:
4203
4204Configuration file format
4205^^^^^^^^^^^^^^^^^^^^^^^^^
4206
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004207The configuration file format understood by :func:`fileConfig` is based on
4208:mod:`configparser` functionality. The file must contain sections called
4209``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4210entities of each type which are defined in the file. For each such entity, there
4211is a separate section which identifies how that entity is configured. Thus, for
4212a logger named ``log01`` in the ``[loggers]`` section, the relevant
4213configuration details are held in a section ``[logger_log01]``. Similarly, a
4214handler called ``hand01`` in the ``[handlers]`` section will have its
4215configuration held in a section called ``[handler_hand01]``, while a formatter
4216called ``form01`` in the ``[formatters]`` section will have its configuration
4217specified in a section called ``[formatter_form01]``. The root logger
4218configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004219
4220Examples of these sections in the file are given below. ::
4221
4222 [loggers]
4223 keys=root,log02,log03,log04,log05,log06,log07
4224
4225 [handlers]
4226 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4227
4228 [formatters]
4229 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4230
4231The root logger must specify a level and a list of handlers. An example of a
4232root logger section is given below. ::
4233
4234 [logger_root]
4235 level=NOTSET
4236 handlers=hand01
4237
4238The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4239``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4240logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4241package's namespace.
4242
4243The ``handlers`` entry is a comma-separated list of handler names, which must
4244appear in the ``[handlers]`` section. These names must appear in the
4245``[handlers]`` section and have corresponding sections in the configuration
4246file.
4247
4248For loggers other than the root logger, some additional information is required.
4249This is illustrated by the following example. ::
4250
4251 [logger_parser]
4252 level=DEBUG
4253 handlers=hand01
4254 propagate=1
4255 qualname=compiler.parser
4256
4257The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4258except that if a non-root logger's level is specified as ``NOTSET``, the system
4259consults loggers higher up the hierarchy to determine the effective level of the
4260logger. The ``propagate`` entry is set to 1 to indicate that messages must
4261propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4262indicate that messages are **not** propagated to handlers up the hierarchy. The
4263``qualname`` entry is the hierarchical channel name of the logger, that is to
4264say the name used by the application to get the logger.
4265
4266Sections which specify handler configuration are exemplified by the following.
4267::
4268
4269 [handler_hand01]
4270 class=StreamHandler
4271 level=NOTSET
4272 formatter=form01
4273 args=(sys.stdout,)
4274
4275The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4276in the ``logging`` package's namespace). The ``level`` is interpreted as for
4277loggers, and ``NOTSET`` is taken to mean "log everything".
4278
4279The ``formatter`` entry indicates the key name of the formatter for this
4280handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4281If a name is specified, it must appear in the ``[formatters]`` section and have
4282a corresponding section in the configuration file.
4283
4284The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4285package's namespace, is the list of arguments to the constructor for the handler
4286class. Refer to the constructors for the relevant handlers, or to the examples
4287below, to see how typical entries are constructed. ::
4288
4289 [handler_hand02]
4290 class=FileHandler
4291 level=DEBUG
4292 formatter=form02
4293 args=('python.log', 'w')
4294
4295 [handler_hand03]
4296 class=handlers.SocketHandler
4297 level=INFO
4298 formatter=form03
4299 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4300
4301 [handler_hand04]
4302 class=handlers.DatagramHandler
4303 level=WARN
4304 formatter=form04
4305 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4306
4307 [handler_hand05]
4308 class=handlers.SysLogHandler
4309 level=ERROR
4310 formatter=form05
4311 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4312
4313 [handler_hand06]
4314 class=handlers.NTEventLogHandler
4315 level=CRITICAL
4316 formatter=form06
4317 args=('Python Application', '', 'Application')
4318
4319 [handler_hand07]
4320 class=handlers.SMTPHandler
4321 level=WARN
4322 formatter=form07
4323 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4324
4325 [handler_hand08]
4326 class=handlers.MemoryHandler
4327 level=NOTSET
4328 formatter=form08
4329 target=
4330 args=(10, ERROR)
4331
4332 [handler_hand09]
4333 class=handlers.HTTPHandler
4334 level=NOTSET
4335 formatter=form09
4336 args=('localhost:9022', '/log', 'GET')
4337
4338Sections which specify formatter configuration are typified by the following. ::
4339
4340 [formatter_form01]
4341 format=F1 %(asctime)s %(levelname)s %(message)s
4342 datefmt=
4343 class=logging.Formatter
4344
4345The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004346the :func:`strftime`\ -compatible date/time format string. If empty, the
4347package substitutes ISO8601 format date/times, which is almost equivalent to
4348specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
4349also specifies milliseconds, which are appended to the result of using the above
4350format string, with a comma separator. An example time in ISO8601 format is
4351``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004352
4353The ``class`` entry is optional. It indicates the name of the formatter's class
4354(as a dotted module and class name.) This option is useful for instantiating a
4355:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4356exception tracebacks in an expanded or condensed format.
4357
Christian Heimes8b0facf2007-12-04 19:30:01 +00004358
4359Configuration server example
4360^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4361
4362Here is an example of a module using the logging configuration server::
4363
4364 import logging
4365 import logging.config
4366 import time
4367 import os
4368
4369 # read initial config file
4370 logging.config.fileConfig("logging.conf")
4371
4372 # create and start listener on port 9999
4373 t = logging.config.listen(9999)
4374 t.start()
4375
4376 logger = logging.getLogger("simpleExample")
4377
4378 try:
4379 # loop through logging calls to see the difference
4380 # new configurations make, until Ctrl+C is pressed
4381 while True:
4382 logger.debug("debug message")
4383 logger.info("info message")
4384 logger.warn("warn message")
4385 logger.error("error message")
4386 logger.critical("critical message")
4387 time.sleep(5)
4388 except KeyboardInterrupt:
4389 # cleanup
4390 logging.config.stopListening()
4391 t.join()
4392
4393And here is a script that takes a filename and sends that file to the server,
4394properly preceded with the binary-encoded length, as the new logging
4395configuration::
4396
4397 #!/usr/bin/env python
4398 import socket, sys, struct
4399
4400 data_to_send = open(sys.argv[1], "r").read()
4401
4402 HOST = 'localhost'
4403 PORT = 9999
4404 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00004405 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004406 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00004407 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004408 s.send(struct.pack(">L", len(data_to_send)))
4409 s.send(data_to_send)
4410 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00004411 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004412
4413
4414More examples
4415-------------
4416
4417Multiple handlers and formatters
4418^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4419
4420Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4421or maximum quota for the number of handlers you may add. Sometimes it will be
4422beneficial for an application to log all messages of all severities to a text
4423file while simultaneously logging errors or above to the console. To set this
4424up, simply configure the appropriate handlers. The logging calls in the
4425application code will remain unchanged. Here is a slight modification to the
4426previous simple module-based configuration example::
4427
4428 import logging
4429
4430 logger = logging.getLogger("simple_example")
4431 logger.setLevel(logging.DEBUG)
4432 # create file handler which logs even debug messages
4433 fh = logging.FileHandler("spam.log")
4434 fh.setLevel(logging.DEBUG)
4435 # create console handler with a higher log level
4436 ch = logging.StreamHandler()
4437 ch.setLevel(logging.ERROR)
4438 # create formatter and add it to the handlers
4439 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4440 ch.setFormatter(formatter)
4441 fh.setFormatter(formatter)
4442 # add the handlers to logger
4443 logger.addHandler(ch)
4444 logger.addHandler(fh)
4445
4446 # "application" code
4447 logger.debug("debug message")
4448 logger.info("info message")
4449 logger.warn("warn message")
4450 logger.error("error message")
4451 logger.critical("critical message")
4452
4453Notice that the "application" code does not care about multiple handlers. All
4454that changed was the addition and configuration of a new handler named *fh*.
4455
4456The ability to create new handlers with higher- or lower-severity filters can be
4457very helpful when writing and testing an application. Instead of using many
4458``print`` statements for debugging, use ``logger.debug``: Unlike the print
4459statements, which you will have to delete or comment out later, the logger.debug
4460statements can remain intact in the source code and remain dormant until you
4461need them again. At that time, the only change that needs to happen is to
4462modify the severity level of the logger and/or handler to debug.
4463
4464
4465Using logging in multiple modules
4466^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4467
4468It was mentioned above that multiple calls to
4469``logging.getLogger('someLogger')`` return a reference to the same logger
4470object. This is true not only within the same module, but also across modules
4471as long as it is in the same Python interpreter process. It is true for
4472references to the same object; additionally, application code can define and
4473configure a parent logger in one module and create (but not configure) a child
4474logger in a separate module, and all logger calls to the child will pass up to
4475the parent. Here is a main module::
4476
4477 import logging
4478 import auxiliary_module
4479
4480 # create logger with "spam_application"
4481 logger = logging.getLogger("spam_application")
4482 logger.setLevel(logging.DEBUG)
4483 # create file handler which logs even debug messages
4484 fh = logging.FileHandler("spam.log")
4485 fh.setLevel(logging.DEBUG)
4486 # create console handler with a higher log level
4487 ch = logging.StreamHandler()
4488 ch.setLevel(logging.ERROR)
4489 # create formatter and add it to the handlers
4490 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4491 fh.setFormatter(formatter)
4492 ch.setFormatter(formatter)
4493 # add the handlers to the logger
4494 logger.addHandler(fh)
4495 logger.addHandler(ch)
4496
4497 logger.info("creating an instance of auxiliary_module.Auxiliary")
4498 a = auxiliary_module.Auxiliary()
4499 logger.info("created an instance of auxiliary_module.Auxiliary")
4500 logger.info("calling auxiliary_module.Auxiliary.do_something")
4501 a.do_something()
4502 logger.info("finished auxiliary_module.Auxiliary.do_something")
4503 logger.info("calling auxiliary_module.some_function()")
4504 auxiliary_module.some_function()
4505 logger.info("done with auxiliary_module.some_function()")
4506
4507Here is the auxiliary module::
4508
4509 import logging
4510
4511 # create logger
4512 module_logger = logging.getLogger("spam_application.auxiliary")
4513
4514 class Auxiliary:
4515 def __init__(self):
4516 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4517 self.logger.info("creating an instance of Auxiliary")
4518 def do_something(self):
4519 self.logger.info("doing something")
4520 a = 1 + 1
4521 self.logger.info("done doing something")
4522
4523 def some_function():
4524 module_logger.info("received a call to \"some_function\"")
4525
4526The output looks like this::
4527
Christian Heimes043d6f62008-01-07 17:19:16 +00004528 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004529 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004530 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004531 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004532 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004533 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004534 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004535 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004536 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004537 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004538 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004539 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004540 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004541 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004542 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004543 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004544 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004545 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004546 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004547 done with auxiliary_module.some_function()
4548