blob: fb4bc4c7dd7fb3b6ab2ea0eb6df1fc1aa6111de7 [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
12.. % These apply to all modules, and may be given more than once:
13
14
15
16.. index:: pair: Errors; logging
17
Georg Brandl116aa622007-08-15 14:28:22 +000018This module defines functions and classes which implement a flexible error
19logging system for applications.
20
21Logging is performed by calling methods on instances of the :class:`Logger`
22class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
23conceptually arranged in a name space hierarchy using dots (periods) as
24separators. For example, a logger named "scan" is the parent of loggers
25"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
26and indicate the area of an application in which a logged message originates.
27
28Logged messages also have levels of importance associated with them. The default
29levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
30:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
31importance of a logged message by calling an appropriate method of
32:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
33:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
34constrained to use these levels: you can specify your own and use a more general
35:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
36
37The numeric values of logging levels are given in the following table. These are
38primarily of interest if you want to define your own levels, and need them to
39have specific values relative to the predefined levels. If you define a level
40with the same numeric value, it overwrites the predefined value; the predefined
41name is lost.
42
43+--------------+---------------+
44| Level | Numeric value |
45+==============+===============+
46| ``CRITICAL`` | 50 |
47+--------------+---------------+
48| ``ERROR`` | 40 |
49+--------------+---------------+
50| ``WARNING`` | 30 |
51+--------------+---------------+
52| ``INFO`` | 20 |
53+--------------+---------------+
54| ``DEBUG`` | 10 |
55+--------------+---------------+
56| ``NOTSET`` | 0 |
57+--------------+---------------+
58
59Levels can also be associated with loggers, being set either by the developer or
60through loading a saved logging configuration. When a logging method is called
61on a logger, the logger compares its own level with the level associated with
62the method call. If the logger's level is higher than the method call's, no
63logging message is actually generated. This is the basic mechanism controlling
64the verbosity of logging output.
65
66Logging messages are encoded as instances of the :class:`LogRecord` class. When
67a logger decides to actually log an event, a :class:`LogRecord` instance is
68created from the logging message.
69
70Logging messages are subjected to a dispatch mechanism through the use of
71:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
72class. Handlers are responsible for ensuring that a logged message (in the form
73of a :class:`LogRecord`) ends up in a particular location (or set of locations)
74which is useful for the target audience for that message (such as end users,
75support desk staff, system administrators, developers). Handlers are passed
76:class:`LogRecord` instances intended for particular destinations. Each logger
77can have zero, one or more handlers associated with it (via the
78:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
79directly associated with a logger, *all handlers associated with all ancestors
80of the logger* are called to dispatch the message.
81
82Just as for loggers, handlers can have levels associated with them. A handler's
83level acts as a filter in the same way as a logger's level does. If a handler
84decides to actually dispatch an event, the :meth:`emit` method is used to send
85the message to its destination. Most user-defined subclasses of :class:`Handler`
86will need to override this :meth:`emit`.
87
88In addition to the base :class:`Handler` class, many useful subclasses are
89provided:
90
91#. :class:`StreamHandler` instances send error messages to streams (file-like
92 objects).
93
94#. :class:`FileHandler` instances send error messages to disk files.
95
96#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log
97 files at a certain point. It is not meant to be instantiated directly. Instead,
98 use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`.
99
100#. :class:`RotatingFileHandler` instances send error messages to disk files,
101 with support for maximum log file sizes and log file rotation.
102
103#. :class:`TimedRotatingFileHandler` instances send error messages to disk files
104 rotating the log file at certain timed intervals.
105
106#. :class:`SocketHandler` instances send error messages to TCP/IP sockets.
107
108#. :class:`DatagramHandler` instances send error messages to UDP sockets.
109
110#. :class:`SMTPHandler` instances send error messages to a designated email
111 address.
112
113#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon,
114 possibly on a remote machine.
115
116#. :class:`NTEventLogHandler` instances send error messages to a Windows
117 NT/2000/XP event log.
118
119#. :class:`MemoryHandler` instances send error messages to a buffer in memory,
120 which is flushed whenever specific criteria are met.
121
122#. :class:`HTTPHandler` instances send error messages to an HTTP server using
123 either ``GET`` or ``POST`` semantics.
124
125The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the
126core logging package. The other handlers are defined in a sub- module,
127:mod:`logging.handlers`. (There is also another sub-module,
128:mod:`logging.config`, for configuration functionality.)
129
130Logged messages are formatted for presentation through instances of the
131:class:`Formatter` class. They are initialized with a format string suitable for
132use with the % operator and a dictionary.
133
134For formatting multiple messages in a batch, instances of
135:class:`BufferingFormatter` can be used. In addition to the format string (which
136is applied to each message in the batch), there is provision for header and
137trailer format strings.
138
139When filtering based on logger level and/or handler level is not enough,
140instances of :class:`Filter` can be added to both :class:`Logger` and
141:class:`Handler` instances (through their :meth:`addFilter` method). Before
142deciding to process a message further, both loggers and handlers consult all
143their filters for permission. If any filter returns a false value, the message
144is not processed further.
145
146The basic :class:`Filter` functionality allows filtering by specific logger
147name. If this feature is used, messages sent to the named logger and its
148children are allowed through the filter, and all others dropped.
149
150In addition to the classes described above, there are a number of module- level
151functions.
152
153
154.. function:: getLogger([name])
155
156 Return a logger with the specified name or, if no name is specified, return a
157 logger which is the root logger of the hierarchy. If specified, the name is
158 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
159 Choice of these names is entirely up to the developer who is using logging.
160
161 All calls to this function with a given name return the same logger instance.
162 This means that logger instances never need to be passed between different parts
163 of an application.
164
165
166.. function:: getLoggerClass()
167
168 Return either the standard :class:`Logger` class, or the last class passed to
169 :func:`setLoggerClass`. This function may be called from within a new class
170 definition, to ensure that installing a customised :class:`Logger` class will
171 not undo customisations already applied by other code. For example::
172
173 class MyLogger(logging.getLoggerClass()):
174 # ... override behaviour here
175
176
177.. function:: debug(msg[, *args[, **kwargs]])
178
179 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
180 message format string, and the *args* are the arguments which are merged into
181 *msg* using the string formatting operator. (Note that this means that you can
182 use keywords in the format string, together with a single dictionary argument.)
183
184 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
185 which, if it does not evaluate as false, causes exception information to be
186 added to the logging message. If an exception tuple (in the format returned by
187 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
188 is called to get the exception information.
189
190 The other optional keyword argument is *extra* which can be used to pass a
191 dictionary which is used to populate the __dict__ of the LogRecord created for
192 the logging event with user-defined attributes. These custom attributes can then
193 be used as you like. For example, they could be incorporated into logged
194 messages. For example::
195
196 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
197 logging.basicConfig(format=FORMAT)
198 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
199 logging.warning("Protocol problem: %s", "connection reset", extra=d)
200
201 would print something like ::
202
203 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
204
205 The keys in the dictionary passed in *extra* should not clash with the keys used
206 by the logging system. (See the :class:`Formatter` documentation for more
207 information on which keys are used by the logging system.)
208
209 If you choose to use these attributes in logged messages, you need to exercise
210 some care. In the above example, for instance, the :class:`Formatter` has been
211 set up with a format string which expects 'clientip' and 'user' in the attribute
212 dictionary of the LogRecord. If these are missing, the message will not be
213 logged because a string formatting exception will occur. So in this case, you
214 always need to pass the *extra* dictionary with these keys.
215
216 While this might be annoying, this feature is intended for use in specialized
217 circumstances, such as multi-threaded servers where the same code executes in
218 many contexts, and interesting conditions which arise are dependent on this
219 context (such as remote client IP address and authenticated user name, in the
220 above example). In such circumstances, it is likely that specialized
221 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. function:: info(msg[, *args[, **kwargs]])
225
226 Logs a message with level :const:`INFO` on the root logger. The arguments are
227 interpreted as for :func:`debug`.
228
229
230.. function:: warning(msg[, *args[, **kwargs]])
231
232 Logs a message with level :const:`WARNING` on the root logger. The arguments are
233 interpreted as for :func:`debug`.
234
235
236.. function:: error(msg[, *args[, **kwargs]])
237
238 Logs a message with level :const:`ERROR` on the root logger. The arguments are
239 interpreted as for :func:`debug`.
240
241
242.. function:: critical(msg[, *args[, **kwargs]])
243
244 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
245 are interpreted as for :func:`debug`.
246
247
248.. function:: exception(msg[, *args])
249
250 Logs a message with level :const:`ERROR` on the root logger. The arguments are
251 interpreted as for :func:`debug`. Exception info is added to the logging
252 message. This function should only be called from an exception handler.
253
254
255.. function:: log(level, msg[, *args[, **kwargs]])
256
257 Logs a message with level *level* on the root logger. The other arguments are
258 interpreted as for :func:`debug`.
259
260
261.. function:: disable(lvl)
262
263 Provides an overriding level *lvl* for all loggers which takes precedence over
264 the logger's own level. When the need arises to temporarily throttle logging
265 output down across the whole application, this function can be useful.
266
267
268.. function:: addLevelName(lvl, levelName)
269
270 Associates level *lvl* with text *levelName* in an internal dictionary, which is
271 used to map numeric levels to a textual representation, for example when a
272 :class:`Formatter` formats a message. This function can also be used to define
273 your own levels. The only constraints are that all levels used must be
274 registered using this function, levels should be positive integers and they
275 should increase in increasing order of severity.
276
277
278.. function:: getLevelName(lvl)
279
280 Returns the textual representation of logging level *lvl*. If the level is one
281 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
282 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
283 have associated levels with names using :func:`addLevelName` then the name you
284 have associated with *lvl* is returned. If a numeric value corresponding to one
285 of the defined levels is passed in, the corresponding string representation is
286 returned. Otherwise, the string "Level %s" % lvl is returned.
287
288
289.. function:: makeLogRecord(attrdict)
290
291 Creates and returns a new :class:`LogRecord` instance whose attributes are
292 defined by *attrdict*. This function is useful for taking a pickled
293 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
294 it as a :class:`LogRecord` instance at the receiving end.
295
296
297.. function:: basicConfig([**kwargs])
298
299 Does basic configuration for the logging system by creating a
300 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
301 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
302 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
303 if no handlers are defined for the root logger.
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305 The following keyword arguments are supported.
306
307 +--------------+---------------------------------------------+
308 | Format | Description |
309 +==============+=============================================+
310 | ``filename`` | Specifies that a FileHandler be created, |
311 | | using the specified filename, rather than a |
312 | | StreamHandler. |
313 +--------------+---------------------------------------------+
314 | ``filemode`` | Specifies the mode to open the file, if |
315 | | filename is specified (if filemode is |
316 | | unspecified, it defaults to 'a'). |
317 +--------------+---------------------------------------------+
318 | ``format`` | Use the specified format string for the |
319 | | handler. |
320 +--------------+---------------------------------------------+
321 | ``datefmt`` | Use the specified date/time format. |
322 +--------------+---------------------------------------------+
323 | ``level`` | Set the root logger level to the specified |
324 | | level. |
325 +--------------+---------------------------------------------+
326 | ``stream`` | Use the specified stream to initialize the |
327 | | StreamHandler. Note that this argument is |
328 | | incompatible with 'filename' - if both are |
329 | | present, 'stream' is ignored. |
330 +--------------+---------------------------------------------+
331
332
333.. function:: shutdown()
334
335 Informs the logging system to perform an orderly shutdown by flushing and
336 closing all handlers.
337
338
339.. function:: setLoggerClass(klass)
340
341 Tells the logging system to use the class *klass* when instantiating a logger.
342 The class should define :meth:`__init__` such that only a name argument is
343 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
344 function is typically called before any loggers are instantiated by applications
345 which need to use custom logger behavior.
346
347
348.. seealso::
349
350 :pep:`282` - A Logging System
351 The proposal which described this feature for inclusion in the Python standard
352 library.
353
354 `Original Python :mod:`logging` package <http://www.red-dove.com/python_logging.html>`_
355 This is the original source for the :mod:`logging` package. The version of the
356 package available from this site is suitable for use with Python 1.5.2, 2.1.x
357 and 2.2.x, which do not include the :mod:`logging` package in the standard
358 library.
359
360
361Logger Objects
362--------------
363
364Loggers have the following attributes and methods. Note that Loggers are never
365instantiated directly, but always through the module-level function
366``logging.getLogger(name)``.
367
368
369.. attribute:: Logger.propagate
370
371 If this evaluates to false, logging messages are not passed by this logger or by
372 child loggers to higher level (ancestor) loggers. The constructor sets this
373 attribute to 1.
374
375
376.. method:: Logger.setLevel(lvl)
377
378 Sets the threshold for this logger to *lvl*. Logging messages which are less
379 severe than *lvl* will be ignored. When a logger is created, the level is set to
380 :const:`NOTSET` (which causes all messages to be processed when the logger is
381 the root logger, or delegation to the parent when the logger is a non-root
382 logger). Note that the root logger is created with level :const:`WARNING`.
383
384 The term "delegation to the parent" means that if a logger has a level of
385 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
386 a level other than NOTSET is found, or the root is reached.
387
388 If an ancestor is found with a level other than NOTSET, then that ancestor's
389 level is treated as the effective level of the logger where the ancestor search
390 began, and is used to determine how a logging event is handled.
391
392 If the root is reached, and it has a level of NOTSET, then all messages will be
393 processed. Otherwise, the root's level will be used as the effective level.
394
395
396.. method:: Logger.isEnabledFor(lvl)
397
398 Indicates if a message of severity *lvl* would be processed by this logger.
399 This method checks first the module-level level set by
400 ``logging.disable(lvl)`` and then the logger's effective level as determined
401 by :meth:`getEffectiveLevel`.
402
403
404.. method:: Logger.getEffectiveLevel()
405
406 Indicates the effective level for this logger. If a value other than
407 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
408 the hierarchy is traversed towards the root until a value other than
409 :const:`NOTSET` is found, and that value is returned.
410
411
412.. method:: Logger.debug(msg[, *args[, **kwargs]])
413
414 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
415 message format string, and the *args* are the arguments which are merged into
416 *msg* using the string formatting operator. (Note that this means that you can
417 use keywords in the format string, together with a single dictionary argument.)
418
419 There are two keyword arguments in *kwargs* which are inspected: *exc_info*
420 which, if it does not evaluate as false, causes exception information to be
421 added to the logging message. If an exception tuple (in the format returned by
422 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
423 is called to get the exception information.
424
425 The other optional keyword argument is *extra* which can be used to pass a
426 dictionary which is used to populate the __dict__ of the LogRecord created for
427 the logging event with user-defined attributes. These custom attributes can then
428 be used as you like. For example, they could be incorporated into logged
429 messages. For example::
430
431 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
432 logging.basicConfig(format=FORMAT)
433 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
434 logger = logging.getLogger("tcpserver")
435 logger.warning("Protocol problem: %s", "connection reset", extra=d)
436
437 would print something like ::
438
439 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
440
441 The keys in the dictionary passed in *extra* should not clash with the keys used
442 by the logging system. (See the :class:`Formatter` documentation for more
443 information on which keys are used by the logging system.)
444
445 If you choose to use these attributes in logged messages, you need to exercise
446 some care. In the above example, for instance, the :class:`Formatter` has been
447 set up with a format string which expects 'clientip' and 'user' in the attribute
448 dictionary of the LogRecord. If these are missing, the message will not be
449 logged because a string formatting exception will occur. So in this case, you
450 always need to pass the *extra* dictionary with these keys.
451
452 While this might be annoying, this feature is intended for use in specialized
453 circumstances, such as multi-threaded servers where the same code executes in
454 many contexts, and interesting conditions which arise are dependent on this
455 context (such as remote client IP address and authenticated user name, in the
456 above example). In such circumstances, it is likely that specialized
457 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
458
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460.. method:: Logger.info(msg[, *args[, **kwargs]])
461
462 Logs a message with level :const:`INFO` on this logger. The arguments are
463 interpreted as for :meth:`debug`.
464
465
466.. method:: Logger.warning(msg[, *args[, **kwargs]])
467
468 Logs a message with level :const:`WARNING` on this logger. The arguments are
469 interpreted as for :meth:`debug`.
470
471
472.. method:: Logger.error(msg[, *args[, **kwargs]])
473
474 Logs a message with level :const:`ERROR` on this logger. The arguments are
475 interpreted as for :meth:`debug`.
476
477
478.. method:: Logger.critical(msg[, *args[, **kwargs]])
479
480 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
481 interpreted as for :meth:`debug`.
482
483
484.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
485
486 Logs a message with integer level *lvl* on this logger. The other arguments are
487 interpreted as for :meth:`debug`.
488
489
490.. method:: Logger.exception(msg[, *args])
491
492 Logs a message with level :const:`ERROR` on this logger. The arguments are
493 interpreted as for :meth:`debug`. Exception info is added to the logging
494 message. This method should only be called from an exception handler.
495
496
497.. method:: Logger.addFilter(filt)
498
499 Adds the specified filter *filt* to this logger.
500
501
502.. method:: Logger.removeFilter(filt)
503
504 Removes the specified filter *filt* from this logger.
505
506
507.. method:: Logger.filter(record)
508
509 Applies this logger's filters to the record and returns a true value if the
510 record is to be processed.
511
512
513.. method:: Logger.addHandler(hdlr)
514
515 Adds the specified handler *hdlr* to this logger.
516
517
518.. method:: Logger.removeHandler(hdlr)
519
520 Removes the specified handler *hdlr* from this logger.
521
522
523.. method:: Logger.findCaller()
524
525 Finds the caller's source filename and line number. Returns the filename, line
526 number and function name as a 3-element tuple.
527
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529.. method:: Logger.handle(record)
530
531 Handles a record by passing it to all handlers associated with this logger and
532 its ancestors (until a false value of *propagate* is found). This method is used
533 for unpickled records received from a socket, as well as those created locally.
534 Logger-level filtering is applied using :meth:`filter`.
535
536
537.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
538
539 This is a factory method which can be overridden in subclasses to create
540 specialized :class:`LogRecord` instances.
541
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543.. _minimal-example:
544
545Basic example
546-------------
547
Georg Brandl116aa622007-08-15 14:28:22 +0000548The :mod:`logging` package provides a lot of flexibility, and its configuration
549can appear daunting. This section demonstrates that simple use of the logging
550package is possible.
551
552The simplest example shows logging to the console::
553
554 import logging
555
556 logging.debug('A debug message')
557 logging.info('Some information')
558 logging.warning('A shot across the bows')
559
560If you run the above script, you'll see this::
561
562 WARNING:root:A shot across the bows
563
564Because no particular logger was specified, the system used the root logger. The
565debug and info messages didn't appear because by default, the root logger is
566configured to only handle messages with a severity of WARNING or above. The
567message format is also a configuration default, as is the output destination of
568the messages - ``sys.stderr``. The severity level, the message format and
569destination can be easily changed, as shown in the example below::
570
571 import logging
572
573 logging.basicConfig(level=logging.DEBUG,
574 format='%(asctime)s %(levelname)s %(message)s',
575 filename='/tmp/myapp.log',
576 filemode='w')
577 logging.debug('A debug message')
578 logging.info('Some information')
579 logging.warning('A shot across the bows')
580
581The :meth:`basicConfig` method is used to change the configuration defaults,
582which results in output (written to ``/tmp/myapp.log``) which should look
583something like the following::
584
585 2004-07-02 13:00:08,743 DEBUG A debug message
586 2004-07-02 13:00:08,743 INFO Some information
587 2004-07-02 13:00:08,743 WARNING A shot across the bows
588
589This time, all messages with a severity of DEBUG or above were handled, and the
590format of the messages was also changed, and output went to the specified file
591rather than the console.
592
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000593.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +0000594
595Formatting uses the old Python string formatting - see section
596:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +0000597specifiers. For a complete list of specifiers, consult the :class:`Formatter`
598documentation.
599
600+-------------------+-----------------------------------------------+
601| Format | Description |
602+===================+===============================================+
603| ``%(name)s`` | Name of the logger (logging channel). |
604+-------------------+-----------------------------------------------+
605| ``%(levelname)s`` | Text logging level for the message |
606| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
607| | ``'ERROR'``, ``'CRITICAL'``). |
608+-------------------+-----------------------------------------------+
609| ``%(asctime)s`` | Human-readable time when the |
610| | :class:`LogRecord` was created. By default |
611| | this is of the form "2003-07-08 16:49:45,896" |
612| | (the numbers after the comma are millisecond |
613| | portion of the time). |
614+-------------------+-----------------------------------------------+
615| ``%(message)s`` | The logged message. |
616+-------------------+-----------------------------------------------+
617
618To change the date/time format, you can pass an additional keyword parameter,
619*datefmt*, as in the following::
620
621 import logging
622
623 logging.basicConfig(level=logging.DEBUG,
624 format='%(asctime)s %(levelname)-8s %(message)s',
625 datefmt='%a, %d %b %Y %H:%M:%S',
626 filename='/temp/myapp.log',
627 filemode='w')
628 logging.debug('A debug message')
629 logging.info('Some information')
630 logging.warning('A shot across the bows')
631
632which would result in output like ::
633
634 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
635 Fri, 02 Jul 2004 13:06:18 INFO Some information
636 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
637
638The date format string follows the requirements of :func:`strftime` - see the
639documentation for the :mod:`time` module.
640
641If, instead of sending logging output to the console or a file, you'd rather use
642a file-like object which you have created separately, you can pass it to
643:func:`basicConfig` using the *stream* keyword argument. Note that if both
644*stream* and *filename* keyword arguments are passed, the *stream* argument is
645ignored.
646
647Of course, you can put variable information in your output. To do this, simply
648have the message be a format string and pass in additional arguments containing
649the variable information, as in the following example::
650
651 import logging
652
653 logging.basicConfig(level=logging.DEBUG,
654 format='%(asctime)s %(levelname)-8s %(message)s',
655 datefmt='%a, %d %b %Y %H:%M:%S',
656 filename='/temp/myapp.log',
657 filemode='w')
658 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
659
660which would result in ::
661
662 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
663
664
665.. _multiple-destinations:
666
667Logging to multiple destinations
668--------------------------------
669
670Let's say you want to log to console and file with different message formats and
671in differing circumstances. Say you want to log messages with levels of DEBUG
672and higher to file, and those messages at level INFO and higher to the console.
673Let's also assume that the file should contain timestamps, but the console
674messages should not. Here's how you can achieve this::
675
676 import logging
677
678 # set up logging to file - see previous section for more details
679 logging.basicConfig(level=logging.DEBUG,
680 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
681 datefmt='%m-%d %H:%M',
682 filename='/temp/myapp.log',
683 filemode='w')
684 # define a Handler which writes INFO messages or higher to the sys.stderr
685 console = logging.StreamHandler()
686 console.setLevel(logging.INFO)
687 # set a format which is simpler for console use
688 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
689 # tell the handler to use this format
690 console.setFormatter(formatter)
691 # add the handler to the root logger
692 logging.getLogger('').addHandler(console)
693
694 # Now, we can log to the root logger, or any other logger. First the root...
695 logging.info('Jackdaws love my big sphinx of quartz.')
696
697 # Now, define a couple of other loggers which might represent areas in your
698 # application:
699
700 logger1 = logging.getLogger('myapp.area1')
701 logger2 = logging.getLogger('myapp.area2')
702
703 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
704 logger1.info('How quickly daft jumping zebras vex.')
705 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
706 logger2.error('The five boxing wizards jump quickly.')
707
708When you run this, on the console you will see ::
709
710 root : INFO Jackdaws love my big sphinx of quartz.
711 myapp.area1 : INFO How quickly daft jumping zebras vex.
712 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
713 myapp.area2 : ERROR The five boxing wizards jump quickly.
714
715and in the file you will see something like ::
716
717 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
718 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
719 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
720 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
721 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
722
723As you can see, the DEBUG message only shows up in the file. The other messages
724are sent to both destinations.
725
726This example uses console and file handlers, but you can use any number and
727combination of handlers you choose.
728
729
730.. _network-logging:
731
732Sending and receiving logging events across a network
733-----------------------------------------------------
734
735Let's say you want to send logging events across a network, and handle them at
736the receiving end. A simple way of doing this is attaching a
737:class:`SocketHandler` instance to the root logger at the sending end::
738
739 import logging, logging.handlers
740
741 rootLogger = logging.getLogger('')
742 rootLogger.setLevel(logging.DEBUG)
743 socketHandler = logging.handlers.SocketHandler('localhost',
744 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
745 # don't bother with a formatter, since a socket handler sends the event as
746 # an unformatted pickle
747 rootLogger.addHandler(socketHandler)
748
749 # Now, we can log to the root logger, or any other logger. First the root...
750 logging.info('Jackdaws love my big sphinx of quartz.')
751
752 # Now, define a couple of other loggers which might represent areas in your
753 # application:
754
755 logger1 = logging.getLogger('myapp.area1')
756 logger2 = logging.getLogger('myapp.area2')
757
758 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
759 logger1.info('How quickly daft jumping zebras vex.')
760 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
761 logger2.error('The five boxing wizards jump quickly.')
762
763At the receiving end, you can set up a receiver using the :mod:`SocketServer`
764module. Here is a basic working example::
765
766 import cPickle
767 import logging
768 import logging.handlers
769 import SocketServer
770 import struct
771
772
773 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
774 """Handler for a streaming logging request.
775
776 This basically logs the record using whatever logging policy is
777 configured locally.
778 """
779
780 def handle(self):
781 """
782 Handle multiple requests - each expected to be a 4-byte length,
783 followed by the LogRecord in pickle format. Logs the record
784 according to whatever policy is configured locally.
785 """
786 while 1:
787 chunk = self.connection.recv(4)
788 if len(chunk) < 4:
789 break
790 slen = struct.unpack(">L", chunk)[0]
791 chunk = self.connection.recv(slen)
792 while len(chunk) < slen:
793 chunk = chunk + self.connection.recv(slen - len(chunk))
794 obj = self.unPickle(chunk)
795 record = logging.makeLogRecord(obj)
796 self.handleLogRecord(record)
797
798 def unPickle(self, data):
799 return cPickle.loads(data)
800
801 def handleLogRecord(self, record):
802 # if a name is specified, we use the named logger rather than the one
803 # implied by the record.
804 if self.server.logname is not None:
805 name = self.server.logname
806 else:
807 name = record.name
808 logger = logging.getLogger(name)
809 # N.B. EVERY record gets logged. This is because Logger.handle
810 # is normally called AFTER logger-level filtering. If you want
811 # to do filtering, do it at the client end to save wasting
812 # cycles and network bandwidth!
813 logger.handle(record)
814
815 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
816 """simple TCP socket-based logging receiver suitable for testing.
817 """
818
819 allow_reuse_address = 1
820
821 def __init__(self, host='localhost',
822 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
823 handler=LogRecordStreamHandler):
824 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
825 self.abort = 0
826 self.timeout = 1
827 self.logname = None
828
829 def serve_until_stopped(self):
830 import select
831 abort = 0
832 while not abort:
833 rd, wr, ex = select.select([self.socket.fileno()],
834 [], [],
835 self.timeout)
836 if rd:
837 self.handle_request()
838 abort = self.abort
839
840 def main():
841 logging.basicConfig(
842 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
843 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000844 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +0000845 tcpserver.serve_until_stopped()
846
847 if __name__ == "__main__":
848 main()
849
850First run the server, and then the client. On the client side, nothing is
851printed on the console; on the server side, you should see something like::
852
853 About to start TCP server...
854 59 root INFO Jackdaws love my big sphinx of quartz.
855 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
856 69 myapp.area1 INFO How quickly daft jumping zebras vex.
857 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
858 69 myapp.area2 ERROR The five boxing wizards jump quickly.
859
860
861Handler Objects
862---------------
863
864Handlers have the following attributes and methods. Note that :class:`Handler`
865is never instantiated directly; this class acts as a base for more useful
866subclasses. However, the :meth:`__init__` method in subclasses needs to call
867:meth:`Handler.__init__`.
868
869
870.. method:: Handler.__init__(level=NOTSET)
871
872 Initializes the :class:`Handler` instance by setting its level, setting the list
873 of filters to the empty list and creating a lock (using :meth:`createLock`) for
874 serializing access to an I/O mechanism.
875
876
877.. method:: Handler.createLock()
878
879 Initializes a thread lock which can be used to serialize access to underlying
880 I/O functionality which may not be threadsafe.
881
882
883.. method:: Handler.acquire()
884
885 Acquires the thread lock created with :meth:`createLock`.
886
887
888.. method:: Handler.release()
889
890 Releases the thread lock acquired with :meth:`acquire`.
891
892
893.. method:: Handler.setLevel(lvl)
894
895 Sets the threshold for this handler to *lvl*. Logging messages which are less
896 severe than *lvl* will be ignored. When a handler is created, the level is set
897 to :const:`NOTSET` (which causes all messages to be processed).
898
899
900.. method:: Handler.setFormatter(form)
901
902 Sets the :class:`Formatter` for this handler to *form*.
903
904
905.. method:: Handler.addFilter(filt)
906
907 Adds the specified filter *filt* to this handler.
908
909
910.. method:: Handler.removeFilter(filt)
911
912 Removes the specified filter *filt* from this handler.
913
914
915.. method:: Handler.filter(record)
916
917 Applies this handler's filters to the record and returns a true value if the
918 record is to be processed.
919
920
921.. method:: Handler.flush()
922
923 Ensure all logging output has been flushed. This version does nothing and is
924 intended to be implemented by subclasses.
925
926
927.. method:: Handler.close()
928
929 Tidy up any resources used by the handler. This version does nothing and is
930 intended to be implemented by subclasses.
931
932
933.. method:: Handler.handle(record)
934
935 Conditionally emits the specified logging record, depending on filters which may
936 have been added to the handler. Wraps the actual emission of the record with
937 acquisition/release of the I/O thread lock.
938
939
940.. method:: Handler.handleError(record)
941
942 This method should be called from handlers when an exception is encountered
943 during an :meth:`emit` call. By default it does nothing, which means that
944 exceptions get silently ignored. This is what is mostly wanted for a logging
945 system - most users will not care about errors in the logging system, they are
946 more interested in application errors. You could, however, replace this with a
947 custom handler if you wish. The specified record is the one which was being
948 processed when the exception occurred.
949
950
951.. method:: Handler.format(record)
952
953 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
954 default formatter for the module.
955
956
957.. method:: Handler.emit(record)
958
959 Do whatever it takes to actually log the specified logging record. This version
960 is intended to be implemented by subclasses and so raises a
961 :exc:`NotImplementedError`.
962
963
964StreamHandler
965^^^^^^^^^^^^^
966
967The :class:`StreamHandler` class, located in the core :mod:`logging` package,
968sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
969file-like object (or, more precisely, any object which supports :meth:`write`
970and :meth:`flush` methods).
971
972
973.. class:: StreamHandler([strm])
974
975 Returns a new instance of the :class:`StreamHandler` class. If *strm* is
976 specified, the instance will use it for logging output; otherwise, *sys.stderr*
977 will be used.
978
979
980.. method:: StreamHandler.emit(record)
981
982 If a formatter is specified, it is used to format the record. The record is then
983 written to the stream with a trailing newline. If exception information is
984 present, it is formatted using :func:`traceback.print_exception` and appended to
985 the stream.
986
987
988.. method:: StreamHandler.flush()
989
990 Flushes the stream by calling its :meth:`flush` method. Note that the
991 :meth:`close` method is inherited from :class:`Handler` and so does nothing, so
992 an explicit :meth:`flush` call may be needed at times.
993
994
995FileHandler
996^^^^^^^^^^^
997
998The :class:`FileHandler` class, located in the core :mod:`logging` package,
999sends logging output to a disk file. It inherits the output functionality from
1000:class:`StreamHandler`.
1001
1002
1003.. class:: FileHandler(filename[, mode[, encoding]])
1004
1005 Returns a new instance of the :class:`FileHandler` class. The specified file is
1006 opened and used as the stream for logging. If *mode* is not specified,
1007 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
1008 with that encoding. By default, the file grows indefinitely.
1009
1010
1011.. method:: FileHandler.close()
1012
1013 Closes the file.
1014
1015
1016.. method:: FileHandler.emit(record)
1017
1018 Outputs the record to the file.
1019
1020
1021WatchedFileHandler
1022^^^^^^^^^^^^^^^^^^
1023
Georg Brandl116aa622007-08-15 14:28:22 +00001024The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1025module, is a :class:`FileHandler` which watches the file it is logging to. If
1026the file changes, it is closed and reopened using the file name.
1027
1028A file change can happen because of usage of programs such as *newsyslog* and
1029*logrotate* which perform log file rotation. This handler, intended for use
1030under Unix/Linux, watches the file to see if it has changed since the last emit.
1031(A file is deemed to have changed if its device or inode have changed.) If the
1032file has changed, the old file stream is closed, and the file opened to get a
1033new stream.
1034
1035This handler is not appropriate for use under Windows, because under Windows
1036open log files cannot be moved or renamed - logging opens the files with
1037exclusive locks - and so there is no need for such a handler. Furthermore,
1038*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1039this value.
1040
1041
1042.. class:: WatchedFileHandler(filename[,mode[, encoding]])
1043
1044 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1045 file is opened and used as the stream for logging. If *mode* is not specified,
1046 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
1047 with that encoding. By default, the file grows indefinitely.
1048
1049
1050.. method:: WatchedFileHandler.emit(record)
1051
1052 Outputs the record to the file, but first checks to see if the file has changed.
1053 If it has, the existing stream is flushed and closed and the file opened again,
1054 before outputting the record to the file.
1055
1056
1057RotatingFileHandler
1058^^^^^^^^^^^^^^^^^^^
1059
1060The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1061module, supports rotation of disk log files.
1062
1063
1064.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount]]])
1065
1066 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1067 file is opened and used as the stream for logging. If *mode* is not specified,
1068 ``'a'`` is used. By default, the file grows indefinitely.
1069
1070 You can use the *maxBytes* and *backupCount* values to allow the file to
1071 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1072 the file is closed and a new file is silently opened for output. Rollover occurs
1073 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1074 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
1075 old log files by appending the extensions ".1", ".2" etc., to the filename. For
1076 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1077 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1078 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
1079 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1080 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
1081 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
1082
1083
1084.. method:: RotatingFileHandler.doRollover()
1085
1086 Does a rollover, as described above.
1087
1088
1089.. method:: RotatingFileHandler.emit(record)
1090
1091 Outputs the record to the file, catering for rollover as described previously.
1092
1093
1094TimedRotatingFileHandler
1095^^^^^^^^^^^^^^^^^^^^^^^^
1096
1097The :class:`TimedRotatingFileHandler` class, located in the
1098:mod:`logging.handlers` module, supports rotation of disk log files at certain
1099timed intervals.
1100
1101
1102.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])
1103
1104 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1105 specified file is opened and used as the stream for logging. On rotating it also
1106 sets the filename suffix. Rotating happens based on the product of *when* and
1107 *interval*.
1108
1109 You can use the *when* to specify the type of *interval*. The list of possible
1110 values is, note that they are not case sensitive:
1111
1112 +----------+-----------------------+
1113 | Value | Type of interval |
1114 +==========+=======================+
1115 | S | Seconds |
1116 +----------+-----------------------+
1117 | M | Minutes |
1118 +----------+-----------------------+
1119 | H | Hours |
1120 +----------+-----------------------+
1121 | D | Days |
1122 +----------+-----------------------+
1123 | W | Week day (0=Monday) |
1124 +----------+-----------------------+
1125 | midnight | Roll over at midnight |
1126 +----------+-----------------------+
1127
1128 If *backupCount* is non-zero, the system will save old log files by appending
1129 extensions to the filename. The extensions are date-and-time based, using the
1130 strftime format ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on
1131 the rollover interval. At most *backupCount* files will be kept, and if more
1132 would be created when rollover occurs, the oldest one is deleted.
1133
1134
1135.. method:: TimedRotatingFileHandler.doRollover()
1136
1137 Does a rollover, as described above.
1138
1139
1140.. method:: TimedRotatingFileHandler.emit(record)
1141
1142 Outputs the record to the file, catering for rollover as described above.
1143
1144
1145SocketHandler
1146^^^^^^^^^^^^^
1147
1148The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
1149sends logging output to a network socket. The base class uses a TCP socket.
1150
1151
1152.. class:: SocketHandler(host, port)
1153
1154 Returns a new instance of the :class:`SocketHandler` class intended to
1155 communicate with a remote machine whose address is given by *host* and *port*.
1156
1157
1158.. method:: SocketHandler.close()
1159
1160 Closes the socket.
1161
1162
1163.. method:: SocketHandler.emit()
1164
1165 Pickles the record's attribute dictionary and writes it to the socket in binary
1166 format. If there is an error with the socket, silently drops the packet. If the
1167 connection was previously lost, re-establishes the connection. To unpickle the
1168 record at the receiving end into a :class:`LogRecord`, use the
1169 :func:`makeLogRecord` function.
1170
1171
1172.. method:: SocketHandler.handleError()
1173
1174 Handles an error which has occurred during :meth:`emit`. The most likely cause
1175 is a lost connection. Closes the socket so that we can retry on the next event.
1176
1177
1178.. method:: SocketHandler.makeSocket()
1179
1180 This is a factory method which allows subclasses to define the precise type of
1181 socket they want. The default implementation creates a TCP socket
1182 (:const:`socket.SOCK_STREAM`).
1183
1184
1185.. method:: SocketHandler.makePickle(record)
1186
1187 Pickles the record's attribute dictionary in binary format with a length prefix,
1188 and returns it ready for transmission across the socket.
1189
1190
1191.. method:: SocketHandler.send(packet)
1192
1193 Send a pickled string *packet* to the socket. This function allows for partial
1194 sends which can happen when the network is busy.
1195
1196
1197DatagramHandler
1198^^^^^^^^^^^^^^^
1199
1200The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
1201module, inherits from :class:`SocketHandler` to support sending logging messages
1202over UDP sockets.
1203
1204
1205.. class:: DatagramHandler(host, port)
1206
1207 Returns a new instance of the :class:`DatagramHandler` class intended to
1208 communicate with a remote machine whose address is given by *host* and *port*.
1209
1210
1211.. method:: DatagramHandler.emit()
1212
1213 Pickles the record's attribute dictionary and writes it to the socket in binary
1214 format. If there is an error with the socket, silently drops the packet. To
1215 unpickle the record at the receiving end into a :class:`LogRecord`, use the
1216 :func:`makeLogRecord` function.
1217
1218
1219.. method:: DatagramHandler.makeSocket()
1220
1221 The factory method of :class:`SocketHandler` is here overridden to create a UDP
1222 socket (:const:`socket.SOCK_DGRAM`).
1223
1224
1225.. method:: DatagramHandler.send(s)
1226
1227 Send a pickled string to a socket.
1228
1229
1230SysLogHandler
1231^^^^^^^^^^^^^
1232
1233The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
1234supports sending logging messages to a remote or local Unix syslog.
1235
1236
1237.. class:: SysLogHandler([address[, facility]])
1238
1239 Returns a new instance of the :class:`SysLogHandler` class intended to
1240 communicate with a remote Unix machine whose address is given by *address* in
1241 the form of a ``(host, port)`` tuple. If *address* is not specified,
1242 ``('localhost', 514)`` is used. The address is used to open a UDP socket. An
1243 alternative to providing a ``(host, port)`` tuple is providing an address as a
1244 string, for example "/dev/log". In this case, a Unix domain socket is used to
1245 send the message to the syslog. If *facility* is not specified,
1246 :const:`LOG_USER` is used.
1247
1248
1249.. method:: SysLogHandler.close()
1250
1251 Closes the socket to the remote host.
1252
1253
1254.. method:: SysLogHandler.emit(record)
1255
1256 The record is formatted, and then sent to the syslog server. If exception
1257 information is present, it is *not* sent to the server.
1258
1259
1260.. method:: SysLogHandler.encodePriority(facility, priority)
1261
1262 Encodes the facility and priority into an integer. You can pass in strings or
1263 integers - if strings are passed, internal mapping dictionaries are used to
1264 convert them to integers.
1265
1266
1267NTEventLogHandler
1268^^^^^^^^^^^^^^^^^
1269
1270The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
1271module, supports sending logging messages to a local Windows NT, Windows 2000 or
1272Windows XP event log. Before you can use it, you need Mark Hammond's Win32
1273extensions for Python installed.
1274
1275
1276.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
1277
1278 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
1279 used to define the application name as it appears in the event log. An
1280 appropriate registry entry is created using this name. The *dllname* should give
1281 the fully qualified pathname of a .dll or .exe which contains message
1282 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
1283 - this is installed with the Win32 extensions and contains some basic
1284 placeholder message definitions. Note that use of these placeholders will make
1285 your event logs big, as the entire message source is held in the log. If you
1286 want slimmer logs, you have to pass in the name of your own .dll or .exe which
1287 contains the message definitions you want to use in the event log). The
1288 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
1289 defaults to ``'Application'``.
1290
1291
1292.. method:: NTEventLogHandler.close()
1293
1294 At this point, you can remove the application name from the registry as a source
1295 of event log entries. However, if you do this, you will not be able to see the
1296 events as you intended in the Event Log Viewer - it needs to be able to access
1297 the registry to get the .dll name. The current version does not do this (in fact
1298 it doesn't do anything).
1299
1300
1301.. method:: NTEventLogHandler.emit(record)
1302
1303 Determines the message ID, event category and event type, and then logs the
1304 message in the NT event log.
1305
1306
1307.. method:: NTEventLogHandler.getEventCategory(record)
1308
1309 Returns the event category for the record. Override this if you want to specify
1310 your own categories. This version returns 0.
1311
1312
1313.. method:: NTEventLogHandler.getEventType(record)
1314
1315 Returns the event type for the record. Override this if you want to specify your
1316 own types. This version does a mapping using the handler's typemap attribute,
1317 which is set up in :meth:`__init__` to a dictionary which contains mappings for
1318 :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and
1319 :const:`CRITICAL`. If you are using your own levels, you will either need to
1320 override this method or place a suitable dictionary in the handler's *typemap*
1321 attribute.
1322
1323
1324.. method:: NTEventLogHandler.getMessageID(record)
1325
1326 Returns the message ID for the record. If you are using your own messages, you
1327 could do this by having the *msg* passed to the logger being an ID rather than a
1328 format string. Then, in here, you could use a dictionary lookup to get the
1329 message ID. This version returns 1, which is the base message ID in
1330 :file:`win32service.pyd`.
1331
1332
1333SMTPHandler
1334^^^^^^^^^^^
1335
1336The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
1337supports sending logging messages to an email address via SMTP.
1338
1339
1340.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
1341
1342 Returns a new instance of the :class:`SMTPHandler` class. The instance is
1343 initialized with the from and to addresses and subject line of the email. The
1344 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
1345 the (host, port) tuple format for the *mailhost* argument. If you use a string,
1346 the standard SMTP port is used. If your SMTP server requires authentication, you
1347 can specify a (username, password) tuple for the *credentials* argument.
1348
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350.. method:: SMTPHandler.emit(record)
1351
1352 Formats the record and sends it to the specified addressees.
1353
1354
1355.. method:: SMTPHandler.getSubject(record)
1356
1357 If you want to specify a subject line which is record-dependent, override this
1358 method.
1359
1360
1361MemoryHandler
1362^^^^^^^^^^^^^
1363
1364The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
1365supports buffering of logging records in memory, periodically flushing them to a
1366:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
1367event of a certain severity or greater is seen.
1368
1369:class:`MemoryHandler` is a subclass of the more general
1370:class:`BufferingHandler`, which is an abstract class. This buffers logging
1371records in memory. Whenever each record is added to the buffer, a check is made
1372by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
1373should, then :meth:`flush` is expected to do the needful.
1374
1375
1376.. class:: BufferingHandler(capacity)
1377
1378 Initializes the handler with a buffer of the specified capacity.
1379
1380
1381.. method:: BufferingHandler.emit(record)
1382
1383 Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls
1384 :meth:`flush` to process the buffer.
1385
1386
1387.. method:: BufferingHandler.flush()
1388
1389 You can override this to implement custom flushing behavior. This version just
1390 zaps the buffer to empty.
1391
1392
1393.. method:: BufferingHandler.shouldFlush(record)
1394
1395 Returns true if the buffer is up to capacity. This method can be overridden to
1396 implement custom flushing strategies.
1397
1398
1399.. class:: MemoryHandler(capacity[, flushLevel [, target]])
1400
1401 Returns a new instance of the :class:`MemoryHandler` class. The instance is
1402 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
1403 :const:`ERROR` is used. If no *target* is specified, the target will need to be
1404 set using :meth:`setTarget` before this handler does anything useful.
1405
1406
1407.. method:: MemoryHandler.close()
1408
1409 Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer.
1410
1411
1412.. method:: MemoryHandler.flush()
1413
1414 For a :class:`MemoryHandler`, flushing means just sending the buffered records
1415 to the target, if there is one. Override if you want different behavior.
1416
1417
1418.. method:: MemoryHandler.setTarget(target)
1419
1420 Sets the target handler for this handler.
1421
1422
1423.. method:: MemoryHandler.shouldFlush(record)
1424
1425 Checks for buffer full or a record at the *flushLevel* or higher.
1426
1427
1428HTTPHandler
1429^^^^^^^^^^^
1430
1431The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
1432supports sending logging messages to a Web server, using either ``GET`` or
1433``POST`` semantics.
1434
1435
1436.. class:: HTTPHandler(host, url[, method])
1437
1438 Returns a new instance of the :class:`HTTPHandler` class. The instance is
1439 initialized with a host address, url and HTTP method. The *host* can be of the
1440 form ``host:port``, should you need to use a specific port number. If no
1441 *method* is specified, ``GET`` is used.
1442
1443
1444.. method:: HTTPHandler.emit(record)
1445
1446 Sends the record to the Web server as an URL-encoded dictionary.
1447
1448
1449Formatter Objects
1450-----------------
1451
1452:class:`Formatter`\ s have the following attributes and methods. They are
1453responsible for converting a :class:`LogRecord` to (usually) a string which can
1454be interpreted by either a human or an external system. The base
1455:class:`Formatter` allows a formatting string to be specified. If none is
1456supplied, the default value of ``'%(message)s'`` is used.
1457
1458A Formatter can be initialized with a format string which makes use of knowledge
1459of the :class:`LogRecord` attributes - such as the default value mentioned above
1460making use of the fact that the user's message and arguments are pre-formatted
1461into a :class:`LogRecord`'s *message* attribute. This format string contains
Georg Brandl4b491312007-08-31 09:22:56 +00001462standard python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00001463for more information on string formatting.
1464
1465Currently, the useful mapping keys in a :class:`LogRecord` are:
1466
1467+-------------------------+-----------------------------------------------+
1468| Format | Description |
1469+=========================+===============================================+
1470| ``%(name)s`` | Name of the logger (logging channel). |
1471+-------------------------+-----------------------------------------------+
1472| ``%(levelno)s`` | Numeric logging level for the message |
1473| | (:const:`DEBUG`, :const:`INFO`, |
1474| | :const:`WARNING`, :const:`ERROR`, |
1475| | :const:`CRITICAL`). |
1476+-------------------------+-----------------------------------------------+
1477| ``%(levelname)s`` | Text logging level for the message |
1478| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1479| | ``'ERROR'``, ``'CRITICAL'``). |
1480+-------------------------+-----------------------------------------------+
1481| ``%(pathname)s`` | Full pathname of the source file where the |
1482| | logging call was issued (if available). |
1483+-------------------------+-----------------------------------------------+
1484| ``%(filename)s`` | Filename portion of pathname. |
1485+-------------------------+-----------------------------------------------+
1486| ``%(module)s`` | Module (name portion of filename). |
1487+-------------------------+-----------------------------------------------+
1488| ``%(funcName)s`` | Name of function containing the logging call. |
1489+-------------------------+-----------------------------------------------+
1490| ``%(lineno)d`` | Source line number where the logging call was |
1491| | issued (if available). |
1492+-------------------------+-----------------------------------------------+
1493| ``%(created)f`` | Time when the :class:`LogRecord` was created |
1494| | (as returned by :func:`time.time`). |
1495+-------------------------+-----------------------------------------------+
1496| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
1497| | created, relative to the time the logging |
1498| | module was loaded. |
1499+-------------------------+-----------------------------------------------+
1500| ``%(asctime)s`` | Human-readable time when the |
1501| | :class:`LogRecord` was created. By default |
1502| | this is of the form "2003-07-08 16:49:45,896" |
1503| | (the numbers after the comma are millisecond |
1504| | portion of the time). |
1505+-------------------------+-----------------------------------------------+
1506| ``%(msecs)d`` | Millisecond portion of the time when the |
1507| | :class:`LogRecord` was created. |
1508+-------------------------+-----------------------------------------------+
1509| ``%(thread)d`` | Thread ID (if available). |
1510+-------------------------+-----------------------------------------------+
1511| ``%(threadName)s`` | Thread name (if available). |
1512+-------------------------+-----------------------------------------------+
1513| ``%(process)d`` | Process ID (if available). |
1514+-------------------------+-----------------------------------------------+
1515| ``%(message)s`` | The logged message, computed as ``msg % |
1516| | args``. |
1517+-------------------------+-----------------------------------------------+
1518
Georg Brandl116aa622007-08-15 14:28:22 +00001519
1520.. class:: Formatter([fmt[, datefmt]])
1521
1522 Returns a new instance of the :class:`Formatter` class. The instance is
1523 initialized with a format string for the message as a whole, as well as a format
1524 string for the date/time portion of a message. If no *fmt* is specified,
1525 ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
1526 is used.
1527
1528
1529.. method:: Formatter.format(record)
1530
1531 The record's attribute dictionary is used as the operand to a string formatting
1532 operation. Returns the resulting string. Before formatting the dictionary, a
1533 couple of preparatory steps are carried out. The *message* attribute of the
1534 record is computed using *msg* % *args*. If the formatting string contains
1535 ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there
1536 is exception information, it is formatted using :meth:`formatException` and
1537 appended to the message.
1538
1539
1540.. method:: Formatter.formatTime(record[, datefmt])
1541
1542 This method should be called from :meth:`format` by a formatter which wants to
1543 make use of a formatted time. This method can be overridden in formatters to
1544 provide for any specific requirement, but the basic behavior is as follows: if
1545 *datefmt* (a string) is specified, it is used with :func:`time.strftime` to
1546 format the creation time of the record. Otherwise, the ISO8601 format is used.
1547 The resulting string is returned.
1548
1549
1550.. method:: Formatter.formatException(exc_info)
1551
1552 Formats the specified exception information (a standard exception tuple as
1553 returned by :func:`sys.exc_info`) as a string. This default implementation just
1554 uses :func:`traceback.print_exception`. The resulting string is returned.
1555
1556
1557Filter Objects
1558--------------
1559
1560:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
1561more sophisticated filtering than is provided by levels. The base filter class
1562only allows events which are below a certain point in the logger hierarchy. For
1563example, a filter initialized with "A.B" will allow events logged by loggers
1564"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
1565initialized with the empty string, all events are passed.
1566
1567
1568.. class:: Filter([name])
1569
1570 Returns an instance of the :class:`Filter` class. If *name* is specified, it
1571 names a logger which, together with its children, will have its events allowed
1572 through the filter. If no name is specified, allows every event.
1573
1574
1575.. method:: Filter.filter(record)
1576
1577 Is the specified record to be logged? Returns zero for no, nonzero for yes. If
1578 deemed appropriate, the record may be modified in-place by this method.
1579
1580
1581LogRecord Objects
1582-----------------
1583
1584:class:`LogRecord` instances are created every time something is logged. They
1585contain all the information pertinent to the event being logged. The main
1586information passed in is in msg and args, which are combined using msg % args to
1587create the message field of the record. The record also includes information
1588such as when the record was created, the source line where the logging call was
1589made, and any exception information to be logged.
1590
1591
1592.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
1593
1594 Returns an instance of :class:`LogRecord` initialized with interesting
1595 information. The *name* is the logger name; *lvl* is the numeric level;
1596 *pathname* is the absolute pathname of the source file in which the logging
1597 call was made; *lineno* is the line number in that file where the logging
1598 call is found; *msg* is the user-supplied message (a format string); *args*
1599 is the tuple which, together with *msg*, makes up the user message; and
1600 *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
1601 (or :const:`None`, if no exception information is available). The *func* is
1602 the name of the function from which the logging call was made. If not
1603 specified, it defaults to ``None``.
1604
Georg Brandl116aa622007-08-15 14:28:22 +00001605
1606.. method:: LogRecord.getMessage()
1607
1608 Returns the message for this :class:`LogRecord` instance after merging any
1609 user-supplied arguments with the message.
1610
1611
1612Thread Safety
1613-------------
1614
1615The logging module is intended to be thread-safe without any special work
1616needing to be done by its clients. It achieves this though using threading
1617locks; there is one lock to serialize access to the module's shared data, and
1618each handler also creates a lock to serialize access to its underlying I/O.
1619
1620
1621Configuration
1622-------------
1623
1624
1625.. _logging-config-api:
1626
1627Configuration functions
1628^^^^^^^^^^^^^^^^^^^^^^^
1629
1630.. %
1631
1632The following functions configure the logging module. They are located in the
1633:mod:`logging.config` module. Their use is optional --- you can configure the
1634logging module using these functions or by making calls to the main API (defined
1635in :mod:`logging` itself) and defining handlers which are declared either in
1636:mod:`logging` or :mod:`logging.handlers`.
1637
1638
1639.. function:: fileConfig(fname[, defaults])
1640
1641 Reads the logging configuration from a ConfigParser-format file named *fname*.
1642 This function can be called several times from an application, allowing an end
1643 user the ability to select from various pre-canned configurations (if the
1644 developer provides a mechanism to present the choices and load the chosen
1645 configuration). Defaults to be passed to ConfigParser can be specified in the
1646 *defaults* argument.
1647
1648
1649.. function:: listen([port])
1650
1651 Starts up a socket server on the specified port, and listens for new
1652 configurations. If no port is specified, the module's default
1653 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
1654 sent as a file suitable for processing by :func:`fileConfig`. Returns a
1655 :class:`Thread` instance on which you can call :meth:`start` to start the
1656 server, and which you can :meth:`join` when appropriate. To stop the server,
1657 call :func:`stopListening`. To send a configuration to the socket, read in the
1658 configuration file and send it to the socket as a string of bytes preceded by a
1659 four-byte length packed in binary using struct.\ ``pack('>L', n)``.
1660
1661
1662.. function:: stopListening()
1663
1664 Stops the listening server which was created with a call to :func:`listen`. This
1665 is typically called before calling :meth:`join` on the return value from
1666 :func:`listen`.
1667
1668
1669.. _logging-config-fileformat:
1670
1671Configuration file format
1672^^^^^^^^^^^^^^^^^^^^^^^^^
1673
1674.. %
1675
1676The configuration file format understood by :func:`fileConfig` is based on
1677ConfigParser functionality. The file must contain sections called ``[loggers]``,
1678``[handlers]`` and ``[formatters]`` which identify by name the entities of each
1679type which are defined in the file. For each such entity, there is a separate
1680section which identified how that entity is configured. Thus, for a logger named
1681``log01`` in the ``[loggers]`` section, the relevant configuration details are
1682held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
1683the ``[handlers]`` section will have its configuration held in a section called
1684``[handler_hand01]``, while a formatter called ``form01`` in the
1685``[formatters]`` section will have its configuration specified in a section
1686called ``[formatter_form01]``. The root logger configuration must be specified
1687in a section called ``[logger_root]``.
1688
1689Examples of these sections in the file are given below. ::
1690
1691 [loggers]
1692 keys=root,log02,log03,log04,log05,log06,log07
1693
1694 [handlers]
1695 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1696
1697 [formatters]
1698 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
1699
1700The root logger must specify a level and a list of handlers. An example of a
1701root logger section is given below. ::
1702
1703 [logger_root]
1704 level=NOTSET
1705 handlers=hand01
1706
1707The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
1708``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
1709logged. Level values are :func:`eval`\ uated in the context of the ``logging``
1710package's namespace.
1711
1712The ``handlers`` entry is a comma-separated list of handler names, which must
1713appear in the ``[handlers]`` section. These names must appear in the
1714``[handlers]`` section and have corresponding sections in the configuration
1715file.
1716
1717For loggers other than the root logger, some additional information is required.
1718This is illustrated by the following example. ::
1719
1720 [logger_parser]
1721 level=DEBUG
1722 handlers=hand01
1723 propagate=1
1724 qualname=compiler.parser
1725
1726The ``level`` and ``handlers`` entries are interpreted as for the root logger,
1727except that if a non-root logger's level is specified as ``NOTSET``, the system
1728consults loggers higher up the hierarchy to determine the effective level of the
1729logger. The ``propagate`` entry is set to 1 to indicate that messages must
1730propagate to handlers higher up the logger hierarchy from this logger, or 0 to
1731indicate that messages are **not** propagated to handlers up the hierarchy. The
1732``qualname`` entry is the hierarchical channel name of the logger, that is to
1733say the name used by the application to get the logger.
1734
1735Sections which specify handler configuration are exemplified by the following.
1736::
1737
1738 [handler_hand01]
1739 class=StreamHandler
1740 level=NOTSET
1741 formatter=form01
1742 args=(sys.stdout,)
1743
1744The ``class`` entry indicates the handler's class (as determined by :func:`eval`
1745in the ``logging`` package's namespace). The ``level`` is interpreted as for
1746loggers, and ``NOTSET`` is taken to mean "log everything".
1747
1748The ``formatter`` entry indicates the key name of the formatter for this
1749handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
1750If a name is specified, it must appear in the ``[formatters]`` section and have
1751a corresponding section in the configuration file.
1752
1753The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
1754package's namespace, is the list of arguments to the constructor for the handler
1755class. Refer to the constructors for the relevant handlers, or to the examples
1756below, to see how typical entries are constructed. ::
1757
1758 [handler_hand02]
1759 class=FileHandler
1760 level=DEBUG
1761 formatter=form02
1762 args=('python.log', 'w')
1763
1764 [handler_hand03]
1765 class=handlers.SocketHandler
1766 level=INFO
1767 formatter=form03
1768 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1769
1770 [handler_hand04]
1771 class=handlers.DatagramHandler
1772 level=WARN
1773 formatter=form04
1774 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1775
1776 [handler_hand05]
1777 class=handlers.SysLogHandler
1778 level=ERROR
1779 formatter=form05
1780 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1781
1782 [handler_hand06]
1783 class=handlers.NTEventLogHandler
1784 level=CRITICAL
1785 formatter=form06
1786 args=('Python Application', '', 'Application')
1787
1788 [handler_hand07]
1789 class=handlers.SMTPHandler
1790 level=WARN
1791 formatter=form07
1792 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1793
1794 [handler_hand08]
1795 class=handlers.MemoryHandler
1796 level=NOTSET
1797 formatter=form08
1798 target=
1799 args=(10, ERROR)
1800
1801 [handler_hand09]
1802 class=handlers.HTTPHandler
1803 level=NOTSET
1804 formatter=form09
1805 args=('localhost:9022', '/log', 'GET')
1806
1807Sections which specify formatter configuration are typified by the following. ::
1808
1809 [formatter_form01]
1810 format=F1 %(asctime)s %(levelname)s %(message)s
1811 datefmt=
1812 class=logging.Formatter
1813
1814The ``format`` entry is the overall format string, and the ``datefmt`` entry is
1815the :func:`strftime`\ -compatible date/time format string. If empty, the package
1816substitutes ISO8601 format date/times, which is almost equivalent to specifying
1817the date format string "The ISO8601 format also specifies milliseconds, which
1818are appended to the result of using the above format string, with a comma
1819separator. An example time in ISO8601 format is ``2003-01-23 00:29:50,411``.
1820
1821.. % Y-%m-%d %H:%M:%S".
1822
1823The ``class`` entry is optional. It indicates the name of the formatter's class
1824(as a dotted module and class name.) This option is useful for instantiating a
1825:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
1826exception tracebacks in an expanded or condensed format.
1827