blob: 54d72b3d25045ec2beeaa8a1a294beb1ec1e1131 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
5 :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Georg Brandl116aa622007-08-15 14:28:22 +000014This module defines functions and classes which implement a flexible error
15logging system for applications.
16
Vinay Sajipa18b9592010-12-12 13:20:55 +000017The key benefit of having the logging API provided by a standard library module
18is that all Python modules can participate in logging, so your application log
19can include your own messages integrated with messages from third-party
20modules.
21
22
23Logging tutorial
24----------------
25
26Logging is a means of tracking events that happen when some software runs. The
27software's developer adds logging calls to their code to indicate that certain
28events have occurred. An event is described by a descriptive message which can
29optionally contain variable data (i.e. data that is potentially different for
30each occurrence of the event). Events also have an importance which the
31developer ascribes to the event; the importance can also be called the *level*
32or *severity*.
33
34When to use logging
35^^^^^^^^^^^^^^^^^^^
36
37Logging provides a set of convenience functions for simple logging usage. These
38are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and
39:func:`critical`. To determine when to use logging, see the table below, which
40states, for each of a set of common tasks, the best tool to use for it.
41
42+-------------------------------------+--------------------------------------+
43| Task you want to perform | The best tool for the task |
44+=====================================+======================================+
45| Display console output for ordinary | print() |
46| usage of a command line script or | |
47| program | |
48+-------------------------------------+--------------------------------------+
49| Report events that occur during | logging.info() (or logging.debug() |
50| normal operation of a program (e.g. | for very detailed output for |
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
227:meth:`str.format` and :class:`string.Template`. These formatting options *are*
228supported, but exploring them is outside the scope of this tutorial.
229
230
231Changing the format of displayed messages
232^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
233
234To change the format which is used to display messages, you need to
235specify the format you want to use::
236
237 import logging
238 logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
239 logging.debug('This message should appear on the console')
240 logging.info('So should this')
241 logging.warning('And this, too')
242
243which would print::
244
245 DEBUG:This message should appear on the console
246 INFO:So should this
247 WARNING:And this, too
248
249Notice that the 'root' which appeared in earlier examples has disappeared. For
250a full set of things that can appear in format strings, you can refer to the
251documentation for :ref:`formatter-objects`, but for simple usage, you just need
252the *levelname* (severity), *message* (event description, including variable
253data) and perhaps to display when the event occurred. This is described in the
254next section.
255
256Displaying the date/time in messages
257^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
258
259To display the date and time of an event, you would place "%(asctime)s" in
260your format string::
261
262 import logging
263 logging.basicConfig(format='%(asctime)s %(message)s')
264 logging.warning('is when this event was logged.')
265
266which should print something like this::
267
268 2010-12-12 11:41:42,612 is when this event was logged.
269
270The default format for date/time display (shown above) is ISO8601. If you need
271more control over the formatting of the date/time, provide a *datefmt*
272argument to ``basicConfig``, as in this example::
273
274 import logging
275 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
276 logging.warning('is when this event was logged.')
277
278which would display something like this::
279
280 12/12/2010 11:46:36 AM is when this event was logged.
281
282The format of the *datefmt* argument is the same as supported by
283:func:`time.strftime`.
284
285
Vinay Sajipf234eb92010-12-12 17:37:27 +0000286Er...that's it for the basics
287^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Vinay Sajipa18b9592010-12-12 13:20:55 +0000288
Vinay Sajipf234eb92010-12-12 17:37:27 +0000289That concludes the basic tutorial. It should be enough to get you up and
290running with logging. There's a lot more that the logging package offers, but
291to 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 +0000292reading the following sections. If you're ready for that, grab some of your
293favourite beverage and carry on.
294
295If your logging needs are simple, then use the above examples to incorporate
296logging into your own scripts, and if you run into problems or don't
297understand something, please post a question on the comp.lang.python Usenet
298group (available at http://groups.google.com/group/comp.lang.python) and you
299should receive help before too long.
300
Vinay Sajipf234eb92010-12-12 17:37:27 +0000301Still here? There's no need to read the whole of the logging documentation in
302linear fashion, top to bottom (there's quite a lot of it still to come). You
303can carry on reading the next few sections, which provide a slightly more
304advanced/in-depth tutorial than the basic one above. After that, you can
305take a look at the topics in the sidebar to see if there's something that
306especially interests you, and click on a topic to see more detail. Although
307some of the topics do follow on from each other, there are a few that can just
308stand alone.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000309
310
311.. _more-advanced-logging:
312
313More advanced logging
314---------------------
315
316The logging library takes a modular approach and offers several categories
317of components: loggers, handlers, filters, and formatters. Loggers expose the
318interface that application code directly uses. Handlers send the log records
319(created by loggers) to the appropriate destination. Filters provide a finer
320grained facility for determining which log records to output. Formatters
321specify the layout of the resultant log record in the final output.
322
Georg Brandl116aa622007-08-15 14:28:22 +0000323Logging is performed by calling methods on instances of the :class:`Logger`
324class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +0000325conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +0000326separators. For example, a logger named "scan" is the parent of loggers
327"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
328and indicate the area of an application in which a logged message originates.
329
Vinay Sajip5286ccf2010-12-12 13:25:29 +0000330A good convention to use when naming loggers is to use a module-level logger,
331in each module which uses logging, named as follows::
332
333 logger = logging.getLogger(__name__)
334
335This means that logger names track the package/module hierarchy, and it's
336intuitively obvious where events are logged just from the logger name.
337
Vinay Sajipa18b9592010-12-12 13:20:55 +0000338The root of the hierarchy of loggers is called the root logger. That's the
339logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
340:func:`error` and :func:`critical`, which just call the same-named method of
341the root logger. The functions and the methods have the same signatures. The
342root logger's name is printed as 'root' in the logged output.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Vinay Sajipa18b9592010-12-12 13:20:55 +0000344It is, of course, possible to log messages to different destinations. Support
345for writing log messages to files, HTTP GET/POST locations, email via SMTP,
346generic sockets, or OS-specific logging mechanisms is included in the package.
347Destinations are served by :dfn:`handler` classes. You can create your own log
Vinay Sajipdfa0a2a2010-12-10 08:17:05 +0000348destination class if you have special requirements not met by any of the
Vinay Sajipa18b9592010-12-12 13:20:55 +0000349built-in handler classes.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000350
Vinay Sajipa18b9592010-12-12 13:20:55 +0000351By default, no destination is set for any logging messages. You can specify
352a destination (such as console or file) by using :func:`basicConfig` as in the
353tutorial examples. If you call the functions :func:`debug`, :func:`info`,
354:func:`warning`, :func:`error` and :func:`critical`, they will check to see
355if no destination is set; and if one is not set, they will set a destination
356of the console (``sys.stderr``) and a default format for the displayed
357message before delegating to the root logger to do the actual message output.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000358
Vinay Sajipa18b9592010-12-12 13:20:55 +0000359The default format set by :func:`basicConfig` for messages is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000360
Vinay Sajipa18b9592010-12-12 13:20:55 +0000361 severity:logger name:message
Christian Heimes8b0facf2007-12-04 19:30:01 +0000362
Vinay Sajipa18b9592010-12-12 13:20:55 +0000363You can change this by passing a format string to :func:`basicConfig` with the
364*format* keyword argument. For all options regarding how a format string is
365constructed, see :ref:`formatter-objects`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000366
Christian Heimes8b0facf2007-12-04 19:30:01 +0000367
368Loggers
369^^^^^^^
370
Christian Heimes8b0facf2007-12-04 19:30:01 +0000371:class:`Logger` objects have a threefold job. First, they expose several
372methods to application code so that applications can log messages at runtime.
373Second, logger objects determine which log messages to act upon based upon
374severity (the default filtering facility) or filter objects. Third, logger
375objects pass along relevant log messages to all interested log handlers.
376
377The most widely used methods on logger objects fall into two categories:
378configuration and message sending.
379
Vinay Sajipf234eb92010-12-12 17:37:27 +0000380These are the most common configuration methods:
381
Christian Heimes8b0facf2007-12-04 19:30:01 +0000382* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
Vinay Sajipf234eb92010-12-12 17:37:27 +0000383 will handle, where debug is the lowest built-in severity level and critical
384 is the highest built-in severity. For example, if the severity level is
385 INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
386 and will ignore DEBUG messages.
387
388* :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove
389 handler objects from the logger object. Handlers are covered in more detail
390 in :ref:`handler-basic`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000391
392* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
Vinay Sajipf234eb92010-12-12 17:37:27 +0000393 objects from the logger object. Filters are covered in more detail in
394 :ref:`filter`.
395
396You don't need to always call these methods on every logger you create. See the
397last two paragraphs in this section.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000398
399With the logger object configured, the following methods create log messages:
400
401* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
402 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
403 a message and a level that corresponds to their respective method names. The
404 message is actually a format string, which may contain the standard string
405 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
406 rest of their arguments is a list of objects that correspond with the
407 substitution fields in the message. With regard to :const:`**kwargs`, the
408 logging methods care only about a keyword of :const:`exc_info` and use it to
409 determine whether to log exception information.
410
411* :meth:`Logger.exception` creates a log message similar to
412 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
413 stack trace along with it. Call this method only from an exception handler.
414
415* :meth:`Logger.log` takes a log level as an explicit argument. This is a
416 little more verbose for logging messages than using the log level convenience
417 methods listed above, but this is how to log at custom log levels.
418
Christian Heimesdcca98d2008-02-25 13:19:43 +0000419:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000420name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000421hierarchical structures. Multiple calls to :func:`getLogger` with the same name
422will return a reference to the same logger object. Loggers that are further
423down in the hierarchical list are children of loggers higher up in the list.
424For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000425``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000426
427Loggers have a concept of *effective level*. If a level is not explicitly set
428on a logger, the level of its parent is used instead as its effective level.
429If the parent has no explicit level set, *its* parent is examined, and so on -
430all ancestors are searched until an explicitly set level is found. The root
431logger always has an explicit level set (``WARNING`` by default). When deciding
432whether to process an event, the effective level of the logger is used to
433determine whether the event is passed to the logger's handlers.
434
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000435Child loggers propagate messages up to the handlers associated with their
Vinay Sajipf234eb92010-12-12 17:37:27 +0000436ancestor loggers. Because of this, it is unnecessary to define and configure
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000437handlers for all the loggers an application uses. It is sufficient to
438configure handlers for a top-level logger and create child loggers as needed.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000439(You can, however, turn off propagation by setting the *propagate*
440attribute of a logger to *False*.)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000441
442
Vinay Sajipf234eb92010-12-12 17:37:27 +0000443.. _handler-basic:
444
Christian Heimes8b0facf2007-12-04 19:30:01 +0000445Handlers
446^^^^^^^^
447
448:class:`Handler` objects are responsible for dispatching the appropriate log
449messages (based on the log messages' severity) to the handler's specified
450destination. Logger objects can add zero or more handler objects to themselves
451with an :func:`addHandler` method. As an example scenario, an application may
452want to send all log messages to a log file, all log messages of error or higher
453to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000454requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000455messages of a specific severity to a specific location.
456
Vinay Sajipf234eb92010-12-12 17:37:27 +0000457The standard library includes quite a few handler types (see
458:ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and
459:class:`FileHandler` in its examples.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000460
461There are very few methods in a handler for application developers to concern
462themselves with. The only handler methods that seem relevant for application
463developers who are using the built-in handler objects (that is, not creating
464custom handlers) are the following configuration methods:
465
466* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
467 lowest severity that will be dispatched to the appropriate destination. Why
468 are there two :func:`setLevel` methods? The level set in the logger
469 determines which severity of messages it will pass to its handlers. The level
470 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000471
472* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000473
474* :func:`addFilter` and :func:`removeFilter` respectively configure and
475 deconfigure filter objects on handlers.
476
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000477Application code should not directly instantiate and use instances of
478:class:`Handler`. Instead, the :class:`Handler` class is a base class that
479defines the interface that all handlers should have and establishes some
480default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000481
482
483Formatters
484^^^^^^^^^^
485
486Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000487message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000488instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000489if your application needs special behavior. The constructor takes three
490optional arguments -- a message format string, a date format string and a style
491indicator.
492
493.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
494
495If there is no message format string, the default is to use the
496raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000497
498 %Y-%m-%d %H:%M:%S
499
Vinay Sajipa39c5712010-10-25 13:57:39 +0000500with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
501or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000502
Vinay Sajipa39c5712010-10-25 13:57:39 +0000503If the ``style`` is '%', the message format string uses
504``%(<dictionary key>)s`` styled string substitution; the possible keys are
505documented in :ref:`formatter-objects`. If the style is '{', the message format
506string is assumed to be compatible with :meth:`str.format` (using keyword
507arguments), while if the style is '$' then the message format string should
508conform to what is expected by :meth:`string.Template.substitute`.
509
510.. versionchanged:: 3.2
511 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000512
513The following message format string will log the time in a human-readable
514format, the severity of the message, and the contents of the message, in that
515order::
516
517 "%(asctime)s - %(levelname)s - %(message)s"
518
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000519Formatters use a user-configurable function to convert the creation time of a
520record to a tuple. By default, :func:`time.localtime` is used; to change this
521for a particular formatter instance, set the ``converter`` attribute of the
522instance to a function with the same signature as :func:`time.localtime` or
523:func:`time.gmtime`. To change it for all formatters, for example if you want
524all logging times to be shown in GMT, set the ``converter`` attribute in the
525Formatter class (to ``time.gmtime`` for GMT display).
526
Christian Heimes8b0facf2007-12-04 19:30:01 +0000527
528Configuring Logging
529^^^^^^^^^^^^^^^^^^^
530
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000531Programmers can configure logging in three ways:
532
5331. Creating loggers, handlers, and formatters explicitly using Python
534 code that calls the configuration methods listed above.
5352. Creating a logging config file and reading it using the :func:`fileConfig`
536 function.
5373. Creating a dictionary of configuration information and passing it
538 to the :func:`dictConfig` function.
539
540The following example configures a very simple logger, a console
541handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000542
543 import logging
544
545 # create logger
546 logger = logging.getLogger("simple_example")
547 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000548
Christian Heimes8b0facf2007-12-04 19:30:01 +0000549 # create console handler and set level to debug
550 ch = logging.StreamHandler()
551 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000552
Christian Heimes8b0facf2007-12-04 19:30:01 +0000553 # create formatter
554 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000555
Christian Heimes8b0facf2007-12-04 19:30:01 +0000556 # add formatter to ch
557 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000558
Christian Heimes8b0facf2007-12-04 19:30:01 +0000559 # add ch to logger
560 logger.addHandler(ch)
561
562 # "application" code
563 logger.debug("debug message")
564 logger.info("info message")
565 logger.warn("warn message")
566 logger.error("error message")
567 logger.critical("critical message")
568
569Running this module from the command line produces the following output::
570
571 $ python simple_logging_module.py
572 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
573 2005-03-19 15:10:26,620 - simple_example - INFO - info message
574 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
575 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
576 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
577
578The following Python module creates a logger, handler, and formatter nearly
579identical to those in the example listed above, with the only difference being
580the names of the objects::
581
582 import logging
583 import logging.config
584
585 logging.config.fileConfig("logging.conf")
586
587 # create logger
588 logger = logging.getLogger("simpleExample")
589
590 # "application" code
591 logger.debug("debug message")
592 logger.info("info message")
593 logger.warn("warn message")
594 logger.error("error message")
595 logger.critical("critical message")
596
597Here is the logging.conf file::
598
599 [loggers]
600 keys=root,simpleExample
601
602 [handlers]
603 keys=consoleHandler
604
605 [formatters]
606 keys=simpleFormatter
607
608 [logger_root]
609 level=DEBUG
610 handlers=consoleHandler
611
612 [logger_simpleExample]
613 level=DEBUG
614 handlers=consoleHandler
615 qualname=simpleExample
616 propagate=0
617
618 [handler_consoleHandler]
619 class=StreamHandler
620 level=DEBUG
621 formatter=simpleFormatter
622 args=(sys.stdout,)
623
624 [formatter_simpleFormatter]
625 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
626 datefmt=
627
628The output is nearly identical to that of the non-config-file-based example::
629
630 $ python simple_logging_config.py
631 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
632 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
633 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
634 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
635 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
636
637You can see that the config file approach has a few advantages over the Python
638code approach, mainly separation of configuration and code and the ability of
639noncoders to easily modify the logging properties.
640
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000641Note that the class names referenced in config files need to be either relative
642to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000643import mechanisms. Thus, you could use either
644:class:`handlers.WatchedFileHandler` (relative to the logging module) or
645``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
646and module ``mymodule``, where ``mypackage`` is available on the Python import
647path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000648
Benjamin Peterson56894b52010-06-28 00:16:12 +0000649In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000650dictionaries to hold configuration information. This provides a superset of the
651functionality of the config-file-based approach outlined above, and is the
652recommended configuration method for new applications and deployments. Because
653a Python dictionary is used to hold configuration information, and since you
654can populate that dictionary using different means, you have more options for
655configuration. For example, you can use a configuration file in JSON format,
656or, if you have access to YAML processing functionality, a file in YAML
657format, to populate the configuration dictionary. Or, of course, you can
658construct the dictionary in Python code, receive it in pickled form over a
659socket, or use whatever approach makes sense for your application.
660
661Here's an example of the same configuration as above, in YAML format for
662the new dictionary-based approach::
663
664 version: 1
665 formatters:
666 simple:
667 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
668 handlers:
669 console:
670 class: logging.StreamHandler
671 level: DEBUG
672 formatter: simple
673 stream: ext://sys.stdout
674 loggers:
675 simpleExample:
676 level: DEBUG
677 handlers: [console]
678 propagate: no
679 root:
680 level: DEBUG
681 handlers: [console]
682
683For more information about logging using a dictionary, see
684:ref:`logging-config-api`.
685
Vinay Sajipf234eb92010-12-12 17:37:27 +0000686What happens if no configuration is provided
687^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
688
689If no logging configuration is provided, it is possible to have a situation
690where a logging event needs to be output, but no handlers can be found to
691output the event. The behaviour of the logging package in these
692circumstances is dependent on the Python version.
693
694For versions of Python prior to 3.2, the behaviour is as follows:
695
696* If *logging.raiseExceptions* is *False* (production mode), the event is
697 silently dropped.
698
699* If *logging.raiseExceptions* is *True* (development mode), a message
700 "No handlers could be found for logger X.Y.Z" is printed once.
701
702In Python 3.2 and later, the behaviour is as follows:
703
704* The event is output using a 'handler of last resort", stored in
705 ``logging.lastResort``. This internal handler is not associated with any
706 logger, and acts like a :class:`StreamHandler` which writes the event
707 description message to the current value of ``sys.stderr`` (therefore
708 respecting any redirections which may be in effect). No formatting is
709 done on the message - just the bare event description message is printed.
710 The handler's level is set to ``WARNING``, so all events at this and
711 greater severities will be output.
712
713To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*.
714
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000715.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000716
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000717Configuring Logging for a Library
718^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
719
Vinay Sajipf234eb92010-12-12 17:37:27 +0000720When developing a library which uses logging, you should take care to
721document how the library uses logging - for example, the names of loggers
722used. Some consideration also needs to be given to its logging configuration.
723If the using application does not use logging, and library code makes logging
724calls, then (as described in the previous section) events of severity
725``WARNING`` and greater will be printed to ``sys.stderr``. This is regarded as
726the best default behaviour.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000727
Vinay Sajipf234eb92010-12-12 17:37:27 +0000728If for some reason you *don't* want these messages printed in the absence of
729any logging configuration, you can attach a do-nothing handler to the top-level
730logger for your library. This avoids the message being printed, since a handler
731will be always be found for the library's events: it just doesn't produce any
732output. If the library user configures logging for application use, presumably
733that configuration will add some handlers, and if levels are suitably
734configured then logging calls made in library code will send output to those
735handlers, as normal.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000736
Vinay Sajipf234eb92010-12-12 17:37:27 +0000737A do-nothing handler is included in the logging package: :class:`NullHandler`
738(since Python 3.1). An instance of this handler could be added to the top-level
739logger of the logging namespace used by the library (*if* you want to prevent
740your library's logged events being output to ``sys.stderr`` in the absence of
741logging configuration). If all logging by a library *foo* is done using loggers
742with names matching 'foo.x', 'foo.x.y', etc. then the code::
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000743
744 import logging
Vinay Sajipf234eb92010-12-12 17:37:27 +0000745 logging.getLogger('foo').addHandler(logging.NullHandler())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000746
747should have the desired effect. If an organisation produces a number of
Vinay Sajipf234eb92010-12-12 17:37:27 +0000748libraries, then the logger name specified can be 'orgname.foo' rather than
749just 'foo'.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000750
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000751**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
752than* :class:`NullHandler` *to your library's loggers*. This is because the
753configuration of handlers is the prerogative of the application developer who
754uses your library. The application developer knows their target audience and
755what handlers are most appropriate for their application: if you add handlers
756"under the hood", you might well interfere with their ability to carry out
757unit tests and deliver logs which suit their requirements.
758
Christian Heimes8b0facf2007-12-04 19:30:01 +0000759
760Logging Levels
761--------------
762
Georg Brandl116aa622007-08-15 14:28:22 +0000763The numeric values of logging levels are given in the following table. These are
764primarily of interest if you want to define your own levels, and need them to
765have specific values relative to the predefined levels. If you define a level
766with the same numeric value, it overwrites the predefined value; the predefined
767name is lost.
768
769+--------------+---------------+
770| Level | Numeric value |
771+==============+===============+
772| ``CRITICAL`` | 50 |
773+--------------+---------------+
774| ``ERROR`` | 40 |
775+--------------+---------------+
776| ``WARNING`` | 30 |
777+--------------+---------------+
778| ``INFO`` | 20 |
779+--------------+---------------+
780| ``DEBUG`` | 10 |
781+--------------+---------------+
782| ``NOTSET`` | 0 |
783+--------------+---------------+
784
785Levels can also be associated with loggers, being set either by the developer or
786through loading a saved logging configuration. When a logging method is called
787on a logger, the logger compares its own level with the level associated with
788the method call. If the logger's level is higher than the method call's, no
789logging message is actually generated. This is the basic mechanism controlling
790the verbosity of logging output.
791
792Logging messages are encoded as instances of the :class:`LogRecord` class. When
793a logger decides to actually log an event, a :class:`LogRecord` instance is
794created from the logging message.
795
796Logging messages are subjected to a dispatch mechanism through the use of
797:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
798class. Handlers are responsible for ensuring that a logged message (in the form
799of a :class:`LogRecord`) ends up in a particular location (or set of locations)
800which is useful for the target audience for that message (such as end users,
801support desk staff, system administrators, developers). Handlers are passed
802:class:`LogRecord` instances intended for particular destinations. Each logger
803can have zero, one or more handlers associated with it (via the
804:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
805directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000806of the logger* are called to dispatch the message (unless the *propagate* flag
807for a logger is set to a false value, at which point the passing to ancestor
808handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810Just as for loggers, handlers can have levels associated with them. A handler's
811level acts as a filter in the same way as a logger's level does. If a handler
812decides to actually dispatch an event, the :meth:`emit` method is used to send
813the message to its destination. Most user-defined subclasses of :class:`Handler`
814will need to override this :meth:`emit`.
815
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000816.. _custom-levels:
817
818Custom Levels
819^^^^^^^^^^^^^
820
821Defining your own levels is possible, but should not be necessary, as the
822existing levels have been chosen on the basis of practical experience.
823However, if you are convinced that you need custom levels, great care should
824be exercised when doing this, and it is possibly *a very bad idea to define
825custom levels if you are developing a library*. That's because if multiple
826library authors all define their own custom levels, there is a chance that
827the logging output from such multiple libraries used together will be
828difficult for the using developer to control and/or interpret, because a
829given numeric value might mean different things for different libraries.
830
831
Vinay Sajipf234eb92010-12-12 17:37:27 +0000832.. _useful-handlers:
833
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000834Useful Handlers
835---------------
836
Georg Brandl116aa622007-08-15 14:28:22 +0000837In addition to the base :class:`Handler` class, many useful subclasses are
838provided:
839
Vinay Sajip121a1c42010-09-08 10:46:15 +0000840#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000841 objects).
842
Vinay Sajip121a1c42010-09-08 10:46:15 +0000843#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000844
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000845.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000846
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000847#. :class:`BaseRotatingHandler` is the base class for handlers that
848 rotate log files at a certain point. It is not meant to be instantiated
849 directly. Instead, use :class:`RotatingFileHandler` or
850 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000851
Vinay Sajip121a1c42010-09-08 10:46:15 +0000852#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000853 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000854
Vinay Sajip121a1c42010-09-08 10:46:15 +0000855#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000856 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Vinay Sajip121a1c42010-09-08 10:46:15 +0000858#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000859 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000860
Vinay Sajip121a1c42010-09-08 10:46:15 +0000861#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000862 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000863
Vinay Sajip121a1c42010-09-08 10:46:15 +0000864#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000865 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000866
Vinay Sajip121a1c42010-09-08 10:46:15 +0000867#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000868 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000869
Vinay Sajip121a1c42010-09-08 10:46:15 +0000870#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000871 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Vinay Sajip121a1c42010-09-08 10:46:15 +0000873#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000874 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000875
Vinay Sajip121a1c42010-09-08 10:46:15 +0000876#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000877 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000878
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000879#. :class:`WatchedFileHandler` instances watch the file they are
880 logging to. If the file changes, it is closed and reopened using the file
881 name. This handler is only useful on Unix-like systems; Windows does not
882 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000883
Vinay Sajip121a1c42010-09-08 10:46:15 +0000884#. :class:`QueueHandler` instances send messages to a queue, such as
885 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
886
Vinay Sajip30bf1222009-01-10 19:23:34 +0000887.. currentmodule:: logging
888
Georg Brandlf9734072008-12-07 15:30:06 +0000889#. :class:`NullHandler` instances do nothing with error messages. They are used
890 by library developers who want to use logging, but want to avoid the "No
891 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000892 the library user has not configured logging. See :ref:`library-config` for
893 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000894
895.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000896 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000897
Vinay Sajip121a1c42010-09-08 10:46:15 +0000898.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000899 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000900
Vinay Sajipa17775f2008-12-30 07:32:59 +0000901The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
902classes are defined in the core logging package. The other handlers are
903defined in a sub- module, :mod:`logging.handlers`. (There is also another
904sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906Logged messages are formatted for presentation through instances of the
907:class:`Formatter` class. They are initialized with a format string suitable for
908use with the % operator and a dictionary.
909
910For formatting multiple messages in a batch, instances of
911:class:`BufferingFormatter` can be used. In addition to the format string (which
912is applied to each message in the batch), there is provision for header and
913trailer format strings.
914
915When filtering based on logger level and/or handler level is not enough,
916instances of :class:`Filter` can be added to both :class:`Logger` and
917:class:`Handler` instances (through their :meth:`addFilter` method). Before
918deciding to process a message further, both loggers and handlers consult all
919their filters for permission. If any filter returns a false value, the message
920is not processed further.
921
922The basic :class:`Filter` functionality allows filtering by specific logger
923name. If this feature is used, messages sent to the named logger and its
924children are allowed through the filter, and all others dropped.
925
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000926Module-Level Functions
927----------------------
928
Georg Brandl116aa622007-08-15 14:28:22 +0000929In addition to the classes described above, there are a number of module- level
930functions.
931
932
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000933.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000934
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000935 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000936 logger which is the root logger of the hierarchy. If specified, the name is
937 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
938 Choice of these names is entirely up to the developer who is using logging.
939
940 All calls to this function with a given name return the same logger instance.
941 This means that logger instances never need to be passed between different parts
942 of an application.
943
944
945.. function:: getLoggerClass()
946
947 Return either the standard :class:`Logger` class, or the last class passed to
948 :func:`setLoggerClass`. This function may be called from within a new class
949 definition, to ensure that installing a customised :class:`Logger` class will
950 not undo customisations already applied by other code. For example::
951
952 class MyLogger(logging.getLoggerClass()):
953 # ... override behaviour here
954
955
Vinay Sajip61561522010-12-03 11:50:38 +0000956.. function:: getLogRecordFactory()
957
958 Return a callable which is used to create a :class:`LogRecord`.
959
960 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000961 This function has been provided, along with :func:`setLogRecordFactory`,
962 to allow developers more control over how the :class:`LogRecord`
963 representing a logging event is constructed.
964
965 See :func:`setLogRecordFactory` for more information about the how the
966 factory is called.
967
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000968.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
971 message format string, and the *args* are the arguments which are merged into
972 *msg* using the string formatting operator. (Note that this means that you can
973 use keywords in the format string, together with a single dictionary argument.)
974
Vinay Sajip8593ae62010-11-14 21:33:04 +0000975 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +0000976 which, if it does not evaluate as false, causes exception information to be
977 added to the logging message. If an exception tuple (in the format returned by
978 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
979 is called to get the exception information.
980
Vinay Sajip8593ae62010-11-14 21:33:04 +0000981 The second optional keyword argument is *stack_info*, which defaults to
982 False. If specified as True, stack information is added to the logging
983 message, including the actual logging call. Note that this is not the same
984 stack information as that displayed through specifying *exc_info*: The
985 former is stack frames from the bottom of the stack up to the logging call
986 in the current thread, whereas the latter is information about stack frames
987 which have been unwound, following an exception, while searching for
988 exception handlers.
989
990 You can specify *stack_info* independently of *exc_info*, e.g. to just show
991 how you got to a certain point in your code, even when no exceptions were
992 raised. The stack frames are printed following a header line which says::
993
994 Stack (most recent call last):
995
996 This mimics the `Traceback (most recent call last):` which is used when
997 displaying exception frames.
998
999 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001000 dictionary which is used to populate the __dict__ of the LogRecord created for
1001 the logging event with user-defined attributes. These custom attributes can then
1002 be used as you like. For example, they could be incorporated into logged
1003 messages. For example::
1004
1005 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1006 logging.basicConfig(format=FORMAT)
1007 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
1008 logging.warning("Protocol problem: %s", "connection reset", extra=d)
1009
Vinay Sajip4039aff2010-09-11 10:25:28 +00001010 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +00001011
1012 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1013
1014 The keys in the dictionary passed in *extra* should not clash with the keys used
1015 by the logging system. (See the :class:`Formatter` documentation for more
1016 information on which keys are used by the logging system.)
1017
1018 If you choose to use these attributes in logged messages, you need to exercise
1019 some care. In the above example, for instance, the :class:`Formatter` has been
1020 set up with a format string which expects 'clientip' and 'user' in the attribute
1021 dictionary of the LogRecord. If these are missing, the message will not be
1022 logged because a string formatting exception will occur. So in this case, you
1023 always need to pass the *extra* dictionary with these keys.
1024
1025 While this might be annoying, this feature is intended for use in specialized
1026 circumstances, such as multi-threaded servers where the same code executes in
1027 many contexts, and interesting conditions which arise are dependent on this
1028 context (such as remote client IP address and authenticated user name, in the
1029 above example). In such circumstances, it is likely that specialized
1030 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1031
Vinay Sajip8593ae62010-11-14 21:33:04 +00001032 .. versionadded:: 3.2
1033 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001035.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037 Logs a message with level :const:`INFO` on the root logger. The arguments are
1038 interpreted as for :func:`debug`.
1039
1040
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001041.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043 Logs a message with level :const:`WARNING` on the root logger. The arguments are
1044 interpreted as for :func:`debug`.
1045
1046
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001047.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1050 interpreted as for :func:`debug`.
1051
1052
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001053.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1056 are interpreted as for :func:`debug`.
1057
1058
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001059.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1062 interpreted as for :func:`debug`. Exception info is added to the logging
1063 message. This function should only be called from an exception handler.
1064
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001065.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001066
1067 Logs a message with level *level* on the root logger. The other arguments are
1068 interpreted as for :func:`debug`.
1069
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001070 PLEASE NOTE: The above module-level functions which delegate to the root
1071 logger should *not* be used in threads, in versions of Python earlier than
1072 2.7.1 and 3.2, unless at least one handler has been added to the root
1073 logger *before* the threads are started. These convenience functions call
1074 :func:`basicConfig` to ensure that at least one handler is available; in
1075 earlier versions of Python, this can (under rare circumstances) lead to
1076 handlers being added multiple times to the root logger, which can in turn
1077 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079.. function:: disable(lvl)
1080
1081 Provides an overriding level *lvl* for all loggers which takes precedence over
1082 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001083 output down across the whole application, this function can be useful. Its
1084 effect is to disable all logging calls of severity *lvl* and below, so that
1085 if you call it with a value of INFO, then all INFO and DEBUG events would be
1086 discarded, whereas those of severity WARNING and above would be processed
1087 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001088
1089
1090.. function:: addLevelName(lvl, levelName)
1091
1092 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1093 used to map numeric levels to a textual representation, for example when a
1094 :class:`Formatter` formats a message. This function can also be used to define
1095 your own levels. The only constraints are that all levels used must be
1096 registered using this function, levels should be positive integers and they
1097 should increase in increasing order of severity.
1098
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001099 NOTE: If you are thinking of defining your own levels, please see the section
1100 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102.. function:: getLevelName(lvl)
1103
1104 Returns the textual representation of logging level *lvl*. If the level is one
1105 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1106 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1107 have associated levels with names using :func:`addLevelName` then the name you
1108 have associated with *lvl* is returned. If a numeric value corresponding to one
1109 of the defined levels is passed in, the corresponding string representation is
1110 returned. Otherwise, the string "Level %s" % lvl is returned.
1111
1112
1113.. function:: makeLogRecord(attrdict)
1114
1115 Creates and returns a new :class:`LogRecord` instance whose attributes are
1116 defined by *attrdict*. This function is useful for taking a pickled
1117 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1118 it as a :class:`LogRecord` instance at the receiving end.
1119
1120
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001121.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001122
1123 Does basic configuration for the logging system by creating a
1124 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001125 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001126 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1127 if no handlers are defined for the root logger.
1128
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001129 This function does nothing if the root logger already has handlers
1130 configured for it.
1131
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001132 PLEASE NOTE: This function should be called from the main thread
1133 before other threads are started. In versions of Python prior to
1134 2.7.1 and 3.2, if this function is called from multiple threads,
1135 it is possible (in rare circumstances) that a handler will be added
1136 to the root logger more than once, leading to unexpected results
1137 such as messages being duplicated in the log.
1138
Georg Brandl116aa622007-08-15 14:28:22 +00001139 The following keyword arguments are supported.
1140
1141 +--------------+---------------------------------------------+
1142 | Format | Description |
1143 +==============+=============================================+
1144 | ``filename`` | Specifies that a FileHandler be created, |
1145 | | using the specified filename, rather than a |
1146 | | StreamHandler. |
1147 +--------------+---------------------------------------------+
1148 | ``filemode`` | Specifies the mode to open the file, if |
1149 | | filename is specified (if filemode is |
1150 | | unspecified, it defaults to 'a'). |
1151 +--------------+---------------------------------------------+
1152 | ``format`` | Use the specified format string for the |
1153 | | handler. |
1154 +--------------+---------------------------------------------+
1155 | ``datefmt`` | Use the specified date/time format. |
1156 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001157 | ``style`` | If ``format`` is specified, use this style |
1158 | | for the format string. One of '%', '{' or |
1159 | | '$' for %-formatting, :meth:`str.format` or |
1160 | | :class:`string.Template` respectively, and |
1161 | | defaulting to '%' if not specified. |
1162 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001163 | ``level`` | Set the root logger level to the specified |
1164 | | level. |
1165 +--------------+---------------------------------------------+
1166 | ``stream`` | Use the specified stream to initialize the |
1167 | | StreamHandler. Note that this argument is |
1168 | | incompatible with 'filename' - if both are |
1169 | | present, 'stream' is ignored. |
1170 +--------------+---------------------------------------------+
1171
Vinay Sajipc5b27302010-10-31 14:59:16 +00001172 .. versionchanged:: 3.2
1173 The ``style`` argument was added.
1174
1175
Georg Brandl116aa622007-08-15 14:28:22 +00001176.. function:: shutdown()
1177
1178 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001179 closing all handlers. This should be called at application exit and no
1180 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001181
1182
1183.. function:: setLoggerClass(klass)
1184
1185 Tells the logging system to use the class *klass* when instantiating a logger.
1186 The class should define :meth:`__init__` such that only a name argument is
1187 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1188 function is typically called before any loggers are instantiated by applications
1189 which need to use custom logger behavior.
1190
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001191
Vinay Sajip61561522010-12-03 11:50:38 +00001192.. function:: setLogRecordFactory(factory)
1193
1194 Set a callable which is used to create a :class:`LogRecord`.
1195
1196 :param factory: The factory callable to be used to instantiate a log record.
1197
1198 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001199 This function has been provided, along with :func:`getLogRecordFactory`, to
1200 allow developers more control over how the :class:`LogRecord` representing
1201 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001202
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001203 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001204
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001205 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, \*\*kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001206
1207 :name: The logger name.
1208 :level: The logging level (numeric).
1209 :fn: The full pathname of the file where the logging call was made.
1210 :lno: The line number in the file where the logging call was made.
1211 :msg: The logging message.
1212 :args: The arguments for the logging message.
1213 :exc_info: An exception tuple, or None.
1214 :func: The name of the function or method which invoked the logging
1215 call.
1216 :sinfo: A stack traceback such as is provided by
1217 :func:`traceback.print_stack`, showing the call hierarchy.
1218 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001219
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001220
Georg Brandl116aa622007-08-15 14:28:22 +00001221.. seealso::
1222
1223 :pep:`282` - A Logging System
1224 The proposal which described this feature for inclusion in the Python standard
1225 library.
1226
Christian Heimes255f53b2007-12-08 15:33:56 +00001227 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001228 This is the original source for the :mod:`logging` package. The version of the
1229 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1230 and 2.2.x, which do not include the :mod:`logging` package in the standard
1231 library.
1232
Vinay Sajip4039aff2010-09-11 10:25:28 +00001233.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001234
1235Logger Objects
1236--------------
1237
1238Loggers have the following attributes and methods. Note that Loggers are never
1239instantiated directly, but always through the module-level function
1240``logging.getLogger(name)``.
1241
Vinay Sajip0258ce82010-09-22 20:34:53 +00001242.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244.. attribute:: Logger.propagate
1245
1246 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001247 its child loggers to the handlers of higher level (ancestor) loggers. The
1248 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001249
1250
1251.. method:: Logger.setLevel(lvl)
1252
1253 Sets the threshold for this logger to *lvl*. Logging messages which are less
1254 severe than *lvl* will be ignored. When a logger is created, the level is set to
1255 :const:`NOTSET` (which causes all messages to be processed when the logger is
1256 the root logger, or delegation to the parent when the logger is a non-root
1257 logger). Note that the root logger is created with level :const:`WARNING`.
1258
1259 The term "delegation to the parent" means that if a logger has a level of
1260 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1261 a level other than NOTSET is found, or the root is reached.
1262
1263 If an ancestor is found with a level other than NOTSET, then that ancestor's
1264 level is treated as the effective level of the logger where the ancestor search
1265 began, and is used to determine how a logging event is handled.
1266
1267 If the root is reached, and it has a level of NOTSET, then all messages will be
1268 processed. Otherwise, the root's level will be used as the effective level.
1269
1270
1271.. method:: Logger.isEnabledFor(lvl)
1272
1273 Indicates if a message of severity *lvl* would be processed by this logger.
1274 This method checks first the module-level level set by
1275 ``logging.disable(lvl)`` and then the logger's effective level as determined
1276 by :meth:`getEffectiveLevel`.
1277
1278
1279.. method:: Logger.getEffectiveLevel()
1280
1281 Indicates the effective level for this logger. If a value other than
1282 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1283 the hierarchy is traversed towards the root until a value other than
1284 :const:`NOTSET` is found, and that value is returned.
1285
1286
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001287.. method:: Logger.getChild(suffix)
1288
1289 Returns a logger which is a descendant to this logger, as determined by the suffix.
1290 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1291 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1292 convenience method, useful when the parent logger is named using e.g. ``__name__``
1293 rather than a literal string.
1294
1295 .. versionadded:: 3.2
1296
Georg Brandl67b21b72010-08-17 15:07:14 +00001297
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001298.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1301 message format string, and the *args* are the arguments which are merged into
1302 *msg* using the string formatting operator. (Note that this means that you can
1303 use keywords in the format string, together with a single dictionary argument.)
1304
Vinay Sajip8593ae62010-11-14 21:33:04 +00001305 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001306 which, if it does not evaluate as false, causes exception information to be
1307 added to the logging message. If an exception tuple (in the format returned by
1308 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1309 is called to get the exception information.
1310
Vinay Sajip8593ae62010-11-14 21:33:04 +00001311 The second optional keyword argument is *stack_info*, which defaults to
1312 False. If specified as True, stack information is added to the logging
1313 message, including the actual logging call. Note that this is not the same
1314 stack information as that displayed through specifying *exc_info*: The
1315 former is stack frames from the bottom of the stack up to the logging call
1316 in the current thread, whereas the latter is information about stack frames
1317 which have been unwound, following an exception, while searching for
1318 exception handlers.
1319
1320 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1321 how you got to a certain point in your code, even when no exceptions were
1322 raised. The stack frames are printed following a header line which says::
1323
1324 Stack (most recent call last):
1325
1326 This mimics the `Traceback (most recent call last):` which is used when
1327 displaying exception frames.
1328
1329 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001330 dictionary which is used to populate the __dict__ of the LogRecord created for
1331 the logging event with user-defined attributes. These custom attributes can then
1332 be used as you like. For example, they could be incorporated into logged
1333 messages. For example::
1334
1335 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1336 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001337 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001338 logger = logging.getLogger("tcpserver")
1339 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1340
1341 would print something like ::
1342
1343 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1344
1345 The keys in the dictionary passed in *extra* should not clash with the keys used
1346 by the logging system. (See the :class:`Formatter` documentation for more
1347 information on which keys are used by the logging system.)
1348
1349 If you choose to use these attributes in logged messages, you need to exercise
1350 some care. In the above example, for instance, the :class:`Formatter` has been
1351 set up with a format string which expects 'clientip' and 'user' in the attribute
1352 dictionary of the LogRecord. If these are missing, the message will not be
1353 logged because a string formatting exception will occur. So in this case, you
1354 always need to pass the *extra* dictionary with these keys.
1355
1356 While this might be annoying, this feature is intended for use in specialized
1357 circumstances, such as multi-threaded servers where the same code executes in
1358 many contexts, and interesting conditions which arise are dependent on this
1359 context (such as remote client IP address and authenticated user name, in the
1360 above example). In such circumstances, it is likely that specialized
1361 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1362
Vinay Sajip8593ae62010-11-14 21:33:04 +00001363 .. versionadded:: 3.2
1364 The *stack_info* parameter was added.
1365
Georg Brandl116aa622007-08-15 14:28:22 +00001366
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001367.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369 Logs a message with level :const:`INFO` on this logger. The arguments are
1370 interpreted as for :meth:`debug`.
1371
1372
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001373.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001374
1375 Logs a message with level :const:`WARNING` on this logger. The arguments are
1376 interpreted as for :meth:`debug`.
1377
1378
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001379.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001380
1381 Logs a message with level :const:`ERROR` on this logger. The arguments are
1382 interpreted as for :meth:`debug`.
1383
1384
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001385.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1388 interpreted as for :meth:`debug`.
1389
1390
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001391.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393 Logs a message with integer level *lvl* on this logger. The other arguments are
1394 interpreted as for :meth:`debug`.
1395
1396
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001397.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001398
1399 Logs a message with level :const:`ERROR` on this logger. The arguments are
1400 interpreted as for :meth:`debug`. Exception info is added to the logging
1401 message. This method should only be called from an exception handler.
1402
1403
1404.. method:: Logger.addFilter(filt)
1405
1406 Adds the specified filter *filt* to this logger.
1407
1408
1409.. method:: Logger.removeFilter(filt)
1410
1411 Removes the specified filter *filt* from this logger.
1412
1413
1414.. method:: Logger.filter(record)
1415
1416 Applies this logger's filters to the record and returns a true value if the
1417 record is to be processed.
1418
1419
1420.. method:: Logger.addHandler(hdlr)
1421
1422 Adds the specified handler *hdlr* to this logger.
1423
1424
1425.. method:: Logger.removeHandler(hdlr)
1426
1427 Removes the specified handler *hdlr* from this logger.
1428
1429
Vinay Sajip8593ae62010-11-14 21:33:04 +00001430.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001431
1432 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001433 number, function name and stack information as a 4-element tuple. The stack
1434 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001435
Georg Brandl116aa622007-08-15 14:28:22 +00001436
1437.. method:: Logger.handle(record)
1438
1439 Handles a record by passing it to all handlers associated with this logger and
1440 its ancestors (until a false value of *propagate* is found). This method is used
1441 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001442 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001443
1444
Vinay Sajip8593ae62010-11-14 21:33:04 +00001445.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001446
1447 This is a factory method which can be overridden in subclasses to create
1448 specialized :class:`LogRecord` instances.
1449
Vinay Sajip83eadd12010-09-20 10:31:18 +00001450.. method:: Logger.hasHandlers()
1451
1452 Checks to see if this logger has any handlers configured. This is done by
1453 looking for handlers in this logger and its parents in the logger hierarchy.
1454 Returns True if a handler was found, else False. The method stops searching
1455 up the hierarchy whenever a logger with the "propagate" attribute set to
1456 False is found - that will be the last logger which is checked for the
1457 existence of handlers.
1458
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001459 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001460
Vinay Sajipa18b9592010-12-12 13:20:55 +00001461.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001462
1463Basic example
1464-------------
1465
Georg Brandl116aa622007-08-15 14:28:22 +00001466The :mod:`logging` package provides a lot of flexibility, and its configuration
1467can appear daunting. This section demonstrates that simple use of the logging
1468package is possible.
1469
1470The simplest example shows logging to the console::
1471
1472 import logging
1473
1474 logging.debug('A debug message')
1475 logging.info('Some information')
1476 logging.warning('A shot across the bows')
1477
1478If you run the above script, you'll see this::
1479
1480 WARNING:root:A shot across the bows
1481
1482Because no particular logger was specified, the system used the root logger. The
1483debug and info messages didn't appear because by default, the root logger is
1484configured to only handle messages with a severity of WARNING or above. The
1485message format is also a configuration default, as is the output destination of
1486the messages - ``sys.stderr``. The severity level, the message format and
1487destination can be easily changed, as shown in the example below::
1488
1489 import logging
1490
1491 logging.basicConfig(level=logging.DEBUG,
1492 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001493 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001494 filemode='w')
1495 logging.debug('A debug message')
1496 logging.info('Some information')
1497 logging.warning('A shot across the bows')
1498
1499The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001500which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001501something like the following::
1502
1503 2004-07-02 13:00:08,743 DEBUG A debug message
1504 2004-07-02 13:00:08,743 INFO Some information
1505 2004-07-02 13:00:08,743 WARNING A shot across the bows
1506
1507This time, all messages with a severity of DEBUG or above were handled, and the
1508format of the messages was also changed, and output went to the specified file
1509rather than the console.
1510
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001511.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001512
1513Formatting uses the old Python string formatting - see section
1514:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001515specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1516documentation.
1517
1518+-------------------+-----------------------------------------------+
1519| Format | Description |
1520+===================+===============================================+
1521| ``%(name)s`` | Name of the logger (logging channel). |
1522+-------------------+-----------------------------------------------+
1523| ``%(levelname)s`` | Text logging level for the message |
1524| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1525| | ``'ERROR'``, ``'CRITICAL'``). |
1526+-------------------+-----------------------------------------------+
1527| ``%(asctime)s`` | Human-readable time when the |
1528| | :class:`LogRecord` was created. By default |
1529| | this is of the form "2003-07-08 16:49:45,896" |
1530| | (the numbers after the comma are millisecond |
1531| | portion of the time). |
1532+-------------------+-----------------------------------------------+
1533| ``%(message)s`` | The logged message. |
1534+-------------------+-----------------------------------------------+
1535
1536To change the date/time format, you can pass an additional keyword parameter,
1537*datefmt*, as in the following::
1538
1539 import logging
1540
1541 logging.basicConfig(level=logging.DEBUG,
1542 format='%(asctime)s %(levelname)-8s %(message)s',
1543 datefmt='%a, %d %b %Y %H:%M:%S',
1544 filename='/temp/myapp.log',
1545 filemode='w')
1546 logging.debug('A debug message')
1547 logging.info('Some information')
1548 logging.warning('A shot across the bows')
1549
1550which would result in output like ::
1551
1552 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1553 Fri, 02 Jul 2004 13:06:18 INFO Some information
1554 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1555
1556The date format string follows the requirements of :func:`strftime` - see the
1557documentation for the :mod:`time` module.
1558
1559If, instead of sending logging output to the console or a file, you'd rather use
1560a file-like object which you have created separately, you can pass it to
1561:func:`basicConfig` using the *stream* keyword argument. Note that if both
1562*stream* and *filename* keyword arguments are passed, the *stream* argument is
1563ignored.
1564
1565Of course, you can put variable information in your output. To do this, simply
1566have the message be a format string and pass in additional arguments containing
1567the variable information, as in the following example::
1568
1569 import logging
1570
1571 logging.basicConfig(level=logging.DEBUG,
1572 format='%(asctime)s %(levelname)-8s %(message)s',
1573 datefmt='%a, %d %b %Y %H:%M:%S',
1574 filename='/temp/myapp.log',
1575 filemode='w')
1576 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1577
1578which would result in ::
1579
1580 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1581
1582
Vinay Sajipa18b9592010-12-12 13:20:55 +00001583Using file rotation
1584^^^^^^^^^^^^^^^^^^^
1585
1586.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1587.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1588
1589Sometimes you want to let a log file grow to a certain size, then open a new
1590file and log to that. You may want to keep a certain number of these files, and
1591when that many files have been created, rotate the files so that the number of
1592files and the size of the files both remin bounded. For this usage pattern, the
1593logging package provides a :class:`RotatingFileHandler`::
1594
1595 import glob
1596 import logging
1597 import logging.handlers
1598
1599 LOG_FILENAME = 'logging_rotatingfile_example.out'
1600
1601 # Set up a specific logger with our desired output level
1602 my_logger = logging.getLogger('MyLogger')
1603 my_logger.setLevel(logging.DEBUG)
1604
1605 # Add the log message handler to the logger
1606 handler = logging.handlers.RotatingFileHandler(
1607 LOG_FILENAME, maxBytes=20, backupCount=5)
1608
1609 my_logger.addHandler(handler)
1610
1611 # Log some messages
1612 for i in range(20):
1613 my_logger.debug('i = %d' % i)
1614
1615 # See what files are created
1616 logfiles = glob.glob('%s*' % LOG_FILENAME)
1617
1618 for filename in logfiles:
1619 print(filename)
1620
1621The result should be 6 separate files, each with part of the log history for the
1622application::
1623
1624 logging_rotatingfile_example.out
1625 logging_rotatingfile_example.out.1
1626 logging_rotatingfile_example.out.2
1627 logging_rotatingfile_example.out.3
1628 logging_rotatingfile_example.out.4
1629 logging_rotatingfile_example.out.5
1630
1631The most current file is always :file:`logging_rotatingfile_example.out`,
1632and each time it reaches the size limit it is renamed with the suffix
1633``.1``. Each of the existing backup files is renamed to increment the suffix
1634(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1635
1636Obviously this example sets the log length much much too small as an extreme
1637example. You would want to set *maxBytes* to an appropriate value.
1638
1639
1640The logger, handler, and log message call each specify a level. The log message
1641is only emitted if the handler and logger are configured to emit messages of
1642that level or lower. For example, if a message is ``CRITICAL``, and the logger
1643is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1644the logger is set to produce only ``ERROR``\s, the message is not emitted::
1645
1646 import logging
1647 import sys
1648
1649 LEVELS = {'debug': logging.DEBUG,
1650 'info': logging.INFO,
1651 'warning': logging.WARNING,
1652 'error': logging.ERROR,
1653 'critical': logging.CRITICAL}
1654
1655 if len(sys.argv) > 1:
1656 level_name = sys.argv[1]
1657 level = LEVELS.get(level_name, logging.NOTSET)
1658 logging.basicConfig(level=level)
1659
1660 logging.debug('This is a debug message')
1661 logging.info('This is an info message')
1662 logging.warning('This is a warning message')
1663 logging.error('This is an error message')
1664 logging.critical('This is a critical error message')
1665
1666Run the script with an argument like 'debug' or 'warning' to see which messages
1667show up at different levels::
1668
1669 $ python logging_level_example.py debug
1670 DEBUG:root:This is a debug message
1671 INFO:root:This is an info message
1672 WARNING:root:This is a warning message
1673 ERROR:root:This is an error message
1674 CRITICAL:root:This is a critical error message
1675
1676 $ python logging_level_example.py info
1677 INFO:root:This is an info message
1678 WARNING:root:This is a warning message
1679 ERROR:root:This is an error message
1680 CRITICAL:root:This is a critical error message
1681
1682You will notice that these log messages all have ``root`` embedded in them. The
1683logging module supports a hierarchy of loggers with different names. An easy
1684way to tell where a specific log message comes from is to use a separate logger
1685object for each of your modules. Each new logger "inherits" the configuration
1686of its parent, and log messages sent to a logger include the name of that
1687logger. Optionally, each logger can be configured differently, so that messages
1688from different modules are handled in different ways. Let's look at a simple
1689example of how to log from different modules so it is easy to trace the source
1690of the message::
1691
1692 import logging
1693
1694 logging.basicConfig(level=logging.WARNING)
1695
1696 logger1 = logging.getLogger('package1.module1')
1697 logger2 = logging.getLogger('package2.module2')
1698
1699 logger1.warning('This message comes from one module')
1700 logger2.warning('And this message comes from another module')
1701
1702And the output::
1703
1704 $ python logging_modules_example.py
1705 WARNING:package1.module1:This message comes from one module
1706 WARNING:package2.module2:And this message comes from another module
1707
1708There are many more options for configuring logging, including different log
1709message formatting options, having messages delivered to multiple destinations,
1710and changing the configuration of a long-running application on the fly using a
1711socket interface. All of these options are covered in depth in the library
1712module documentation.
1713
1714
Georg Brandl116aa622007-08-15 14:28:22 +00001715.. _multiple-destinations:
1716
1717Logging to multiple destinations
1718--------------------------------
1719
1720Let's say you want to log to console and file with different message formats and
1721in differing circumstances. Say you want to log messages with levels of DEBUG
1722and higher to file, and those messages at level INFO and higher to the console.
1723Let's also assume that the file should contain timestamps, but the console
1724messages should not. Here's how you can achieve this::
1725
1726 import logging
1727
1728 # set up logging to file - see previous section for more details
1729 logging.basicConfig(level=logging.DEBUG,
1730 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1731 datefmt='%m-%d %H:%M',
1732 filename='/temp/myapp.log',
1733 filemode='w')
1734 # define a Handler which writes INFO messages or higher to the sys.stderr
1735 console = logging.StreamHandler()
1736 console.setLevel(logging.INFO)
1737 # set a format which is simpler for console use
1738 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1739 # tell the handler to use this format
1740 console.setFormatter(formatter)
1741 # add the handler to the root logger
1742 logging.getLogger('').addHandler(console)
1743
1744 # Now, we can log to the root logger, or any other logger. First the root...
1745 logging.info('Jackdaws love my big sphinx of quartz.')
1746
1747 # Now, define a couple of other loggers which might represent areas in your
1748 # application:
1749
1750 logger1 = logging.getLogger('myapp.area1')
1751 logger2 = logging.getLogger('myapp.area2')
1752
1753 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1754 logger1.info('How quickly daft jumping zebras vex.')
1755 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1756 logger2.error('The five boxing wizards jump quickly.')
1757
1758When you run this, on the console you will see ::
1759
1760 root : INFO Jackdaws love my big sphinx of quartz.
1761 myapp.area1 : INFO How quickly daft jumping zebras vex.
1762 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1763 myapp.area2 : ERROR The five boxing wizards jump quickly.
1764
1765and in the file you will see something like ::
1766
1767 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1768 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1769 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1770 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1771 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1772
1773As you can see, the DEBUG message only shows up in the file. The other messages
1774are sent to both destinations.
1775
1776This example uses console and file handlers, but you can use any number and
1777combination of handlers you choose.
1778
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001779.. _logging-exceptions:
1780
1781Exceptions raised during logging
1782--------------------------------
1783
1784The logging package is designed to swallow exceptions which occur while logging
1785in production. This is so that errors which occur while handling logging events
1786- such as logging misconfiguration, network or other similar errors - do not
1787cause the application using logging to terminate prematurely.
1788
1789:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1790swallowed. Other exceptions which occur during the :meth:`emit` method of a
1791:class:`Handler` subclass are passed to its :meth:`handleError` method.
1792
1793The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001794to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1795traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001796
Georg Brandlef871f62010-03-12 10:06:40 +00001797**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001798during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001799occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001800usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001801
Christian Heimes790c8232008-01-07 21:14:23 +00001802.. _context-info:
1803
1804Adding contextual information to your logging output
1805----------------------------------------------------
1806
1807Sometimes you want logging output to contain contextual information in
1808addition to the parameters passed to the logging call. For example, in a
1809networked application, it may be desirable to log client-specific information
1810in the log (e.g. remote client's username, or IP address). Although you could
1811use the *extra* parameter to achieve this, it's not always convenient to pass
1812the information in this way. While it might be tempting to create
1813:class:`Logger` instances on a per-connection basis, this is not a good idea
1814because these instances are not garbage collected. While this is not a problem
1815in practice, when the number of :class:`Logger` instances is dependent on the
1816level of granularity you want to use in logging an application, it could
1817be hard to manage if the number of :class:`Logger` instances becomes
1818effectively unbounded.
1819
Vinay Sajipc31be632010-09-06 22:18:20 +00001820
1821Using LoggerAdapters to impart contextual information
1822^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1823
Christian Heimes04c420f2008-01-18 18:40:46 +00001824An easy way in which you can pass contextual information to be output along
1825with logging event information is to use the :class:`LoggerAdapter` class.
1826This class is designed to look like a :class:`Logger`, so that you can call
1827:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1828:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1829same signatures as their counterparts in :class:`Logger`, so you can use the
1830two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001831
Christian Heimes04c420f2008-01-18 18:40:46 +00001832When you create an instance of :class:`LoggerAdapter`, you pass it a
1833:class:`Logger` instance and a dict-like object which contains your contextual
1834information. When you call one of the logging methods on an instance of
1835:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1836:class:`Logger` passed to its constructor, and arranges to pass the contextual
1837information in the delegated call. Here's a snippet from the code of
1838:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001839
Christian Heimes04c420f2008-01-18 18:40:46 +00001840 def debug(self, msg, *args, **kwargs):
1841 """
1842 Delegate a debug call to the underlying logger, after adding
1843 contextual information from this adapter instance.
1844 """
1845 msg, kwargs = self.process(msg, kwargs)
1846 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001847
Christian Heimes04c420f2008-01-18 18:40:46 +00001848The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1849information is added to the logging output. It's passed the message and
1850keyword arguments of the logging call, and it passes back (potentially)
1851modified versions of these to use in the call to the underlying logger. The
1852default implementation of this method leaves the message alone, but inserts
1853an "extra" key in the keyword argument whose value is the dict-like object
1854passed to the constructor. Of course, if you had passed an "extra" keyword
1855argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001856
Christian Heimes04c420f2008-01-18 18:40:46 +00001857The advantage of using "extra" is that the values in the dict-like object are
1858merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1859customized strings with your :class:`Formatter` instances which know about
1860the keys of the dict-like object. If you need a different method, e.g. if you
1861want to prepend or append the contextual information to the message string,
1862you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1863to do what you need. Here's an example script which uses this class, which
1864also illustrates what dict-like behaviour is needed from an arbitrary
1865"dict-like" object for use in the constructor::
1866
Christian Heimes587c2bf2008-01-19 16:21:02 +00001867 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001868
Christian Heimes587c2bf2008-01-19 16:21:02 +00001869 class ConnInfo:
1870 """
1871 An example class which shows how an arbitrary class can be used as
1872 the 'extra' context information repository passed to a LoggerAdapter.
1873 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001874
Christian Heimes587c2bf2008-01-19 16:21:02 +00001875 def __getitem__(self, name):
1876 """
1877 To allow this instance to look like a dict.
1878 """
1879 from random import choice
1880 if name == "ip":
1881 result = choice(["127.0.0.1", "192.168.0.1"])
1882 elif name == "user":
1883 result = choice(["jim", "fred", "sheila"])
1884 else:
1885 result = self.__dict__.get(name, "?")
1886 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001887
Christian Heimes587c2bf2008-01-19 16:21:02 +00001888 def __iter__(self):
1889 """
1890 To allow iteration over keys, which will be merged into
1891 the LogRecord dict before formatting and output.
1892 """
1893 keys = ["ip", "user"]
1894 keys.extend(self.__dict__.keys())
1895 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001896
Christian Heimes587c2bf2008-01-19 16:21:02 +00001897 if __name__ == "__main__":
1898 from random import choice
1899 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1900 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1901 { "ip" : "123.231.231.123", "user" : "sheila" })
1902 logging.basicConfig(level=logging.DEBUG,
1903 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1904 a1.debug("A debug message")
1905 a1.info("An info message with %s", "some parameters")
1906 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1907 for x in range(10):
1908 lvl = choice(levels)
1909 lvlname = logging.getLevelName(lvl)
1910 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001911
1912When this script is run, the output should look something like this::
1913
Christian Heimes587c2bf2008-01-19 16:21:02 +00001914 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1915 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1916 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
1917 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
1918 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
1919 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
1920 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
1921 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
1922 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
1923 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
1924 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
1925 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 +00001926
Christian Heimes790c8232008-01-07 21:14:23 +00001927
Vinay Sajipac007992010-09-17 12:45:26 +00001928.. _filters-contextual:
1929
Vinay Sajipc31be632010-09-06 22:18:20 +00001930Using Filters to impart contextual information
1931^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1932
1933You can also add contextual information to log output using a user-defined
1934:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1935passed to them, including adding additional attributes which can then be output
1936using a suitable format string, or if needed a custom :class:`Formatter`.
1937
1938For example in a web application, the request being processed (or at least,
1939the interesting parts of it) can be stored in a threadlocal
1940(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1941add, say, information from the request - say, the remote IP address and remote
1942user's username - to the ``LogRecord``, using the attribute names 'ip' and
1943'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1944string can be used to get similar output to that shown above. Here's an example
1945script::
1946
1947 import logging
1948 from random import choice
1949
1950 class ContextFilter(logging.Filter):
1951 """
1952 This is a filter which injects contextual information into the log.
1953
1954 Rather than use actual contextual information, we just use random
1955 data in this demo.
1956 """
1957
1958 USERS = ['jim', 'fred', 'sheila']
1959 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1960
1961 def filter(self, record):
1962
1963 record.ip = choice(ContextFilter.IPS)
1964 record.user = choice(ContextFilter.USERS)
1965 return True
1966
1967 if __name__ == "__main__":
1968 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1969 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1970 { "ip" : "123.231.231.123", "user" : "sheila" })
1971 logging.basicConfig(level=logging.DEBUG,
1972 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1973 a1 = logging.getLogger("a.b.c")
1974 a2 = logging.getLogger("d.e.f")
1975
1976 f = ContextFilter()
1977 a1.addFilter(f)
1978 a2.addFilter(f)
1979 a1.debug("A debug message")
1980 a1.info("An info message with %s", "some parameters")
1981 for x in range(10):
1982 lvl = choice(levels)
1983 lvlname = logging.getLevelName(lvl)
1984 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1985
1986which, when run, produces something like::
1987
1988 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
1989 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
1990 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
1991 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
1992 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
1993 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
1994 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
1995 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
1996 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
1997 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
1998 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
1999 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
2000
2001
Vinay Sajipd31f3632010-06-29 15:31:15 +00002002.. _multiple-processes:
2003
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002004Logging to a single file from multiple processes
2005------------------------------------------------
2006
2007Although logging is thread-safe, and logging to a single file from multiple
2008threads in a single process *is* supported, logging to a single file from
2009*multiple processes* is *not* supported, because there is no standard way to
2010serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00002011need to log to a single file from multiple processes, one way of doing this is
2012to have all the processes log to a :class:`SocketHandler`, and have a separate
2013process which implements a socket server which reads from the socket and logs
2014to file. (If you prefer, you can dedicate one thread in one of the existing
2015processes to perform this function.) The following section documents this
2016approach in more detail and includes a working socket receiver which can be
2017used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002018
Vinay Sajip5a92b132009-08-15 23:35:08 +00002019If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00002020:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00002021:class:`Lock` class from this module to serialize access to the file from
2022your processes. The existing :class:`FileHandler` and subclasses do not make
2023use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00002024Note that at present, the :mod:`multiprocessing` module does not provide
2025working lock functionality on all platforms (see
2026http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00002027
Vinay Sajip121a1c42010-09-08 10:46:15 +00002028.. currentmodule:: logging.handlers
2029
2030Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
2031all logging events to one of the processes in your multi-process application.
2032The following example script demonstrates how you can do this; in the example
2033a separate listener process listens for events sent by other processes and logs
2034them according to its own logging configuration. Although the example only
2035demonstrates one way of doing it (for example, you may want to use a listener
2036thread rather than a separate listener process - the implementation would be
2037analogous) it does allow for completely different logging configurations for
2038the listener and the other processes in your application, and can be used as
2039the basis for code meeting your own specific requirements::
2040
2041 # You'll need these imports in your own code
2042 import logging
2043 import logging.handlers
2044 import multiprocessing
2045
2046 # Next two import lines for this demo only
2047 from random import choice, random
2048 import time
2049
2050 #
2051 # Because you'll want to define the logging configurations for listener and workers, the
2052 # listener and worker process functions take a configurer parameter which is a callable
2053 # for configuring logging for that process. These functions are also passed the queue,
2054 # which they use for communication.
2055 #
2056 # In practice, you can configure the listener however you want, but note that in this
2057 # simple example, the listener does not apply level or filter logic to received records.
2058 # In practice, you would probably want to do ths logic in the worker processes, to avoid
2059 # sending events which would be filtered out between processes.
2060 #
2061 # The size of the rotated files is made small so you can see the results easily.
2062 def listener_configurer():
2063 root = logging.getLogger()
2064 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2065 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2066 h.setFormatter(f)
2067 root.addHandler(h)
2068
2069 # This is the listener process top-level loop: wait for logging events
2070 # (LogRecords)on the queue and handle them, quit when you get a None for a
2071 # LogRecord.
2072 def listener_process(queue, configurer):
2073 configurer()
2074 while True:
2075 try:
2076 record = queue.get()
2077 if record is None: # We send this as a sentinel to tell the listener to quit.
2078 break
2079 logger = logging.getLogger(record.name)
2080 logger.handle(record) # No level or filter logic applied - just do it!
2081 except (KeyboardInterrupt, SystemExit):
2082 raise
2083 except:
2084 import sys, traceback
2085 print >> sys.stderr, 'Whoops! Problem:'
2086 traceback.print_exc(file=sys.stderr)
2087
2088 # Arrays used for random selections in this demo
2089
2090 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2091 logging.ERROR, logging.CRITICAL]
2092
2093 LOGGERS = ['a.b.c', 'd.e.f']
2094
2095 MESSAGES = [
2096 'Random message #1',
2097 'Random message #2',
2098 'Random message #3',
2099 ]
2100
2101 # The worker configuration is done at the start of the worker process run.
2102 # Note that on Windows you can't rely on fork semantics, so each process
2103 # will run the logging configuration code when it starts.
2104 def worker_configurer(queue):
2105 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2106 root = logging.getLogger()
2107 root.addHandler(h)
2108 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2109
2110 # This is the worker process top-level loop, which just logs ten events with
2111 # random intervening delays before terminating.
2112 # The print messages are just so you know it's doing something!
2113 def worker_process(queue, configurer):
2114 configurer(queue)
2115 name = multiprocessing.current_process().name
2116 print('Worker started: %s' % name)
2117 for i in range(10):
2118 time.sleep(random())
2119 logger = logging.getLogger(choice(LOGGERS))
2120 level = choice(LEVELS)
2121 message = choice(MESSAGES)
2122 logger.log(level, message)
2123 print('Worker finished: %s' % name)
2124
2125 # Here's where the demo gets orchestrated. Create the queue, create and start
2126 # the listener, create ten workers and start them, wait for them to finish,
2127 # then send a None to the queue to tell the listener to finish.
2128 def main():
2129 queue = multiprocessing.Queue(-1)
2130 listener = multiprocessing.Process(target=listener_process,
2131 args=(queue, listener_configurer))
2132 listener.start()
2133 workers = []
2134 for i in range(10):
2135 worker = multiprocessing.Process(target=worker_process,
2136 args=(queue, worker_configurer))
2137 workers.append(worker)
2138 worker.start()
2139 for w in workers:
2140 w.join()
2141 queue.put_nowait(None)
2142 listener.join()
2143
2144 if __name__ == '__main__':
2145 main()
2146
2147
2148.. currentmodule:: logging
2149
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002150
Georg Brandl116aa622007-08-15 14:28:22 +00002151.. _network-logging:
2152
2153Sending and receiving logging events across a network
2154-----------------------------------------------------
2155
2156Let's say you want to send logging events across a network, and handle them at
2157the receiving end. A simple way of doing this is attaching a
2158:class:`SocketHandler` instance to the root logger at the sending end::
2159
2160 import logging, logging.handlers
2161
2162 rootLogger = logging.getLogger('')
2163 rootLogger.setLevel(logging.DEBUG)
2164 socketHandler = logging.handlers.SocketHandler('localhost',
2165 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2166 # don't bother with a formatter, since a socket handler sends the event as
2167 # an unformatted pickle
2168 rootLogger.addHandler(socketHandler)
2169
2170 # Now, we can log to the root logger, or any other logger. First the root...
2171 logging.info('Jackdaws love my big sphinx of quartz.')
2172
2173 # Now, define a couple of other loggers which might represent areas in your
2174 # application:
2175
2176 logger1 = logging.getLogger('myapp.area1')
2177 logger2 = logging.getLogger('myapp.area2')
2178
2179 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2180 logger1.info('How quickly daft jumping zebras vex.')
2181 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2182 logger2.error('The five boxing wizards jump quickly.')
2183
Alexandre Vassalottice261952008-05-12 02:31:37 +00002184At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002185module. Here is a basic working example::
2186
Georg Brandla35f4b92009-05-31 16:41:59 +00002187 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002188 import logging
2189 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002190 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002191 import struct
2192
2193
Alexandre Vassalottice261952008-05-12 02:31:37 +00002194 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002195 """Handler for a streaming logging request.
2196
2197 This basically logs the record using whatever logging policy is
2198 configured locally.
2199 """
2200
2201 def handle(self):
2202 """
2203 Handle multiple requests - each expected to be a 4-byte length,
2204 followed by the LogRecord in pickle format. Logs the record
2205 according to whatever policy is configured locally.
2206 """
Collin Winter46334482007-09-10 00:49:57 +00002207 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002208 chunk = self.connection.recv(4)
2209 if len(chunk) < 4:
2210 break
2211 slen = struct.unpack(">L", chunk)[0]
2212 chunk = self.connection.recv(slen)
2213 while len(chunk) < slen:
2214 chunk = chunk + self.connection.recv(slen - len(chunk))
2215 obj = self.unPickle(chunk)
2216 record = logging.makeLogRecord(obj)
2217 self.handleLogRecord(record)
2218
2219 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002220 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002221
2222 def handleLogRecord(self, record):
2223 # if a name is specified, we use the named logger rather than the one
2224 # implied by the record.
2225 if self.server.logname is not None:
2226 name = self.server.logname
2227 else:
2228 name = record.name
2229 logger = logging.getLogger(name)
2230 # N.B. EVERY record gets logged. This is because Logger.handle
2231 # is normally called AFTER logger-level filtering. If you want
2232 # to do filtering, do it at the client end to save wasting
2233 # cycles and network bandwidth!
2234 logger.handle(record)
2235
Alexandre Vassalottice261952008-05-12 02:31:37 +00002236 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00002237 """simple TCP socket-based logging receiver suitable for testing.
2238 """
2239
2240 allow_reuse_address = 1
2241
2242 def __init__(self, host='localhost',
2243 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2244 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002245 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002246 self.abort = 0
2247 self.timeout = 1
2248 self.logname = None
2249
2250 def serve_until_stopped(self):
2251 import select
2252 abort = 0
2253 while not abort:
2254 rd, wr, ex = select.select([self.socket.fileno()],
2255 [], [],
2256 self.timeout)
2257 if rd:
2258 self.handle_request()
2259 abort = self.abort
2260
2261 def main():
2262 logging.basicConfig(
2263 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
2264 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00002265 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00002266 tcpserver.serve_until_stopped()
2267
2268 if __name__ == "__main__":
2269 main()
2270
2271First run the server, and then the client. On the client side, nothing is
2272printed on the console; on the server side, you should see something like::
2273
2274 About to start TCP server...
2275 59 root INFO Jackdaws love my big sphinx of quartz.
2276 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2277 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2278 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2279 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2280
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002281Note that there are some security issues with pickle in some scenarios. If
2282these affect you, you can use an alternative serialization scheme by overriding
2283the :meth:`makePickle` method and implementing your alternative there, as
2284well as adapting the above script to use your alternative serialization.
2285
Vinay Sajip4039aff2010-09-11 10:25:28 +00002286.. _arbitrary-object-messages:
2287
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002288Using arbitrary objects as messages
2289-----------------------------------
2290
2291In the preceding sections and examples, it has been assumed that the message
2292passed when logging the event is a string. However, this is not the only
2293possibility. You can pass an arbitrary object as a message, and its
2294:meth:`__str__` method will be called when the logging system needs to convert
2295it to a string representation. In fact, if you want to, you can avoid
2296computing a string representation altogether - for example, the
2297:class:`SocketHandler` emits an event by pickling it and sending it over the
2298wire.
2299
Vinay Sajip55778922010-09-23 09:09:15 +00002300Dealing with handlers that block
2301--------------------------------
2302
2303.. currentmodule:: logging.handlers
2304
2305Sometimes you have to get your logging handlers to do their work without
2306blocking the thread you’re logging from. This is common in Web applications,
2307though of course it also occurs in other scenarios.
2308
2309A common culprit which demonstrates sluggish behaviour is the
2310:class:`SMTPHandler`: sending emails can take a long time, for a
2311number of reasons outside the developer’s control (for example, a poorly
2312performing mail or network infrastructure). But almost any network-based
2313handler can block: Even a :class:`SocketHandler` operation may do a
2314DNS query under the hood which is too slow (and this query can be deep in the
2315socket library code, below the Python layer, and outside your control).
2316
2317One solution is to use a two-part approach. For the first part, attach only a
2318:class:`QueueHandler` to those loggers which are accessed from
2319performance-critical threads. They simply write to their queue, which can be
2320sized to a large enough capacity or initialized with no upper bound to their
2321size. The write to the queue will typically be accepted quickly, though you
2322will probably need to catch the :ref:`queue.Full` exception as a precaution
2323in your code. If you are a library developer who has performance-critical
2324threads in their code, be sure to document this (together with a suggestion to
2325attach only ``QueueHandlers`` to your loggers) for the benefit of other
2326developers who will use your code.
2327
2328The second part of the solution is :class:`QueueListener`, which has been
2329designed as the counterpart to :class:`QueueHandler`. A
2330:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2331and it fires up an internal thread which listens to its queue for LogRecords
2332sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2333matter). The ``LogRecords`` are removed from the queue and passed to the
2334handlers for processing.
2335
2336The advantage of having a separate :class:`QueueListener` class is that you
2337can use the same instance to service multiple ``QueueHandlers``. This is more
2338resource-friendly than, say, having threaded versions of the existing handler
2339classes, which would eat up one thread per handler for no particular benefit.
2340
2341An example of using these two classes follows (imports omitted)::
2342
2343 que = queue.Queue(-1) # no limit on size
2344 queue_handler = QueueHandler(que)
2345 handler = logging.StreamHandler()
2346 listener = QueueListener(que, handler)
2347 root = logging.getLogger()
2348 root.addHandler(queue_handler)
2349 formatter = logging.Formatter('%(threadName)s: %(message)s')
2350 handler.setFormatter(formatter)
2351 listener.start()
2352 # The log output will display the thread which generated
2353 # the event (the main thread) rather than the internal
2354 # thread which monitors the internal queue. This is what
2355 # you want to happen.
2356 root.warning('Look out!')
2357 listener.stop()
2358
2359which, when run, will produce::
2360
2361 MainThread: Look out!
2362
2363
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002364Optimization
2365------------
2366
2367Formatting of message arguments is deferred until it cannot be avoided.
2368However, computing the arguments passed to the logging method can also be
2369expensive, and you may want to avoid doing it if the logger will just throw
2370away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2371method which takes a level argument and returns true if the event would be
2372created by the Logger for that level of call. You can write code like this::
2373
2374 if logger.isEnabledFor(logging.DEBUG):
2375 logger.debug("Message with %s, %s", expensive_func1(),
2376 expensive_func2())
2377
2378so that if the logger's threshold is set above ``DEBUG``, the calls to
2379:func:`expensive_func1` and :func:`expensive_func2` are never made.
2380
2381There are other optimizations which can be made for specific applications which
2382need more precise control over what logging information is collected. Here's a
2383list of things you can do to avoid processing during logging which you don't
2384need:
2385
2386+-----------------------------------------------+----------------------------------------+
2387| What you don't want to collect | How to avoid collecting it |
2388+===============================================+========================================+
2389| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2390+-----------------------------------------------+----------------------------------------+
2391| Threading information. | Set ``logging.logThreads`` to ``0``. |
2392+-----------------------------------------------+----------------------------------------+
2393| Process information. | Set ``logging.logProcesses`` to ``0``. |
2394+-----------------------------------------------+----------------------------------------+
2395
2396Also note that the core logging module only includes the basic handlers. If
2397you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2398take up any memory.
2399
2400.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002401
2402Handler Objects
2403---------------
2404
2405Handlers have the following attributes and methods. Note that :class:`Handler`
2406is never instantiated directly; this class acts as a base for more useful
2407subclasses. However, the :meth:`__init__` method in subclasses needs to call
2408:meth:`Handler.__init__`.
2409
2410
2411.. method:: Handler.__init__(level=NOTSET)
2412
2413 Initializes the :class:`Handler` instance by setting its level, setting the list
2414 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2415 serializing access to an I/O mechanism.
2416
2417
2418.. method:: Handler.createLock()
2419
2420 Initializes a thread lock which can be used to serialize access to underlying
2421 I/O functionality which may not be threadsafe.
2422
2423
2424.. method:: Handler.acquire()
2425
2426 Acquires the thread lock created with :meth:`createLock`.
2427
2428
2429.. method:: Handler.release()
2430
2431 Releases the thread lock acquired with :meth:`acquire`.
2432
2433
2434.. method:: Handler.setLevel(lvl)
2435
2436 Sets the threshold for this handler to *lvl*. Logging messages which are less
2437 severe than *lvl* will be ignored. When a handler is created, the level is set
2438 to :const:`NOTSET` (which causes all messages to be processed).
2439
2440
2441.. method:: Handler.setFormatter(form)
2442
2443 Sets the :class:`Formatter` for this handler to *form*.
2444
2445
2446.. method:: Handler.addFilter(filt)
2447
2448 Adds the specified filter *filt* to this handler.
2449
2450
2451.. method:: Handler.removeFilter(filt)
2452
2453 Removes the specified filter *filt* from this handler.
2454
2455
2456.. method:: Handler.filter(record)
2457
2458 Applies this handler's filters to the record and returns a true value if the
2459 record is to be processed.
2460
2461
2462.. method:: Handler.flush()
2463
2464 Ensure all logging output has been flushed. This version does nothing and is
2465 intended to be implemented by subclasses.
2466
2467
2468.. method:: Handler.close()
2469
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002470 Tidy up any resources used by the handler. This version does no output but
2471 removes the handler from an internal list of handlers which is closed when
2472 :func:`shutdown` is called. Subclasses should ensure that this gets called
2473 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002474
2475
2476.. method:: Handler.handle(record)
2477
2478 Conditionally emits the specified logging record, depending on filters which may
2479 have been added to the handler. Wraps the actual emission of the record with
2480 acquisition/release of the I/O thread lock.
2481
2482
2483.. method:: Handler.handleError(record)
2484
2485 This method should be called from handlers when an exception is encountered
2486 during an :meth:`emit` call. By default it does nothing, which means that
2487 exceptions get silently ignored. This is what is mostly wanted for a logging
2488 system - most users will not care about errors in the logging system, they are
2489 more interested in application errors. You could, however, replace this with a
2490 custom handler if you wish. The specified record is the one which was being
2491 processed when the exception occurred.
2492
2493
2494.. method:: Handler.format(record)
2495
2496 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2497 default formatter for the module.
2498
2499
2500.. method:: Handler.emit(record)
2501
2502 Do whatever it takes to actually log the specified logging record. This version
2503 is intended to be implemented by subclasses and so raises a
2504 :exc:`NotImplementedError`.
2505
2506
Vinay Sajipd31f3632010-06-29 15:31:15 +00002507.. _stream-handler:
2508
Georg Brandl116aa622007-08-15 14:28:22 +00002509StreamHandler
2510^^^^^^^^^^^^^
2511
2512The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2513sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2514file-like object (or, more precisely, any object which supports :meth:`write`
2515and :meth:`flush` methods).
2516
2517
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002518.. currentmodule:: logging
2519
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002520.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002521
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002522 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002523 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2524 will be used.
2525
2526
Benjamin Petersone41251e2008-04-25 01:59:09 +00002527 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002528
Benjamin Petersone41251e2008-04-25 01:59:09 +00002529 If a formatter is specified, it is used to format the record. The record
2530 is then written to the stream with a trailing newline. If exception
2531 information is present, it is formatted using
2532 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002533
2534
Benjamin Petersone41251e2008-04-25 01:59:09 +00002535 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002536
Benjamin Petersone41251e2008-04-25 01:59:09 +00002537 Flushes the stream by calling its :meth:`flush` method. Note that the
2538 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002539 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002540
Vinay Sajip05ed6952010-10-20 20:34:09 +00002541.. versionchanged:: 3.2
2542 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2543 value ``"\n"``, which is used as the terminator when writing a formatted
2544 record to a stream. If you don't want this newline termination, you can
2545 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002546
Vinay Sajipd31f3632010-06-29 15:31:15 +00002547.. _file-handler:
2548
Georg Brandl116aa622007-08-15 14:28:22 +00002549FileHandler
2550^^^^^^^^^^^
2551
2552The :class:`FileHandler` class, located in the core :mod:`logging` package,
2553sends logging output to a disk file. It inherits the output functionality from
2554:class:`StreamHandler`.
2555
2556
Vinay Sajipd31f3632010-06-29 15:31:15 +00002557.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002558
2559 Returns a new instance of the :class:`FileHandler` class. The specified file is
2560 opened and used as the stream for logging. If *mode* is not specified,
2561 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002562 with that encoding. If *delay* is true, then file opening is deferred until the
2563 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002564
2565
Benjamin Petersone41251e2008-04-25 01:59:09 +00002566 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002567
Benjamin Petersone41251e2008-04-25 01:59:09 +00002568 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002569
2570
Benjamin Petersone41251e2008-04-25 01:59:09 +00002571 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002572
Benjamin Petersone41251e2008-04-25 01:59:09 +00002573 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002574
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002575
Vinay Sajipd31f3632010-06-29 15:31:15 +00002576.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002577
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002578NullHandler
2579^^^^^^^^^^^
2580
2581.. versionadded:: 3.1
2582
2583The :class:`NullHandler` class, located in the core :mod:`logging` package,
2584does not do any formatting or output. It is essentially a "no-op" handler
2585for use by library developers.
2586
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002587.. class:: NullHandler()
2588
2589 Returns a new instance of the :class:`NullHandler` class.
2590
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002591 .. method:: emit(record)
2592
2593 This method does nothing.
2594
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002595 .. method:: handle(record)
2596
2597 This method does nothing.
2598
2599 .. method:: createLock()
2600
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002601 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002602 underlying I/O to which access needs to be serialized.
2603
2604
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002605See :ref:`library-config` for more information on how to use
2606:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002607
Vinay Sajipd31f3632010-06-29 15:31:15 +00002608.. _watched-file-handler:
2609
Georg Brandl116aa622007-08-15 14:28:22 +00002610WatchedFileHandler
2611^^^^^^^^^^^^^^^^^^
2612
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002613.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002614
Georg Brandl116aa622007-08-15 14:28:22 +00002615The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2616module, is a :class:`FileHandler` which watches the file it is logging to. If
2617the file changes, it is closed and reopened using the file name.
2618
2619A file change can happen because of usage of programs such as *newsyslog* and
2620*logrotate* which perform log file rotation. This handler, intended for use
2621under Unix/Linux, watches the file to see if it has changed since the last emit.
2622(A file is deemed to have changed if its device or inode have changed.) If the
2623file has changed, the old file stream is closed, and the file opened to get a
2624new stream.
2625
2626This handler is not appropriate for use under Windows, because under Windows
2627open log files cannot be moved or renamed - logging opens the files with
2628exclusive locks - and so there is no need for such a handler. Furthermore,
2629*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2630this value.
2631
2632
Christian Heimese7a15bb2008-01-24 16:21:45 +00002633.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002634
2635 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2636 file is opened and used as the stream for logging. If *mode* is not specified,
2637 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002638 with that encoding. If *delay* is true, then file opening is deferred until the
2639 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002640
2641
Benjamin Petersone41251e2008-04-25 01:59:09 +00002642 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002643
Benjamin Petersone41251e2008-04-25 01:59:09 +00002644 Outputs the record to the file, but first checks to see if the file has
2645 changed. If it has, the existing stream is flushed and closed and the
2646 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002647
Vinay Sajipd31f3632010-06-29 15:31:15 +00002648.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002649
2650RotatingFileHandler
2651^^^^^^^^^^^^^^^^^^^
2652
2653The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2654module, supports rotation of disk log files.
2655
2656
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002657.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002658
2659 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2660 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002661 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2662 with that encoding. If *delay* is true, then file opening is deferred until the
2663 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002664
2665 You can use the *maxBytes* and *backupCount* values to allow the file to
2666 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2667 the file is closed and a new file is silently opened for output. Rollover occurs
2668 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2669 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2670 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2671 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2672 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2673 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2674 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2675 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2676 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2677
2678
Benjamin Petersone41251e2008-04-25 01:59:09 +00002679 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002680
Benjamin Petersone41251e2008-04-25 01:59:09 +00002681 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002682
2683
Benjamin Petersone41251e2008-04-25 01:59:09 +00002684 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002685
Benjamin Petersone41251e2008-04-25 01:59:09 +00002686 Outputs the record to the file, catering for rollover as described
2687 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002688
Vinay Sajipd31f3632010-06-29 15:31:15 +00002689.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002690
2691TimedRotatingFileHandler
2692^^^^^^^^^^^^^^^^^^^^^^^^
2693
2694The :class:`TimedRotatingFileHandler` class, located in the
2695:mod:`logging.handlers` module, supports rotation of disk log files at certain
2696timed intervals.
2697
2698
Vinay Sajipd31f3632010-06-29 15:31:15 +00002699.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002700
2701 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2702 specified file is opened and used as the stream for logging. On rotating it also
2703 sets the filename suffix. Rotating happens based on the product of *when* and
2704 *interval*.
2705
2706 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002707 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002708
Christian Heimesb558a2e2008-03-02 22:46:37 +00002709 +----------------+-----------------------+
2710 | Value | Type of interval |
2711 +================+=======================+
2712 | ``'S'`` | Seconds |
2713 +----------------+-----------------------+
2714 | ``'M'`` | Minutes |
2715 +----------------+-----------------------+
2716 | ``'H'`` | Hours |
2717 +----------------+-----------------------+
2718 | ``'D'`` | Days |
2719 +----------------+-----------------------+
2720 | ``'W'`` | Week day (0=Monday) |
2721 +----------------+-----------------------+
2722 | ``'midnight'`` | Roll over at midnight |
2723 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002724
Christian Heimesb558a2e2008-03-02 22:46:37 +00002725 The system will save old log files by appending extensions to the filename.
2726 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002727 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002728 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002729
2730 When computing the next rollover time for the first time (when the handler
2731 is created), the last modification time of an existing log file, or else
2732 the current time, is used to compute when the next rotation will occur.
2733
Georg Brandl0c77a822008-06-10 16:37:50 +00002734 If the *utc* argument is true, times in UTC will be used; otherwise
2735 local time is used.
2736
2737 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002738 will be kept, and if more would be created when rollover occurs, the oldest
2739 one is deleted. The deletion logic uses the interval to determine which
2740 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002741
Vinay Sajipd31f3632010-06-29 15:31:15 +00002742 If *delay* is true, then file opening is deferred until the first call to
2743 :meth:`emit`.
2744
Georg Brandl116aa622007-08-15 14:28:22 +00002745
Benjamin Petersone41251e2008-04-25 01:59:09 +00002746 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002747
Benjamin Petersone41251e2008-04-25 01:59:09 +00002748 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002749
2750
Benjamin Petersone41251e2008-04-25 01:59:09 +00002751 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002752
Benjamin Petersone41251e2008-04-25 01:59:09 +00002753 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002754
2755
Vinay Sajipd31f3632010-06-29 15:31:15 +00002756.. _socket-handler:
2757
Georg Brandl116aa622007-08-15 14:28:22 +00002758SocketHandler
2759^^^^^^^^^^^^^
2760
2761The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2762sends logging output to a network socket. The base class uses a TCP socket.
2763
2764
2765.. class:: SocketHandler(host, port)
2766
2767 Returns a new instance of the :class:`SocketHandler` class intended to
2768 communicate with a remote machine whose address is given by *host* and *port*.
2769
2770
Benjamin Petersone41251e2008-04-25 01:59:09 +00002771 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002772
Benjamin Petersone41251e2008-04-25 01:59:09 +00002773 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002774
2775
Benjamin Petersone41251e2008-04-25 01:59:09 +00002776 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002777
Benjamin Petersone41251e2008-04-25 01:59:09 +00002778 Pickles the record's attribute dictionary and writes it to the socket in
2779 binary format. If there is an error with the socket, silently drops the
2780 packet. If the connection was previously lost, re-establishes the
2781 connection. To unpickle the record at the receiving end into a
2782 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002783
2784
Benjamin Petersone41251e2008-04-25 01:59:09 +00002785 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002786
Benjamin Petersone41251e2008-04-25 01:59:09 +00002787 Handles an error which has occurred during :meth:`emit`. The most likely
2788 cause is a lost connection. Closes the socket so that we can retry on the
2789 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002790
2791
Benjamin Petersone41251e2008-04-25 01:59:09 +00002792 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002793
Benjamin Petersone41251e2008-04-25 01:59:09 +00002794 This is a factory method which allows subclasses to define the precise
2795 type of socket they want. The default implementation creates a TCP socket
2796 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002797
2798
Benjamin Petersone41251e2008-04-25 01:59:09 +00002799 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002800
Benjamin Petersone41251e2008-04-25 01:59:09 +00002801 Pickles the record's attribute dictionary in binary format with a length
2802 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002803
Vinay Sajipd31f3632010-06-29 15:31:15 +00002804 Note that pickles aren't completely secure. If you are concerned about
2805 security, you may want to override this method to implement a more secure
2806 mechanism. For example, you can sign pickles using HMAC and then verify
2807 them on the receiving end, or alternatively you can disable unpickling of
2808 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002809
Benjamin Petersone41251e2008-04-25 01:59:09 +00002810 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002811
Benjamin Petersone41251e2008-04-25 01:59:09 +00002812 Send a pickled string *packet* to the socket. This function allows for
2813 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002814
2815
Vinay Sajipd31f3632010-06-29 15:31:15 +00002816.. _datagram-handler:
2817
Georg Brandl116aa622007-08-15 14:28:22 +00002818DatagramHandler
2819^^^^^^^^^^^^^^^
2820
2821The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2822module, inherits from :class:`SocketHandler` to support sending logging messages
2823over UDP sockets.
2824
2825
2826.. class:: DatagramHandler(host, port)
2827
2828 Returns a new instance of the :class:`DatagramHandler` class intended to
2829 communicate with a remote machine whose address is given by *host* and *port*.
2830
2831
Benjamin Petersone41251e2008-04-25 01:59:09 +00002832 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002833
Benjamin Petersone41251e2008-04-25 01:59:09 +00002834 Pickles the record's attribute dictionary and writes it to the socket in
2835 binary format. If there is an error with the socket, silently drops the
2836 packet. To unpickle the record at the receiving end into a
2837 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002838
2839
Benjamin Petersone41251e2008-04-25 01:59:09 +00002840 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002841
Benjamin Petersone41251e2008-04-25 01:59:09 +00002842 The factory method of :class:`SocketHandler` is here overridden to create
2843 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002844
2845
Benjamin Petersone41251e2008-04-25 01:59:09 +00002846 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002847
Benjamin Petersone41251e2008-04-25 01:59:09 +00002848 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002849
2850
Vinay Sajipd31f3632010-06-29 15:31:15 +00002851.. _syslog-handler:
2852
Georg Brandl116aa622007-08-15 14:28:22 +00002853SysLogHandler
2854^^^^^^^^^^^^^
2855
2856The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2857supports sending logging messages to a remote or local Unix syslog.
2858
2859
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002860.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002861
2862 Returns a new instance of the :class:`SysLogHandler` class intended to
2863 communicate with a remote Unix machine whose address is given by *address* in
2864 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002865 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002866 alternative to providing a ``(host, port)`` tuple is providing an address as a
2867 string, for example "/dev/log". In this case, a Unix domain socket is used to
2868 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002869 :const:`LOG_USER` is used. The type of socket opened depends on the
2870 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2871 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2872 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2873
Vinay Sajip972412d2010-09-23 20:31:24 +00002874 Note that if your server is not listening on UDP port 514,
2875 :class:`SysLogHandler` may appear not to work. In that case, check what
2876 address you should be using for a domain socket - it's system dependent.
2877 For example, on Linux it's usually "/dev/log" but on OS/X it's
2878 "/var/run/syslog". You'll need to check your platform and use the
2879 appropriate address (you may need to do this check at runtime if your
2880 application needs to run on several platforms). On Windows, you pretty
2881 much have to use the UDP option.
2882
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002883 .. versionchanged:: 3.2
2884 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002885
2886
Benjamin Petersone41251e2008-04-25 01:59:09 +00002887 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002888
Benjamin Petersone41251e2008-04-25 01:59:09 +00002889 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002890
2891
Benjamin Petersone41251e2008-04-25 01:59:09 +00002892 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002893
Benjamin Petersone41251e2008-04-25 01:59:09 +00002894 The record is formatted, and then sent to the syslog server. If exception
2895 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002896
2897
Benjamin Petersone41251e2008-04-25 01:59:09 +00002898 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002899
Benjamin Petersone41251e2008-04-25 01:59:09 +00002900 Encodes the facility and priority into an integer. You can pass in strings
2901 or integers - if strings are passed, internal mapping dictionaries are
2902 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002903
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002904 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2905 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002906
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002907 **Priorities**
2908
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002909 +--------------------------+---------------+
2910 | Name (string) | Symbolic value|
2911 +==========================+===============+
2912 | ``alert`` | LOG_ALERT |
2913 +--------------------------+---------------+
2914 | ``crit`` or ``critical`` | LOG_CRIT |
2915 +--------------------------+---------------+
2916 | ``debug`` | LOG_DEBUG |
2917 +--------------------------+---------------+
2918 | ``emerg`` or ``panic`` | LOG_EMERG |
2919 +--------------------------+---------------+
2920 | ``err`` or ``error`` | LOG_ERR |
2921 +--------------------------+---------------+
2922 | ``info`` | LOG_INFO |
2923 +--------------------------+---------------+
2924 | ``notice`` | LOG_NOTICE |
2925 +--------------------------+---------------+
2926 | ``warn`` or ``warning`` | LOG_WARNING |
2927 +--------------------------+---------------+
2928
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002929 **Facilities**
2930
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002931 +---------------+---------------+
2932 | Name (string) | Symbolic value|
2933 +===============+===============+
2934 | ``auth`` | LOG_AUTH |
2935 +---------------+---------------+
2936 | ``authpriv`` | LOG_AUTHPRIV |
2937 +---------------+---------------+
2938 | ``cron`` | LOG_CRON |
2939 +---------------+---------------+
2940 | ``daemon`` | LOG_DAEMON |
2941 +---------------+---------------+
2942 | ``ftp`` | LOG_FTP |
2943 +---------------+---------------+
2944 | ``kern`` | LOG_KERN |
2945 +---------------+---------------+
2946 | ``lpr`` | LOG_LPR |
2947 +---------------+---------------+
2948 | ``mail`` | LOG_MAIL |
2949 +---------------+---------------+
2950 | ``news`` | LOG_NEWS |
2951 +---------------+---------------+
2952 | ``syslog`` | LOG_SYSLOG |
2953 +---------------+---------------+
2954 | ``user`` | LOG_USER |
2955 +---------------+---------------+
2956 | ``uucp`` | LOG_UUCP |
2957 +---------------+---------------+
2958 | ``local0`` | LOG_LOCAL0 |
2959 +---------------+---------------+
2960 | ``local1`` | LOG_LOCAL1 |
2961 +---------------+---------------+
2962 | ``local2`` | LOG_LOCAL2 |
2963 +---------------+---------------+
2964 | ``local3`` | LOG_LOCAL3 |
2965 +---------------+---------------+
2966 | ``local4`` | LOG_LOCAL4 |
2967 +---------------+---------------+
2968 | ``local5`` | LOG_LOCAL5 |
2969 +---------------+---------------+
2970 | ``local6`` | LOG_LOCAL6 |
2971 +---------------+---------------+
2972 | ``local7`` | LOG_LOCAL7 |
2973 +---------------+---------------+
2974
2975 .. method:: mapPriority(levelname)
2976
2977 Maps a logging level name to a syslog priority name.
2978 You may need to override this if you are using custom levels, or
2979 if the default algorithm is not suitable for your needs. The
2980 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
2981 ``CRITICAL`` to the equivalent syslog names, and all other level
2982 names to "warning".
2983
2984.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002985
2986NTEventLogHandler
2987^^^^^^^^^^^^^^^^^
2988
2989The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
2990module, supports sending logging messages to a local Windows NT, Windows 2000 or
2991Windows XP event log. Before you can use it, you need Mark Hammond's Win32
2992extensions for Python installed.
2993
2994
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002995.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00002996
2997 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
2998 used to define the application name as it appears in the event log. An
2999 appropriate registry entry is created using this name. The *dllname* should give
3000 the fully qualified pathname of a .dll or .exe which contains message
3001 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
3002 - this is installed with the Win32 extensions and contains some basic
3003 placeholder message definitions. Note that use of these placeholders will make
3004 your event logs big, as the entire message source is held in the log. If you
3005 want slimmer logs, you have to pass in the name of your own .dll or .exe which
3006 contains the message definitions you want to use in the event log). The
3007 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
3008 defaults to ``'Application'``.
3009
3010
Benjamin Petersone41251e2008-04-25 01:59:09 +00003011 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003012
Benjamin Petersone41251e2008-04-25 01:59:09 +00003013 At this point, you can remove the application name from the registry as a
3014 source of event log entries. However, if you do this, you will not be able
3015 to see the events as you intended in the Event Log Viewer - it needs to be
3016 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003017 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00003018
3019
Benjamin Petersone41251e2008-04-25 01:59:09 +00003020 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003021
Benjamin Petersone41251e2008-04-25 01:59:09 +00003022 Determines the message ID, event category and event type, and then logs
3023 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00003024
3025
Benjamin Petersone41251e2008-04-25 01:59:09 +00003026 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003027
Benjamin Petersone41251e2008-04-25 01:59:09 +00003028 Returns the event category for the record. Override this if you want to
3029 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00003030
3031
Benjamin Petersone41251e2008-04-25 01:59:09 +00003032 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003033
Benjamin Petersone41251e2008-04-25 01:59:09 +00003034 Returns the event type for the record. Override this if you want to
3035 specify your own types. This version does a mapping using the handler's
3036 typemap attribute, which is set up in :meth:`__init__` to a dictionary
3037 which contains mappings for :const:`DEBUG`, :const:`INFO`,
3038 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
3039 your own levels, you will either need to override this method or place a
3040 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00003041
3042
Benjamin Petersone41251e2008-04-25 01:59:09 +00003043 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003044
Benjamin Petersone41251e2008-04-25 01:59:09 +00003045 Returns the message ID for the record. If you are using your own messages,
3046 you could do this by having the *msg* passed to the logger being an ID
3047 rather than a format string. Then, in here, you could use a dictionary
3048 lookup to get the message ID. This version returns 1, which is the base
3049 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00003050
Vinay Sajipd31f3632010-06-29 15:31:15 +00003051.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003052
3053SMTPHandler
3054^^^^^^^^^^^
3055
3056The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
3057supports sending logging messages to an email address via SMTP.
3058
3059
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003060.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003061
3062 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3063 initialized with the from and to addresses and subject line of the email. The
3064 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3065 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3066 the standard SMTP port is used. If your SMTP server requires authentication, you
3067 can specify a (username, password) tuple for the *credentials* argument.
3068
Georg Brandl116aa622007-08-15 14:28:22 +00003069
Benjamin Petersone41251e2008-04-25 01:59:09 +00003070 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003071
Benjamin Petersone41251e2008-04-25 01:59:09 +00003072 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003073
3074
Benjamin Petersone41251e2008-04-25 01:59:09 +00003075 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003076
Benjamin Petersone41251e2008-04-25 01:59:09 +00003077 If you want to specify a subject line which is record-dependent, override
3078 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003079
Vinay Sajipd31f3632010-06-29 15:31:15 +00003080.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003081
3082MemoryHandler
3083^^^^^^^^^^^^^
3084
3085The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3086supports buffering of logging records in memory, periodically flushing them to a
3087:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3088event of a certain severity or greater is seen.
3089
3090:class:`MemoryHandler` is a subclass of the more general
3091:class:`BufferingHandler`, which is an abstract class. This buffers logging
3092records in memory. Whenever each record is added to the buffer, a check is made
3093by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3094should, then :meth:`flush` is expected to do the needful.
3095
3096
3097.. class:: BufferingHandler(capacity)
3098
3099 Initializes the handler with a buffer of the specified capacity.
3100
3101
Benjamin Petersone41251e2008-04-25 01:59:09 +00003102 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003103
Benjamin Petersone41251e2008-04-25 01:59:09 +00003104 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3105 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003106
3107
Benjamin Petersone41251e2008-04-25 01:59:09 +00003108 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003109
Benjamin Petersone41251e2008-04-25 01:59:09 +00003110 You can override this to implement custom flushing behavior. This version
3111 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003112
3113
Benjamin Petersone41251e2008-04-25 01:59:09 +00003114 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003115
Benjamin Petersone41251e2008-04-25 01:59:09 +00003116 Returns true if the buffer is up to capacity. This method can be
3117 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003118
3119
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003120.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003121
3122 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3123 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3124 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3125 set using :meth:`setTarget` before this handler does anything useful.
3126
3127
Benjamin Petersone41251e2008-04-25 01:59:09 +00003128 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003129
Benjamin Petersone41251e2008-04-25 01:59:09 +00003130 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3131 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003132
3133
Benjamin Petersone41251e2008-04-25 01:59:09 +00003134 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003135
Benjamin Petersone41251e2008-04-25 01:59:09 +00003136 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003137 records to the target, if there is one. The buffer is also cleared when
3138 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003139
3140
Benjamin Petersone41251e2008-04-25 01:59:09 +00003141 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003142
Benjamin Petersone41251e2008-04-25 01:59:09 +00003143 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003144
3145
Benjamin Petersone41251e2008-04-25 01:59:09 +00003146 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003147
Benjamin Petersone41251e2008-04-25 01:59:09 +00003148 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003149
3150
Vinay Sajipd31f3632010-06-29 15:31:15 +00003151.. _http-handler:
3152
Georg Brandl116aa622007-08-15 14:28:22 +00003153HTTPHandler
3154^^^^^^^^^^^
3155
3156The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3157supports sending logging messages to a Web server, using either ``GET`` or
3158``POST`` semantics.
3159
3160
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003161.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003162
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003163 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3164 of the form ``host:port``, should you need to use a specific port number.
3165 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3166 connection will be used. If *credentials* is specified, it should be a
3167 2-tuple consisting of userid and password, which will be placed in an HTTP
3168 'Authorization' header using Basic authentication. If you specify
3169 credentials, you should also specify secure=True so that your userid and
3170 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003171
3172
Benjamin Petersone41251e2008-04-25 01:59:09 +00003173 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003174
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003175 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003176
3177
Vinay Sajip121a1c42010-09-08 10:46:15 +00003178.. _queue-handler:
3179
3180
3181QueueHandler
3182^^^^^^^^^^^^
3183
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003184.. versionadded:: 3.2
3185
Vinay Sajip121a1c42010-09-08 10:46:15 +00003186The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3187supports sending logging messages to a queue, such as those implemented in the
3188:mod:`queue` or :mod:`multiprocessing` modules.
3189
Vinay Sajip0637d492010-09-23 08:15:54 +00003190Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3191to let handlers do their work on a separate thread from the one which does the
3192logging. This is important in Web applications and also other service
3193applications where threads servicing clients need to respond as quickly as
3194possible, while any potentially slow operations (such as sending an email via
3195:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003196
3197.. class:: QueueHandler(queue)
3198
3199 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003200 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003201 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003202 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003203
3204
3205 .. method:: emit(record)
3206
Vinay Sajip0258ce82010-09-22 20:34:53 +00003207 Enqueues the result of preparing the LogRecord.
3208
3209 .. method:: prepare(record)
3210
3211 Prepares a record for queuing. The object returned by this
3212 method is enqueued.
3213
3214 The base implementation formats the record to merge the message
3215 and arguments, and removes unpickleable items from the record
3216 in-place.
3217
3218 You might want to override this method if you want to convert
3219 the record to a dict or JSON string, or send a modified copy
3220 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003221
3222 .. method:: enqueue(record)
3223
3224 Enqueues the record on the queue using ``put_nowait()``; you may
3225 want to override this if you want to use blocking behaviour, or a
3226 timeout, or a customised queue implementation.
3227
3228
Vinay Sajip121a1c42010-09-08 10:46:15 +00003229
Vinay Sajip0637d492010-09-23 08:15:54 +00003230.. queue-listener:
3231
3232QueueListener
3233^^^^^^^^^^^^^
3234
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003235.. versionadded:: 3.2
3236
Vinay Sajip0637d492010-09-23 08:15:54 +00003237The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3238module, supports receiving logging messages from a queue, such as those
3239implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3240messages are received from a queue in an internal thread and passed, on
3241the same thread, to one or more handlers for processing.
3242
3243Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3244to let handlers do their work on a separate thread from the one which does the
3245logging. This is important in Web applications and also other service
3246applications where threads servicing clients need to respond as quickly as
3247possible, while any potentially slow operations (such as sending an email via
3248:class:`SMTPHandler`) are done on a separate thread.
3249
3250.. class:: QueueListener(queue, *handlers)
3251
3252 Returns a new instance of the :class:`QueueListener` class. The instance is
3253 initialized with the queue to send messages to and a list of handlers which
3254 will handle entries placed on the queue. The queue can be any queue-
3255 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3256 to know how to get messages from it.
3257
3258 .. method:: dequeue(block)
3259
3260 Dequeues a record and return it, optionally blocking.
3261
3262 The base implementation uses ``get()``. You may want to override this
3263 method if you want to use timeouts or work with custom queue
3264 implementations.
3265
3266 .. method:: prepare(record)
3267
3268 Prepare a record for handling.
3269
3270 This implementation just returns the passed-in record. You may want to
3271 override this method if you need to do any custom marshalling or
3272 manipulation of the record before passing it to the handlers.
3273
3274 .. method:: handle(record)
3275
3276 Handle a record.
3277
3278 This just loops through the handlers offering them the record
3279 to handle. The actual object passed to the handlers is that which
3280 is returned from :meth:`prepare`.
3281
3282 .. method:: start()
3283
3284 Starts the listener.
3285
3286 This starts up a background thread to monitor the queue for
3287 LogRecords to process.
3288
3289 .. method:: stop()
3290
3291 Stops the listener.
3292
3293 This asks the thread to terminate, and then waits for it to do so.
3294 Note that if you don't call this before your application exits, there
3295 may be some records still left on the queue, which won't be processed.
3296
Vinay Sajip0637d492010-09-23 08:15:54 +00003297
Vinay Sajip63891ed2010-09-13 20:02:39 +00003298.. _zeromq-handlers:
3299
Vinay Sajip0637d492010-09-23 08:15:54 +00003300Subclassing QueueHandler
3301^^^^^^^^^^^^^^^^^^^^^^^^
3302
Vinay Sajip63891ed2010-09-13 20:02:39 +00003303You can use a :class:`QueueHandler` subclass to send messages to other kinds
3304of queues, for example a ZeroMQ "publish" socket. In the example below,the
3305socket is created separately and passed to the handler (as its 'queue')::
3306
3307 import zmq # using pyzmq, the Python binding for ZeroMQ
3308 import json # for serializing records portably
3309
3310 ctx = zmq.Context()
3311 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3312 sock.bind('tcp://*:5556') # or wherever
3313
3314 class ZeroMQSocketHandler(QueueHandler):
3315 def enqueue(self, record):
3316 data = json.dumps(record.__dict__)
3317 self.queue.send(data)
3318
Vinay Sajip0055c422010-09-14 09:42:39 +00003319 handler = ZeroMQSocketHandler(sock)
3320
3321
Vinay Sajip63891ed2010-09-13 20:02:39 +00003322Of course there are other ways of organizing this, for example passing in the
3323data needed by the handler to create the socket::
3324
3325 class ZeroMQSocketHandler(QueueHandler):
3326 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3327 self.ctx = ctx or zmq.Context()
3328 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003329 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003330 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003331
3332 def enqueue(self, record):
3333 data = json.dumps(record.__dict__)
3334 self.queue.send(data)
3335
Vinay Sajipde726922010-09-14 06:59:24 +00003336 def close(self):
3337 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003338
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003339
Vinay Sajip0637d492010-09-23 08:15:54 +00003340Subclassing QueueListener
3341^^^^^^^^^^^^^^^^^^^^^^^^^
3342
3343You can also subclass :class:`QueueListener` to get messages from other kinds
3344of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
3345
3346 class ZeroMQSocketListener(QueueListener):
3347 def __init__(self, uri, *handlers, **kwargs):
3348 self.ctx = kwargs.get('ctx') or zmq.Context()
3349 socket = zmq.Socket(self.ctx, zmq.SUB)
3350 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3351 socket.connect(uri)
3352
3353 def dequeue(self):
3354 msg = self.queue.recv()
3355 return logging.makeLogRecord(json.loads(msg))
3356
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003357
Christian Heimes8b0facf2007-12-04 19:30:01 +00003358.. _formatter-objects:
3359
Georg Brandl116aa622007-08-15 14:28:22 +00003360Formatter Objects
3361-----------------
3362
Benjamin Peterson75edad02009-01-01 15:05:06 +00003363.. currentmodule:: logging
3364
Georg Brandl116aa622007-08-15 14:28:22 +00003365:class:`Formatter`\ s have the following attributes and methods. They are
3366responsible for converting a :class:`LogRecord` to (usually) a string which can
3367be interpreted by either a human or an external system. The base
3368:class:`Formatter` allows a formatting string to be specified. If none is
3369supplied, the default value of ``'%(message)s'`` is used.
3370
3371A Formatter can be initialized with a format string which makes use of knowledge
3372of the :class:`LogRecord` attributes - such as the default value mentioned above
3373making use of the fact that the user's message and arguments are pre-formatted
3374into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003375standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003376for more information on string formatting.
3377
3378Currently, the useful mapping keys in a :class:`LogRecord` are:
3379
3380+-------------------------+-----------------------------------------------+
3381| Format | Description |
3382+=========================+===============================================+
3383| ``%(name)s`` | Name of the logger (logging channel). |
3384+-------------------------+-----------------------------------------------+
3385| ``%(levelno)s`` | Numeric logging level for the message |
3386| | (:const:`DEBUG`, :const:`INFO`, |
3387| | :const:`WARNING`, :const:`ERROR`, |
3388| | :const:`CRITICAL`). |
3389+-------------------------+-----------------------------------------------+
3390| ``%(levelname)s`` | Text logging level for the message |
3391| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3392| | ``'ERROR'``, ``'CRITICAL'``). |
3393+-------------------------+-----------------------------------------------+
3394| ``%(pathname)s`` | Full pathname of the source file where the |
3395| | logging call was issued (if available). |
3396+-------------------------+-----------------------------------------------+
3397| ``%(filename)s`` | Filename portion of pathname. |
3398+-------------------------+-----------------------------------------------+
3399| ``%(module)s`` | Module (name portion of filename). |
3400+-------------------------+-----------------------------------------------+
3401| ``%(funcName)s`` | Name of function containing the logging call. |
3402+-------------------------+-----------------------------------------------+
3403| ``%(lineno)d`` | Source line number where the logging call was |
3404| | issued (if available). |
3405+-------------------------+-----------------------------------------------+
3406| ``%(created)f`` | Time when the :class:`LogRecord` was created |
3407| | (as returned by :func:`time.time`). |
3408+-------------------------+-----------------------------------------------+
3409| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3410| | created, relative to the time the logging |
3411| | module was loaded. |
3412+-------------------------+-----------------------------------------------+
3413| ``%(asctime)s`` | Human-readable time when the |
3414| | :class:`LogRecord` was created. By default |
3415| | this is of the form "2003-07-08 16:49:45,896" |
3416| | (the numbers after the comma are millisecond |
3417| | portion of the time). |
3418+-------------------------+-----------------------------------------------+
3419| ``%(msecs)d`` | Millisecond portion of the time when the |
3420| | :class:`LogRecord` was created. |
3421+-------------------------+-----------------------------------------------+
3422| ``%(thread)d`` | Thread ID (if available). |
3423+-------------------------+-----------------------------------------------+
3424| ``%(threadName)s`` | Thread name (if available). |
3425+-------------------------+-----------------------------------------------+
3426| ``%(process)d`` | Process ID (if available). |
3427+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003428| ``%(processName)s`` | Process name (if available). |
3429+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003430| ``%(message)s`` | The logged message, computed as ``msg % |
3431| | args``. |
3432+-------------------------+-----------------------------------------------+
3433
Georg Brandl116aa622007-08-15 14:28:22 +00003434
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003435.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003436
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003437 Returns a new instance of the :class:`Formatter` class. The instance is
3438 initialized with a format string for the message as a whole, as well as a
3439 format string for the date/time portion of a message. If no *fmt* is
3440 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3441 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003442
Benjamin Petersone41251e2008-04-25 01:59:09 +00003443 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003444
Benjamin Petersone41251e2008-04-25 01:59:09 +00003445 The record's attribute dictionary is used as the operand to a string
3446 formatting operation. Returns the resulting string. Before formatting the
3447 dictionary, a couple of preparatory steps are carried out. The *message*
3448 attribute of the record is computed using *msg* % *args*. If the
3449 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3450 to format the event time. If there is exception information, it is
3451 formatted using :meth:`formatException` and appended to the message. Note
3452 that the formatted exception information is cached in attribute
3453 *exc_text*. This is useful because the exception information can be
3454 pickled and sent across the wire, but you should be careful if you have
3455 more than one :class:`Formatter` subclass which customizes the formatting
3456 of exception information. In this case, you will have to clear the cached
3457 value after a formatter has done its formatting, so that the next
3458 formatter to handle the event doesn't use the cached value but
3459 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003460
Vinay Sajip8593ae62010-11-14 21:33:04 +00003461 If stack information is available, it's appended after the exception
3462 information, using :meth:`formatStack` to transform it if necessary.
3463
Georg Brandl116aa622007-08-15 14:28:22 +00003464
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003465 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003466
Benjamin Petersone41251e2008-04-25 01:59:09 +00003467 This method should be called from :meth:`format` by a formatter which
3468 wants to make use of a formatted time. This method can be overridden in
3469 formatters to provide for any specific requirement, but the basic behavior
3470 is as follows: if *datefmt* (a string) is specified, it is used with
3471 :func:`time.strftime` to format the creation time of the
3472 record. Otherwise, the ISO8601 format is used. The resulting string is
3473 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003474
3475
Benjamin Petersone41251e2008-04-25 01:59:09 +00003476 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003477
Benjamin Petersone41251e2008-04-25 01:59:09 +00003478 Formats the specified exception information (a standard exception tuple as
3479 returned by :func:`sys.exc_info`) as a string. This default implementation
3480 just uses :func:`traceback.print_exception`. The resulting string is
3481 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003482
Vinay Sajip8593ae62010-11-14 21:33:04 +00003483 .. method:: formatStack(stack_info)
3484
3485 Formats the specified stack information (a string as returned by
3486 :func:`traceback.print_stack`, but with the last newline removed) as a
3487 string. This default implementation just returns the input value.
3488
Vinay Sajipd31f3632010-06-29 15:31:15 +00003489.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003490
3491Filter Objects
3492--------------
3493
Georg Brandl5c66bca2010-10-29 05:36:28 +00003494``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003495filtering than is provided by levels. The base filter class only allows events
3496which are below a certain point in the logger hierarchy. For example, a filter
3497initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3498"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3499empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003500
3501
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003502.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003503
3504 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3505 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003506 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003507
3508
Benjamin Petersone41251e2008-04-25 01:59:09 +00003509 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003510
Benjamin Petersone41251e2008-04-25 01:59:09 +00003511 Is the specified record to be logged? Returns zero for no, nonzero for
3512 yes. If deemed appropriate, the record may be modified in-place by this
3513 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003514
Vinay Sajip81010212010-08-19 19:17:41 +00003515Note that filters attached to handlers are consulted whenever an event is
3516emitted by the handler, whereas filters attached to loggers are consulted
3517whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3518etc.) This means that events which have been generated by descendant loggers
3519will not be filtered by a logger's filter setting, unless the filter has also
3520been applied to those descendant loggers.
3521
Vinay Sajip22246fd2010-10-20 11:40:02 +00003522You don't actually need to subclass ``Filter``: you can pass any instance
3523which has a ``filter`` method with the same semantics.
3524
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003525.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003526 You don't need to create specialized ``Filter`` classes, or use other
3527 classes with a ``filter`` method: you can use a function (or other
3528 callable) as a filter. The filtering logic will check to see if the filter
3529 object has a ``filter`` attribute: if it does, it's assumed to be a
3530 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3531 assumed to be a callable and called with the record as the single
3532 parameter. The returned value should conform to that returned by
3533 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003534
Vinay Sajipac007992010-09-17 12:45:26 +00003535Other uses for filters
3536^^^^^^^^^^^^^^^^^^^^^^
3537
3538Although filters are used primarily to filter records based on more
3539sophisticated criteria than levels, they get to see every record which is
3540processed by the handler or logger they're attached to: this can be useful if
3541you want to do things like counting how many records were processed by a
3542particular logger or handler, or adding, changing or removing attributes in
3543the LogRecord being processed. Obviously changing the LogRecord needs to be
3544done with some care, but it does allow the injection of contextual information
3545into logs (see :ref:`filters-contextual`).
3546
Vinay Sajipd31f3632010-06-29 15:31:15 +00003547.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003548
3549LogRecord Objects
3550-----------------
3551
Vinay Sajip4039aff2010-09-11 10:25:28 +00003552:class:`LogRecord` instances are created automatically by the :class:`Logger`
3553every time something is logged, and can be created manually via
3554:func:`makeLogRecord` (for example, from a pickled event received over the
3555wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003556
3557
Vinay Sajipa18b9592010-12-12 13:20:55 +00003558.. class:: LogRecord(name, levelno, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003559
Vinay Sajip4039aff2010-09-11 10:25:28 +00003560 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003561
Vinay Sajip4039aff2010-09-11 10:25:28 +00003562 The primary information is passed in :attr:`msg` and :attr:`args`, which
3563 are combined using ``msg % args`` to create the :attr:`message` field of the
3564 record.
3565
3566 .. attribute:: args
3567
3568 Tuple of arguments to be used in formatting :attr:`msg`.
3569
3570 .. attribute:: exc_info
3571
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003572 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003573 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003574
3575 .. attribute:: func
3576
3577 Name of the function of origin (i.e. in which the logging call was made).
3578
3579 .. attribute:: lineno
3580
3581 Line number in the source file of origin.
3582
Vinay Sajipa18b9592010-12-12 13:20:55 +00003583 .. attribute:: levelno
Vinay Sajip4039aff2010-09-11 10:25:28 +00003584
3585 Numeric logging level.
3586
3587 .. attribute:: message
3588
3589 Bound to the result of :meth:`getMessage` when
3590 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3591
3592 .. attribute:: msg
3593
3594 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3595 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3596
3597 .. attribute:: name
3598
3599 Name of the logger that emitted the record.
3600
3601 .. attribute:: pathname
3602
3603 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003604
Vinay Sajip8593ae62010-11-14 21:33:04 +00003605 .. attribute:: stack_info
3606
3607 Stack frame information (where available) from the bottom of the stack
3608 in the current thread, up to and including the stack frame of the
3609 logging call which resulted in the creation of this record.
3610
Benjamin Petersone41251e2008-04-25 01:59:09 +00003611 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003612
Benjamin Petersone41251e2008-04-25 01:59:09 +00003613 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003614 user-supplied arguments with the message. If the user-supplied message
3615 argument to the logging call is not a string, :func:`str` is called on it to
3616 convert it to a string. This allows use of user-defined classes as
3617 messages, whose ``__str__`` method can return the actual format string to
3618 be used.
3619
Vinay Sajip61561522010-12-03 11:50:38 +00003620 .. versionchanged:: 3.2
3621 The creation of a ``LogRecord`` has been made more configurable by
3622 providing a factory which is used to create the record. The factory can be
3623 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3624 (see this for the factory's signature).
3625
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003626 This functionality can be used to inject your own values into a
3627 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003628
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003629 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003630
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003631 def record_factory(*args, **kwargs):
3632 record = old_factory(*args, **kwargs)
3633 record.custom_attribute = 0xdecafbad
3634 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003635
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003636 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003637
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003638 With this pattern, multiple factories could be chained, and as long
3639 as they don't overwrite each other's attributes or unintentionally
3640 overwrite the standard attributes listed above, there should be no
3641 surprises.
3642
Vinay Sajip61561522010-12-03 11:50:38 +00003643
Vinay Sajipd31f3632010-06-29 15:31:15 +00003644.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003645
Christian Heimes04c420f2008-01-18 18:40:46 +00003646LoggerAdapter Objects
3647---------------------
3648
Christian Heimes04c420f2008-01-18 18:40:46 +00003649:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003650information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003651:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003652
Christian Heimes04c420f2008-01-18 18:40:46 +00003653
3654.. class:: LoggerAdapter(logger, extra)
3655
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003656 Returns an instance of :class:`LoggerAdapter` initialized with an
3657 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003658
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003659 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003660
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003661 Modifies the message and/or keyword arguments passed to a logging call in
3662 order to insert contextual information. This implementation takes the object
3663 passed as *extra* to the constructor and adds it to *kwargs* using key
3664 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3665 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003666
Vinay Sajipc84f0162010-09-21 11:25:39 +00003667In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003668methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003669:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3670:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3671:meth:`hasHandlers`. These methods have the same signatures as their
3672counterparts in :class:`Logger`, so you can use the two types of instances
3673interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003674
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003675.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003676 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3677 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3678 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003679
Georg Brandl116aa622007-08-15 14:28:22 +00003680
3681Thread Safety
3682-------------
3683
3684The logging module is intended to be thread-safe without any special work
3685needing to be done by its clients. It achieves this though using threading
3686locks; there is one lock to serialize access to the module's shared data, and
3687each handler also creates a lock to serialize access to its underlying I/O.
3688
Benjamin Petersond23f8222009-04-05 19:13:16 +00003689If you are implementing asynchronous signal handlers using the :mod:`signal`
3690module, you may not be able to use logging from within such handlers. This is
3691because lock implementations in the :mod:`threading` module are not always
3692re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003693
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003694
3695Integration with the warnings module
3696------------------------------------
3697
3698The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3699with the :mod:`warnings` module.
3700
3701.. function:: captureWarnings(capture)
3702
3703 This function is used to turn the capture of warnings by logging on and
3704 off.
3705
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003706 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3707 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003708 formatted using :func:`warnings.formatwarning` and the resulting string
3709 logged to a logger named "py.warnings" with a severity of `WARNING`.
3710
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003711 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003712 will stop, and warnings will be redirected to their original destinations
3713 (i.e. those in effect before `captureWarnings(True)` was called).
3714
3715
Georg Brandl116aa622007-08-15 14:28:22 +00003716Configuration
3717-------------
3718
3719
3720.. _logging-config-api:
3721
3722Configuration functions
3723^^^^^^^^^^^^^^^^^^^^^^^
3724
Georg Brandl116aa622007-08-15 14:28:22 +00003725The following functions configure the logging module. They are located in the
3726:mod:`logging.config` module. Their use is optional --- you can configure the
3727logging module using these functions or by making calls to the main API (defined
3728in :mod:`logging` itself) and defining handlers which are declared either in
3729:mod:`logging` or :mod:`logging.handlers`.
3730
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003731.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003732
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003733 Takes the logging configuration from a dictionary. The contents of
3734 this dictionary are described in :ref:`logging-config-dictschema`
3735 below.
3736
3737 If an error is encountered during configuration, this function will
3738 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3739 or :exc:`ImportError` with a suitably descriptive message. The
3740 following is a (possibly incomplete) list of conditions which will
3741 raise an error:
3742
3743 * A ``level`` which is not a string or which is a string not
3744 corresponding to an actual logging level.
3745 * A ``propagate`` value which is not a boolean.
3746 * An id which does not have a corresponding destination.
3747 * A non-existent handler id found during an incremental call.
3748 * An invalid logger name.
3749 * Inability to resolve to an internal or external object.
3750
3751 Parsing is performed by the :class:`DictConfigurator` class, whose
3752 constructor is passed the dictionary used for configuration, and
3753 has a :meth:`configure` method. The :mod:`logging.config` module
3754 has a callable attribute :attr:`dictConfigClass`
3755 which is initially set to :class:`DictConfigurator`.
3756 You can replace the value of :attr:`dictConfigClass` with a
3757 suitable implementation of your own.
3758
3759 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3760 the specified dictionary, and then calls the :meth:`configure` method on
3761 the returned object to put the configuration into effect::
3762
3763 def dictConfig(config):
3764 dictConfigClass(config).configure()
3765
3766 For example, a subclass of :class:`DictConfigurator` could call
3767 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3768 set up custom prefixes which would be usable in the subsequent
3769 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3770 this new subclass, and then :func:`dictConfig` could be called exactly as
3771 in the default, uncustomized state.
3772
3773.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003774
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003775 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003776 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003777 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003778 configurations (if the developer provides a mechanism to present the choices
3779 and load the chosen configuration). Defaults to be passed to the ConfigParser
3780 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003781
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003782
3783.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003784
3785 Starts up a socket server on the specified port, and listens for new
3786 configurations. If no port is specified, the module's default
3787 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3788 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3789 :class:`Thread` instance on which you can call :meth:`start` to start the
3790 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003791 call :func:`stopListening`.
3792
3793 To send a configuration to the socket, read in the configuration file and
3794 send it to the socket as a string of bytes preceded by a four-byte length
3795 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003796
3797
3798.. function:: stopListening()
3799
Christian Heimes8b0facf2007-12-04 19:30:01 +00003800 Stops the listening server which was created with a call to :func:`listen`.
3801 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003802 :func:`listen`.
3803
3804
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003805.. _logging-config-dictschema:
3806
3807Configuration dictionary schema
3808^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3809
3810Describing a logging configuration requires listing the various
3811objects to create and the connections between them; for example, you
3812may create a handler named "console" and then say that the logger
3813named "startup" will send its messages to the "console" handler.
3814These objects aren't limited to those provided by the :mod:`logging`
3815module because you might write your own formatter or handler class.
3816The parameters to these classes may also need to include external
3817objects such as ``sys.stderr``. The syntax for describing these
3818objects and connections is defined in :ref:`logging-config-dict-connections`
3819below.
3820
3821Dictionary Schema Details
3822"""""""""""""""""""""""""
3823
3824The dictionary passed to :func:`dictConfig` must contain the following
3825keys:
3826
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003827* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003828 version. The only valid value at present is 1, but having this key
3829 allows the schema to evolve while still preserving backwards
3830 compatibility.
3831
3832All other keys are optional, but if present they will be interpreted
3833as described below. In all cases below where a 'configuring dict' is
3834mentioned, it will be checked for the special ``'()'`` key to see if a
3835custom instantiation is required. If so, the mechanism described in
3836:ref:`logging-config-dict-userdef` below is used to create an instance;
3837otherwise, the context is used to determine what to instantiate.
3838
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003839* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003840 key is a formatter id and each value is a dict describing how to
3841 configure the corresponding Formatter instance.
3842
3843 The configuring dict is searched for keys ``format`` and ``datefmt``
3844 (with defaults of ``None``) and these are used to construct a
3845 :class:`logging.Formatter` instance.
3846
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003847* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003848 is a filter id and each value is a dict describing how to configure
3849 the corresponding Filter instance.
3850
3851 The configuring dict is searched for the key ``name`` (defaulting to the
3852 empty string) and this is used to construct a :class:`logging.Filter`
3853 instance.
3854
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003855* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003856 key is a handler id and each value is a dict describing how to
3857 configure the corresponding Handler instance.
3858
3859 The configuring dict is searched for the following keys:
3860
3861 * ``class`` (mandatory). This is the fully qualified name of the
3862 handler class.
3863
3864 * ``level`` (optional). The level of the handler.
3865
3866 * ``formatter`` (optional). The id of the formatter for this
3867 handler.
3868
3869 * ``filters`` (optional). A list of ids of the filters for this
3870 handler.
3871
3872 All *other* keys are passed through as keyword arguments to the
3873 handler's constructor. For example, given the snippet::
3874
3875 handlers:
3876 console:
3877 class : logging.StreamHandler
3878 formatter: brief
3879 level : INFO
3880 filters: [allow_foo]
3881 stream : ext://sys.stdout
3882 file:
3883 class : logging.handlers.RotatingFileHandler
3884 formatter: precise
3885 filename: logconfig.log
3886 maxBytes: 1024
3887 backupCount: 3
3888
3889 the handler with id ``console`` is instantiated as a
3890 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3891 stream. The handler with id ``file`` is instantiated as a
3892 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3893 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3894
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003895* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003896 is a logger name and each value is a dict describing how to
3897 configure the corresponding Logger instance.
3898
3899 The configuring dict is searched for the following keys:
3900
3901 * ``level`` (optional). The level of the logger.
3902
3903 * ``propagate`` (optional). The propagation setting of the logger.
3904
3905 * ``filters`` (optional). A list of ids of the filters for this
3906 logger.
3907
3908 * ``handlers`` (optional). A list of ids of the handlers for this
3909 logger.
3910
3911 The specified loggers will be configured according to the level,
3912 propagation, filters and handlers specified.
3913
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003914* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003915 Processing of the configuration will be as for any logger, except
3916 that the ``propagate`` setting will not be applicable.
3917
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003918* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003919 incremental to the existing configuration. This value defaults to
3920 ``False``, which means that the specified configuration replaces the
3921 existing configuration with the same semantics as used by the
3922 existing :func:`fileConfig` API.
3923
3924 If the specified value is ``True``, the configuration is processed
3925 as described in the section on :ref:`logging-config-dict-incremental`.
3926
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003927* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003928 disabled. This setting mirrors the parameter of the same name in
3929 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003930 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003931
3932.. _logging-config-dict-incremental:
3933
3934Incremental Configuration
3935"""""""""""""""""""""""""
3936
3937It is difficult to provide complete flexibility for incremental
3938configuration. For example, because objects such as filters
3939and formatters are anonymous, once a configuration is set up, it is
3940not possible to refer to such anonymous objects when augmenting a
3941configuration.
3942
3943Furthermore, there is not a compelling case for arbitrarily altering
3944the object graph of loggers, handlers, filters, formatters at
3945run-time, once a configuration is set up; the verbosity of loggers and
3946handlers can be controlled just by setting levels (and, in the case of
3947loggers, propagation flags). Changing the object graph arbitrarily in
3948a safe way is problematic in a multi-threaded environment; while not
3949impossible, the benefits are not worth the complexity it adds to the
3950implementation.
3951
3952Thus, when the ``incremental`` key of a configuration dict is present
3953and is ``True``, the system will completely ignore any ``formatters`` and
3954``filters`` entries, and process only the ``level``
3955settings in the ``handlers`` entries, and the ``level`` and
3956``propagate`` settings in the ``loggers`` and ``root`` entries.
3957
3958Using a value in the configuration dict lets configurations to be sent
3959over the wire as pickled dicts to a socket listener. Thus, the logging
3960verbosity of a long-running application can be altered over time with
3961no need to stop and restart the application.
3962
3963.. _logging-config-dict-connections:
3964
3965Object connections
3966""""""""""""""""""
3967
3968The schema describes a set of logging objects - loggers,
3969handlers, formatters, filters - which are connected to each other in
3970an object graph. Thus, the schema needs to represent connections
3971between the objects. For example, say that, once configured, a
3972particular logger has attached to it a particular handler. For the
3973purposes of this discussion, we can say that the logger represents the
3974source, and the handler the destination, of a connection between the
3975two. Of course in the configured objects this is represented by the
3976logger holding a reference to the handler. In the configuration dict,
3977this is done by giving each destination object an id which identifies
3978it unambiguously, and then using the id in the source object's
3979configuration to indicate that a connection exists between the source
3980and the destination object with that id.
3981
3982So, for example, consider the following YAML snippet::
3983
3984 formatters:
3985 brief:
3986 # configuration for formatter with id 'brief' goes here
3987 precise:
3988 # configuration for formatter with id 'precise' goes here
3989 handlers:
3990 h1: #This is an id
3991 # configuration of handler with id 'h1' goes here
3992 formatter: brief
3993 h2: #This is another id
3994 # configuration of handler with id 'h2' goes here
3995 formatter: precise
3996 loggers:
3997 foo.bar.baz:
3998 # other configuration for logger 'foo.bar.baz'
3999 handlers: [h1, h2]
4000
4001(Note: YAML used here because it's a little more readable than the
4002equivalent Python source form for the dictionary.)
4003
4004The ids for loggers are the logger names which would be used
4005programmatically to obtain a reference to those loggers, e.g.
4006``foo.bar.baz``. The ids for Formatters and Filters can be any string
4007value (such as ``brief``, ``precise`` above) and they are transient,
4008in that they are only meaningful for processing the configuration
4009dictionary and used to determine connections between objects, and are
4010not persisted anywhere when the configuration call is complete.
4011
4012The above snippet indicates that logger named ``foo.bar.baz`` should
4013have two handlers attached to it, which are described by the handler
4014ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
4015``brief``, and the formatter for ``h2`` is that described by id
4016``precise``.
4017
4018
4019.. _logging-config-dict-userdef:
4020
4021User-defined objects
4022""""""""""""""""""""
4023
4024The schema supports user-defined objects for handlers, filters and
4025formatters. (Loggers do not need to have different types for
4026different instances, so there is no support in this configuration
4027schema for user-defined logger classes.)
4028
4029Objects to be configured are described by dictionaries
4030which detail their configuration. In some places, the logging system
4031will be able to infer from the context how an object is to be
4032instantiated, but when a user-defined object is to be instantiated,
4033the system will not know how to do this. In order to provide complete
4034flexibility for user-defined object instantiation, the user needs
4035to provide a 'factory' - a callable which is called with a
4036configuration dictionary and which returns the instantiated object.
4037This is signalled by an absolute import path to the factory being
4038made available under the special key ``'()'``. Here's a concrete
4039example::
4040
4041 formatters:
4042 brief:
4043 format: '%(message)s'
4044 default:
4045 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
4046 datefmt: '%Y-%m-%d %H:%M:%S'
4047 custom:
4048 (): my.package.customFormatterFactory
4049 bar: baz
4050 spam: 99.9
4051 answer: 42
4052
4053The above YAML snippet defines three formatters. The first, with id
4054``brief``, is a standard :class:`logging.Formatter` instance with the
4055specified format string. The second, with id ``default``, has a
4056longer format and also defines the time format explicitly, and will
4057result in a :class:`logging.Formatter` initialized with those two format
4058strings. Shown in Python source form, the ``brief`` and ``default``
4059formatters have configuration sub-dictionaries::
4060
4061 {
4062 'format' : '%(message)s'
4063 }
4064
4065and::
4066
4067 {
4068 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4069 'datefmt' : '%Y-%m-%d %H:%M:%S'
4070 }
4071
4072respectively, and as these dictionaries do not contain the special key
4073``'()'``, the instantiation is inferred from the context: as a result,
4074standard :class:`logging.Formatter` instances are created. The
4075configuration sub-dictionary for the third formatter, with id
4076``custom``, is::
4077
4078 {
4079 '()' : 'my.package.customFormatterFactory',
4080 'bar' : 'baz',
4081 'spam' : 99.9,
4082 'answer' : 42
4083 }
4084
4085and this contains the special key ``'()'``, which means that
4086user-defined instantiation is wanted. In this case, the specified
4087factory callable will be used. If it is an actual callable it will be
4088used directly - otherwise, if you specify a string (as in the example)
4089the actual callable will be located using normal import mechanisms.
4090The callable will be called with the **remaining** items in the
4091configuration sub-dictionary as keyword arguments. In the above
4092example, the formatter with id ``custom`` will be assumed to be
4093returned by the call::
4094
4095 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4096
4097The key ``'()'`` has been used as the special key because it is not a
4098valid keyword parameter name, and so will not clash with the names of
4099the keyword arguments used in the call. The ``'()'`` also serves as a
4100mnemonic that the corresponding value is a callable.
4101
4102
4103.. _logging-config-dict-externalobj:
4104
4105Access to external objects
4106""""""""""""""""""""""""""
4107
4108There are times where a configuration needs to refer to objects
4109external to the configuration, for example ``sys.stderr``. If the
4110configuration dict is constructed using Python code, this is
4111straightforward, but a problem arises when the configuration is
4112provided via a text file (e.g. JSON, YAML). In a text file, there is
4113no standard way to distinguish ``sys.stderr`` from the literal string
4114``'sys.stderr'``. To facilitate this distinction, the configuration
4115system looks for certain special prefixes in string values and
4116treat them specially. For example, if the literal string
4117``'ext://sys.stderr'`` is provided as a value in the configuration,
4118then the ``ext://`` will be stripped off and the remainder of the
4119value processed using normal import mechanisms.
4120
4121The handling of such prefixes is done in a way analogous to protocol
4122handling: there is a generic mechanism to look for prefixes which
4123match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4124whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4125in a prefix-dependent manner and the result of the processing replaces
4126the string value. If the prefix is not recognised, then the string
4127value will be left as-is.
4128
4129
4130.. _logging-config-dict-internalobj:
4131
4132Access to internal objects
4133""""""""""""""""""""""""""
4134
4135As well as external objects, there is sometimes also a need to refer
4136to objects in the configuration. This will be done implicitly by the
4137configuration system for things that it knows about. For example, the
4138string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4139automatically be converted to the value ``logging.DEBUG``, and the
4140``handlers``, ``filters`` and ``formatter`` entries will take an
4141object id and resolve to the appropriate destination object.
4142
4143However, a more generic mechanism is needed for user-defined
4144objects which are not known to the :mod:`logging` module. For
4145example, consider :class:`logging.handlers.MemoryHandler`, which takes
4146a ``target`` argument which is another handler to delegate to. Since
4147the system already knows about this class, then in the configuration,
4148the given ``target`` just needs to be the object id of the relevant
4149target handler, and the system will resolve to the handler from the
4150id. If, however, a user defines a ``my.package.MyHandler`` which has
4151an ``alternate`` handler, the configuration system would not know that
4152the ``alternate`` referred to a handler. To cater for this, a generic
4153resolution system allows the user to specify::
4154
4155 handlers:
4156 file:
4157 # configuration of file handler goes here
4158
4159 custom:
4160 (): my.package.MyHandler
4161 alternate: cfg://handlers.file
4162
4163The literal string ``'cfg://handlers.file'`` will be resolved in an
4164analogous way to strings with the ``ext://`` prefix, but looking
4165in the configuration itself rather than the import namespace. The
4166mechanism allows access by dot or by index, in a similar way to
4167that provided by ``str.format``. Thus, given the following snippet::
4168
4169 handlers:
4170 email:
4171 class: logging.handlers.SMTPHandler
4172 mailhost: localhost
4173 fromaddr: my_app@domain.tld
4174 toaddrs:
4175 - support_team@domain.tld
4176 - dev_team@domain.tld
4177 subject: Houston, we have a problem.
4178
4179in the configuration, the string ``'cfg://handlers'`` would resolve to
4180the dict with key ``handlers``, the string ``'cfg://handlers.email``
4181would resolve to the dict with key ``email`` in the ``handlers`` dict,
4182and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4183resolve to ``'dev_team.domain.tld'`` and the string
4184``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4185``'support_team@domain.tld'``. The ``subject`` value could be accessed
4186using either ``'cfg://handlers.email.subject'`` or, equivalently,
4187``'cfg://handlers.email[subject]'``. The latter form only needs to be
4188used if the key contains spaces or non-alphanumeric characters. If an
4189index value consists only of decimal digits, access will be attempted
4190using the corresponding integer value, falling back to the string
4191value if needed.
4192
4193Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4194resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4195If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4196the system will attempt to retrieve the value from
4197``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4198to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4199fails.
4200
Georg Brandl116aa622007-08-15 14:28:22 +00004201.. _logging-config-fileformat:
4202
4203Configuration file format
4204^^^^^^^^^^^^^^^^^^^^^^^^^
4205
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004206The configuration file format understood by :func:`fileConfig` is based on
4207:mod:`configparser` functionality. The file must contain sections called
4208``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4209entities of each type which are defined in the file. For each such entity, there
4210is a separate section which identifies how that entity is configured. Thus, for
4211a logger named ``log01`` in the ``[loggers]`` section, the relevant
4212configuration details are held in a section ``[logger_log01]``. Similarly, a
4213handler called ``hand01`` in the ``[handlers]`` section will have its
4214configuration held in a section called ``[handler_hand01]``, while a formatter
4215called ``form01`` in the ``[formatters]`` section will have its configuration
4216specified in a section called ``[formatter_form01]``. The root logger
4217configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004218
4219Examples of these sections in the file are given below. ::
4220
4221 [loggers]
4222 keys=root,log02,log03,log04,log05,log06,log07
4223
4224 [handlers]
4225 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4226
4227 [formatters]
4228 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4229
4230The root logger must specify a level and a list of handlers. An example of a
4231root logger section is given below. ::
4232
4233 [logger_root]
4234 level=NOTSET
4235 handlers=hand01
4236
4237The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4238``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4239logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4240package's namespace.
4241
4242The ``handlers`` entry is a comma-separated list of handler names, which must
4243appear in the ``[handlers]`` section. These names must appear in the
4244``[handlers]`` section and have corresponding sections in the configuration
4245file.
4246
4247For loggers other than the root logger, some additional information is required.
4248This is illustrated by the following example. ::
4249
4250 [logger_parser]
4251 level=DEBUG
4252 handlers=hand01
4253 propagate=1
4254 qualname=compiler.parser
4255
4256The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4257except that if a non-root logger's level is specified as ``NOTSET``, the system
4258consults loggers higher up the hierarchy to determine the effective level of the
4259logger. The ``propagate`` entry is set to 1 to indicate that messages must
4260propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4261indicate that messages are **not** propagated to handlers up the hierarchy. The
4262``qualname`` entry is the hierarchical channel name of the logger, that is to
4263say the name used by the application to get the logger.
4264
4265Sections which specify handler configuration are exemplified by the following.
4266::
4267
4268 [handler_hand01]
4269 class=StreamHandler
4270 level=NOTSET
4271 formatter=form01
4272 args=(sys.stdout,)
4273
4274The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4275in the ``logging`` package's namespace). The ``level`` is interpreted as for
4276loggers, and ``NOTSET`` is taken to mean "log everything".
4277
4278The ``formatter`` entry indicates the key name of the formatter for this
4279handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4280If a name is specified, it must appear in the ``[formatters]`` section and have
4281a corresponding section in the configuration file.
4282
4283The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4284package's namespace, is the list of arguments to the constructor for the handler
4285class. Refer to the constructors for the relevant handlers, or to the examples
4286below, to see how typical entries are constructed. ::
4287
4288 [handler_hand02]
4289 class=FileHandler
4290 level=DEBUG
4291 formatter=form02
4292 args=('python.log', 'w')
4293
4294 [handler_hand03]
4295 class=handlers.SocketHandler
4296 level=INFO
4297 formatter=form03
4298 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4299
4300 [handler_hand04]
4301 class=handlers.DatagramHandler
4302 level=WARN
4303 formatter=form04
4304 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4305
4306 [handler_hand05]
4307 class=handlers.SysLogHandler
4308 level=ERROR
4309 formatter=form05
4310 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4311
4312 [handler_hand06]
4313 class=handlers.NTEventLogHandler
4314 level=CRITICAL
4315 formatter=form06
4316 args=('Python Application', '', 'Application')
4317
4318 [handler_hand07]
4319 class=handlers.SMTPHandler
4320 level=WARN
4321 formatter=form07
4322 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4323
4324 [handler_hand08]
4325 class=handlers.MemoryHandler
4326 level=NOTSET
4327 formatter=form08
4328 target=
4329 args=(10, ERROR)
4330
4331 [handler_hand09]
4332 class=handlers.HTTPHandler
4333 level=NOTSET
4334 formatter=form09
4335 args=('localhost:9022', '/log', 'GET')
4336
4337Sections which specify formatter configuration are typified by the following. ::
4338
4339 [formatter_form01]
4340 format=F1 %(asctime)s %(levelname)s %(message)s
4341 datefmt=
4342 class=logging.Formatter
4343
4344The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004345the :func:`strftime`\ -compatible date/time format string. If empty, the
4346package substitutes ISO8601 format date/times, which is almost equivalent to
4347specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
4348also specifies milliseconds, which are appended to the result of using the above
4349format string, with a comma separator. An example time in ISO8601 format is
4350``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004351
4352The ``class`` entry is optional. It indicates the name of the formatter's class
4353(as a dotted module and class name.) This option is useful for instantiating a
4354:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4355exception tracebacks in an expanded or condensed format.
4356
Christian Heimes8b0facf2007-12-04 19:30:01 +00004357
4358Configuration server example
4359^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4360
4361Here is an example of a module using the logging configuration server::
4362
4363 import logging
4364 import logging.config
4365 import time
4366 import os
4367
4368 # read initial config file
4369 logging.config.fileConfig("logging.conf")
4370
4371 # create and start listener on port 9999
4372 t = logging.config.listen(9999)
4373 t.start()
4374
4375 logger = logging.getLogger("simpleExample")
4376
4377 try:
4378 # loop through logging calls to see the difference
4379 # new configurations make, until Ctrl+C is pressed
4380 while True:
4381 logger.debug("debug message")
4382 logger.info("info message")
4383 logger.warn("warn message")
4384 logger.error("error message")
4385 logger.critical("critical message")
4386 time.sleep(5)
4387 except KeyboardInterrupt:
4388 # cleanup
4389 logging.config.stopListening()
4390 t.join()
4391
4392And here is a script that takes a filename and sends that file to the server,
4393properly preceded with the binary-encoded length, as the new logging
4394configuration::
4395
4396 #!/usr/bin/env python
4397 import socket, sys, struct
4398
4399 data_to_send = open(sys.argv[1], "r").read()
4400
4401 HOST = 'localhost'
4402 PORT = 9999
4403 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00004404 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004405 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00004406 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004407 s.send(struct.pack(">L", len(data_to_send)))
4408 s.send(data_to_send)
4409 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00004410 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004411
4412
4413More examples
4414-------------
4415
4416Multiple handlers and formatters
4417^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4418
4419Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4420or maximum quota for the number of handlers you may add. Sometimes it will be
4421beneficial for an application to log all messages of all severities to a text
4422file while simultaneously logging errors or above to the console. To set this
4423up, simply configure the appropriate handlers. The logging calls in the
4424application code will remain unchanged. Here is a slight modification to the
4425previous simple module-based configuration example::
4426
4427 import logging
4428
4429 logger = logging.getLogger("simple_example")
4430 logger.setLevel(logging.DEBUG)
4431 # create file handler which logs even debug messages
4432 fh = logging.FileHandler("spam.log")
4433 fh.setLevel(logging.DEBUG)
4434 # create console handler with a higher log level
4435 ch = logging.StreamHandler()
4436 ch.setLevel(logging.ERROR)
4437 # create formatter and add it to the handlers
4438 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4439 ch.setFormatter(formatter)
4440 fh.setFormatter(formatter)
4441 # add the handlers to logger
4442 logger.addHandler(ch)
4443 logger.addHandler(fh)
4444
4445 # "application" code
4446 logger.debug("debug message")
4447 logger.info("info message")
4448 logger.warn("warn message")
4449 logger.error("error message")
4450 logger.critical("critical message")
4451
4452Notice that the "application" code does not care about multiple handlers. All
4453that changed was the addition and configuration of a new handler named *fh*.
4454
4455The ability to create new handlers with higher- or lower-severity filters can be
4456very helpful when writing and testing an application. Instead of using many
4457``print`` statements for debugging, use ``logger.debug``: Unlike the print
4458statements, which you will have to delete or comment out later, the logger.debug
4459statements can remain intact in the source code and remain dormant until you
4460need them again. At that time, the only change that needs to happen is to
4461modify the severity level of the logger and/or handler to debug.
4462
4463
4464Using logging in multiple modules
4465^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4466
4467It was mentioned above that multiple calls to
4468``logging.getLogger('someLogger')`` return a reference to the same logger
4469object. This is true not only within the same module, but also across modules
4470as long as it is in the same Python interpreter process. It is true for
4471references to the same object; additionally, application code can define and
4472configure a parent logger in one module and create (but not configure) a child
4473logger in a separate module, and all logger calls to the child will pass up to
4474the parent. Here is a main module::
4475
4476 import logging
4477 import auxiliary_module
4478
4479 # create logger with "spam_application"
4480 logger = logging.getLogger("spam_application")
4481 logger.setLevel(logging.DEBUG)
4482 # create file handler which logs even debug messages
4483 fh = logging.FileHandler("spam.log")
4484 fh.setLevel(logging.DEBUG)
4485 # create console handler with a higher log level
4486 ch = logging.StreamHandler()
4487 ch.setLevel(logging.ERROR)
4488 # create formatter and add it to the handlers
4489 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4490 fh.setFormatter(formatter)
4491 ch.setFormatter(formatter)
4492 # add the handlers to the logger
4493 logger.addHandler(fh)
4494 logger.addHandler(ch)
4495
4496 logger.info("creating an instance of auxiliary_module.Auxiliary")
4497 a = auxiliary_module.Auxiliary()
4498 logger.info("created an instance of auxiliary_module.Auxiliary")
4499 logger.info("calling auxiliary_module.Auxiliary.do_something")
4500 a.do_something()
4501 logger.info("finished auxiliary_module.Auxiliary.do_something")
4502 logger.info("calling auxiliary_module.some_function()")
4503 auxiliary_module.some_function()
4504 logger.info("done with auxiliary_module.some_function()")
4505
4506Here is the auxiliary module::
4507
4508 import logging
4509
4510 # create logger
4511 module_logger = logging.getLogger("spam_application.auxiliary")
4512
4513 class Auxiliary:
4514 def __init__(self):
4515 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4516 self.logger.info("creating an instance of Auxiliary")
4517 def do_something(self):
4518 self.logger.info("doing something")
4519 a = 1 + 1
4520 self.logger.info("done doing something")
4521
4522 def some_function():
4523 module_logger.info("received a call to \"some_function\"")
4524
4525The output looks like this::
4526
Christian Heimes043d6f62008-01-07 17:19:16 +00004527 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004528 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004529 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004530 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004531 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004532 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004533 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004534 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004535 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004536 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004537 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004538 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004539 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004540 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004541 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004542 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004543 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004544 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004545 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004546 done with auxiliary_module.some_function()
4547