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