Debian Codegraph @

Doc/library/logging.rst

raw
1 :mod:`!logging` --- Logging facility for Python
2 ===============================================
3
4 .. module:: logging
5 :synopsis: Flexible event logging system for applications.
6
7 .. moduleauthor:: Vinay Sajip <[email protected]>
8 .. sectionauthor:: Vinay Sajip <[email protected]>
9
10 **Source code:** :source:`Lib/logging/__init__.py`
11
12 .. index:: pair: Errors; logging
13
14 .. sidebar:: Important
15
16 This page contains the API reference information. For tutorial
17 information and discussion of more advanced topics, see
18
19 * :ref:`Basic Tutorial <logging-basic-tutorial>`
20 * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
21 * :ref:`Logging Cookbook <logging-cookbook>`
22
23 --------------
24
25 This module defines functions and classes which implement a flexible event
26 logging system for applications and libraries.
27
28 The key benefit of having the logging API provided by a standard library module
29 is that all Python modules can participate in logging, so your application log
30 can include your own messages integrated with messages from third-party
31 modules.
32
33 Here's a simple example of idiomatic usage: ::
34
35 # myapp.py
36 import logging
37 import mylib
38 logger = logging.getLogger(__name__)
39
40 def main():
41 logging.basicConfig(filename='myapp.log', level=logging.INFO)
42 logger.info('Started')
43 mylib.do_something()
44 logger.info('Finished')
45
46 if __name__ == '__main__':
47 main()
48
49 ::
50
51 # mylib.py
52 import logging
53 logger = logging.getLogger(__name__)
54
55 def do_something():
56 logger.info('Doing something')
57
58 If you run *myapp.py*, you should see this in *myapp.log*:
59
60 .. code-block:: none
61
62 INFO:__main__:Started
63 INFO:mylib:Doing something
64 INFO:__main__:Finished
65
66 The key feature of this idiomatic usage is that the majority of code is simply
67 creating a module level logger with ``getLogger(__name__)``, and using that
68 logger to do any needed logging. This is concise, while allowing downstream
69 code fine-grained control if needed. Logged messages to the module-level logger
70 get forwarded to handlers of loggers in higher-level modules, all the way up to
71 the highest-level logger known as the root logger; this approach is known as
72 hierarchical logging.
73
74 For logging to be useful, it needs to be configured: setting the levels and
75 destinations for each logger, potentially changing how specific modules log,
76 often based on command-line arguments or application configuration. In most
77 cases, like the one above, only the root logger needs to be so configured, since
78 all the lower level loggers at module level eventually forward their messages to
79 its handlers. :func:`~logging.basicConfig` provides a quick way to configure
80 the root logger that handles many use cases.
81
82 The module provides a lot of functionality and flexibility. If you are
83 unfamiliar with logging, the best way to get to grips with it is to view the
84 tutorials (**see the links above and on the right**).
85
86 The basic classes defined by the module, together with their attributes and
87 methods, are listed in the sections below.
88
89 * Loggers expose the interface that application code directly uses.
90 * Handlers send the log records (created by loggers) to the appropriate
91 destination.
92 * Filters provide a finer grained facility for determining which log records
93 to output.
94 * Formatters specify the layout of log records in the final output.
95
96
97 .. _logger:
98
99 Logger Objects
100 --------------
101
102 Loggers have the following attributes and methods. Note that Loggers should
103 *NEVER* be instantiated directly, but always through the module-level function
104 ``logging.getLogger(name)``. Multiple calls to :func:`getLogger` with the same
105 name will always return a reference to the same Logger object.
106
107 The ``name`` is potentially a period-separated hierarchical value, like
108 ``foo.bar.baz`` (though it could also be just plain ``foo``, for example).
109 Loggers that are further down in the hierarchical list are children of loggers
110 higher up in the list. For example, given a logger with a name of ``foo``,
111 loggers with names of ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all
112 descendants of ``foo``. In addition, all loggers are descendants of the root
113 logger. The logger name hierarchy is analogous to the Python package hierarchy,
114 and identical to it if you organise your loggers on a per-module basis using
115 the recommended construction ``logging.getLogger(__name__)``. That's because
116 in a module, ``__name__`` is the module's name in the Python package namespace.
117
118
119 .. class:: Logger
120
121 .. attribute:: Logger.name
122
123 This is the logger's name, and is the value that was passed to :func:`getLogger`
124 to obtain the logger.
125
126 .. note:: This attribute should be treated as read-only.
127
128 .. attribute:: Logger.level
129
130 The threshold of this logger, as set by the :meth:`setLevel` method.
131
132 .. note:: Do not set this attribute directly - always use :meth:`setLevel`,
133 which has checks for the level passed to it.
134
135 .. attribute:: Logger.parent
136
137 The parent logger of this logger. It may change based on later instantiation
138 of loggers which are higher up in the namespace hierarchy.
139
140 .. note:: This value should be treated as read-only.
141
142 .. attribute:: Logger.propagate
143
144 If this attribute evaluates to true, events logged to this logger will be
145 passed to the handlers of higher level (ancestor) loggers, in addition to
146 any handlers attached to this logger. Messages are passed directly to the
147 ancestor loggers' handlers - neither the level nor filters of the ancestor
148 loggers in question are considered.
149
150 If this evaluates to false, logging messages are not passed to the handlers
151 of ancestor loggers.
152
153 Spelling it out with an example: If the propagate attribute of the logger named
154 ``A.B.C`` evaluates to true, any event logged to ``A.B.C`` via a method call such as
155 ``logging.getLogger('A.B.C').error(...)`` will [subject to passing that logger's
156 level and filter settings] be passed in turn to any handlers attached to loggers
157 named ``A.B``, ``A`` and the root logger, after first being passed to any handlers
158 attached to ``A.B.C``. If any logger in the chain ``A.B.C``, ``A.B``, ``A`` has its
159 ``propagate`` attribute set to false, then that is the last logger whose handlers
160 are offered the event to handle, and propagation stops at that point.
161
162 The constructor sets this attribute to ``True``.
163
164 .. note:: If you attach a handler to a logger *and* one or more of its
165 ancestors, it may emit the same record multiple times. In general, you
166 should not need to attach a handler to more than one logger - if you just
167 attach it to the appropriate logger which is highest in the logger
168 hierarchy, then it will see all events logged by all descendant loggers,
169 provided that their propagate setting is left set to ``True``. A common
170 scenario is to attach handlers only to the root logger, and to let
171 propagation take care of the rest.
172
173 .. attribute:: Logger.handlers
174
175 The list of handlers directly attached to this logger instance.
176
177 .. note:: This attribute should be treated as read-only; it is normally changed via
178 the :meth:`addHandler` and :meth:`removeHandler` methods, which use locks to ensure
179 thread-safe operation.
180
181 .. attribute:: Logger.disabled
182
183 This attribute disables handling of any events. It is set to ``False`` in the
184 initializer, and only changed by logging configuration code.
185
186 .. note:: This attribute should be treated as read-only.
187
188 .. method:: Logger.setLevel(level)
189
190 Sets the threshold for this logger to *level*. Logging messages which are less
191 severe than *level* will be ignored; logging messages which have severity *level*
192 or higher will be emitted by whichever handler or handlers service this logger,
193 unless a handler's level has been set to a higher severity level than *level*.
194
195 When a logger is created, the level is set to :const:`NOTSET` (which causes
196 all messages to be processed when the logger is the root logger, or delegation
197 to the parent when the logger is a non-root logger). Note that the root logger
198 is created with level :const:`WARNING`.
199
200 The term 'delegation to the parent' means that if a logger has a level of
201 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
202 a level other than NOTSET is found, or the root is reached.
203
204 If an ancestor is found with a level other than NOTSET, then that ancestor's
205 level is treated as the effective level of the logger where the ancestor search
206 began, and is used to determine how a logging event is handled.
207
208 If the root is reached, and it has a level of NOTSET, then all messages will be
209 processed. Otherwise, the root's level will be used as the effective level.
210
211 See :ref:`levels` for a list of levels.
212
213 .. versionchanged:: 3.2
214 The *level* parameter now accepts a string representation of the
215 level such as 'INFO' as an alternative to the integer constants
216 such as :const:`INFO`. Note, however, that levels are internally stored
217 as integers, and methods such as e.g. :meth:`getEffectiveLevel` and
218 :meth:`isEnabledFor` will return/expect to be passed integers.
219
220
221 .. method:: Logger.isEnabledFor(level)
222
223 Indicates if a message of severity *level* would be processed by this logger.
224 This method checks first the module-level level set by
225 ``logging.disable(level)`` and then the logger's effective level as determined
226 by :meth:`getEffectiveLevel`.
227
228
229 .. method:: Logger.getEffectiveLevel()
230
231 Indicates the effective level for this logger. If a value other than
232 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
233 the hierarchy is traversed towards the root until a value other than
234 :const:`NOTSET` is found, and that value is returned. The value returned is
235 an integer, typically one of :const:`logging.DEBUG`, :const:`logging.INFO`
236 etc.
237
238
239 .. method:: Logger.getChild(suffix)
240
241 Returns a logger which is a descendant to this logger, as determined by the suffix.
242 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
243 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
244 convenience method, useful when the parent logger is named using e.g. ``__name__``
245 rather than a literal string.
246
247 .. versionadded:: 3.2
248
249
250 .. method:: Logger.getChildren()
251
252 Returns a set of loggers which are immediate children of this logger. So for
253 example ``logging.getLogger().getChildren()`` might return a set containing
254 loggers named ``foo`` and ``bar``, but a logger named ``foo.bar`` wouldn't be
255 included in the set. Likewise, ``logging.getLogger('foo').getChildren()`` might
256 return a set including a logger named ``foo.bar``, but it wouldn't include one
257 named ``foo.bar.baz``.
258
259 .. versionadded:: 3.12
260
261
262 .. method:: Logger.debug(msg, *args, **kwargs)
263
264 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
265 message format string, and the *args* are the arguments which are merged into
266 *msg* using the string formatting operator. (Note that this means that you can
267 use keywords in the format string, together with a single dictionary argument.)
268 No % formatting operation is performed on *msg* when no *args* are supplied.
269
270 There are four keyword arguments in *kwargs* which are inspected:
271 *exc_info*, *stack_info*, *stacklevel* and *extra*.
272
273 If *exc_info* does not evaluate as false, it causes exception information to be
274 added to the logging message. If an exception tuple (in the format returned by
275 :func:`sys.exc_info`) or an exception instance is provided, it is used;
276 otherwise, :func:`sys.exc_info` is called to get the exception information.
277
278 The second optional keyword argument is *stack_info*, which defaults to
279 ``False``. If true, stack information is added to the logging
280 message, including the actual logging call. Note that this is not the same
281 stack information as that displayed through specifying *exc_info*: The
282 former is stack frames from the bottom of the stack up to the logging call
283 in the current thread, whereas the latter is information about stack frames
284 which have been unwound, following an exception, while searching for
285 exception handlers.
286
287 You can specify *stack_info* independently of *exc_info*, e.g. to just show
288 how you got to a certain point in your code, even when no exceptions were
289 raised. The stack frames are printed following a header line which says:
290
291 .. code-block:: none
292
293 Stack (most recent call last):
294
295 This mimics the ``Traceback (most recent call last):`` which is used when
296 displaying exception frames.
297
298 The third optional keyword argument is *stacklevel*, which defaults to ``1``.
299 If greater than 1, the corresponding number of stack frames are skipped
300 when computing the line number and function name set in the :class:`LogRecord`
301 created for the logging event. This can be used in logging helpers so that
302 the function name, filename and line number recorded are not the information
303 for the helper function/method, but rather its caller. The name of this
304 parameter mirrors the equivalent one in the :mod:`warnings` module.
305
306 The fourth keyword argument is *extra* which can be used to pass a
307 dictionary which is used to populate the :attr:`~object.__dict__` of the
308 :class:`LogRecord`
309 created for the logging event with user-defined attributes. These custom
310 attributes can then be used as you like. For example, they could be
311 incorporated into logged messages. For example::
312
313 FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
314 logging.basicConfig(format=FORMAT)
315 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
316 logger = logging.getLogger('tcpserver')
317 logger.warning('Protocol problem: %s', 'connection reset', extra=d)
318
319 would print something like
320
321 .. code-block:: none
322
323 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
324
325 The keys in the dictionary passed in *extra* should not clash with the keys used
326 by the logging system. (See the section on :ref:`logrecord-attributes` for more
327 information on which keys are used by the logging system.)
328
329 If you choose to use these attributes in logged messages, you need to exercise
330 some care. In the above example, for instance, the :class:`Formatter` has been
331 set up with a format string which expects 'clientip' and 'user' in the attribute
332 dictionary of the :class:`LogRecord`. If these are missing, the message will
333 not be logged because a string formatting exception will occur. So in this case,
334 you always need to pass the *extra* dictionary with these keys.
335
336 While this might be annoying, this feature is intended for use in specialized
337 circumstances, such as multi-threaded servers where the same code executes in
338 many contexts, and interesting conditions which arise are dependent on this
339 context (such as remote client IP address and authenticated user name, in the
340 above example). In such circumstances, it is likely that specialized
341 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
342
343 If no handler is attached to this logger (or any of its ancestors,
344 taking into account the relevant :attr:`Logger.propagate` attributes),
345 the message will be sent to the handler set on :data:`lastResort`.
346
347 .. versionchanged:: 3.2
348 The *stack_info* parameter was added.
349
350 .. versionchanged:: 3.5
351 The *exc_info* parameter can now accept exception instances.
352
353 .. versionchanged:: 3.8
354 The *stacklevel* parameter was added.
355
356
357 .. method:: Logger.info(msg, *args, **kwargs)
358
359 Logs a message with level :const:`INFO` on this logger. The arguments are
360 interpreted as for :meth:`debug`.
361
362
363 .. method:: Logger.warning(msg, *args, **kwargs)
364
365 Logs a message with level :const:`WARNING` on this logger. The arguments are
366 interpreted as for :meth:`debug`.
367
368 .. note:: There is an obsolete method ``warn`` which is functionally
369 identical to ``warning``. As ``warn`` is deprecated, please do not use
370 it - use ``warning`` instead.
371
372 .. method:: Logger.error(msg, *args, **kwargs)
373
374 Logs a message with level :const:`ERROR` on this logger. The arguments are
375 interpreted as for :meth:`debug`.
376
377
378 .. method:: Logger.critical(msg, *args, **kwargs)
379
380 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
381 interpreted as for :meth:`debug`.
382
383
384 .. method:: Logger.log(level, msg, *args, **kwargs)
385
386 Logs a message with integer level *level* on this logger. The other arguments are
387 interpreted as for :meth:`debug`.
388
389
390 .. method:: Logger.exception(msg, *args, **kwargs)
391
392 Logs a message with level :const:`ERROR` on this logger. The arguments are
393 interpreted as for :meth:`debug`. Exception info is added to the logging
394 message. This method should only be called from an exception handler.
395
396
397 .. method:: Logger.addFilter(filter)
398
399 Adds the specified filter *filter* to this logger.
400
401
402 .. method:: Logger.removeFilter(filter)
403
404 Removes the specified filter *filter* from this logger.
405
406
407 .. method:: Logger.filter(record)
408
409 Apply this logger's filters to the record and return ``True`` if the
410 record is to be processed. The filters are consulted in turn, until one of
411 them returns a false value. If none of them return a false value, the record
412 will be processed (passed to handlers). If one returns a false value, no
413 further processing of the record occurs.
414
415
416 .. method:: Logger.addHandler(hdlr)
417
418 Adds the specified handler *hdlr* to this logger.
419
420
421 .. method:: Logger.removeHandler(hdlr)
422
423 Removes the specified handler *hdlr* from this logger.
424
425
426 .. method:: Logger.findCaller(stack_info=False, stacklevel=1)
427
428 Finds the caller's source filename and line number. Returns the filename, line
429 number, function name and stack information as a 4-element tuple. The stack
430 information is returned as ``None`` unless *stack_info* is ``True``.
431
432 The *stacklevel* parameter is passed from code calling the :meth:`debug`
433 and other APIs. If greater than 1, the excess is used to skip stack frames
434 before determining the values to be returned. This will generally be useful
435 when calling logging APIs from helper/wrapper code, so that the information
436 in the event log refers not to the helper/wrapper code, but to the code that
437 calls it.
438
439
440 .. method:: Logger.handle(record)
441
442 Handles a record by passing it to all handlers associated with this logger and
443 its ancestors (until a false value of *propagate* is found). This method is used
444 for unpickled records received from a socket, as well as those created locally.
445 Logger-level filtering is applied using :meth:`~Logger.filter`.
446
447
448 .. method:: Logger.makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
449
450 This is a factory method which can be overridden in subclasses to create
451 specialized :class:`LogRecord` instances.
452
453 .. method:: Logger.hasHandlers()
454
455 Checks to see if this logger has any handlers configured. This is done by
456 looking for handlers in this logger and its parents in the logger hierarchy.
457 Returns ``True`` if a handler was found, else ``False``. The method stops searching
458 up the hierarchy whenever a logger with the 'propagate' attribute set to
459 false is found - that will be the last logger which is checked for the
460 existence of handlers.
461
462 .. versionadded:: 3.2
463
464 .. versionchanged:: 3.7
465 Loggers can now be pickled and unpickled.
466
467 .. _levels:
468
469 Logging Levels
470 --------------
471
472 The numeric values of logging levels are given in the following table. These are
473 primarily of interest if you want to define your own levels, and need them to
474 have specific values relative to the predefined levels. If you define a level
475 with the same numeric value, it overwrites the predefined value; the predefined
476 name is lost.
477
478 +-----------------------+---------------+-------------------------------------+
479 | Level | Numeric value | What it means / When to use it |
480 +=======================+===============+=====================================+
481 | .. py:data:: NOTSET | 0 | When set on a logger, indicates that|
482 | | | ancestor loggers are to be consulted|
483 | | | to determine the effective level. |
484 | | | If that still resolves to |
485 | | | :const:`!NOTSET`, then all events |
486 | | | are logged. When set on a handler, |
487 | | | all events are handled. |
488 +-----------------------+---------------+-------------------------------------+
489 | .. py:data:: DEBUG | 10 | Detailed information, typically only|
490 | | | of interest to a developer trying to|
491 | | | diagnose a problem. |
492 +-----------------------+---------------+-------------------------------------+
493 | .. py:data:: INFO | 20 | Confirmation that things are working|
494 | | | as expected. |
495 +-----------------------+---------------+-------------------------------------+
496 | .. py:data:: WARNING | 30 | An indication that something |
497 | | | unexpected happened, or that a |
498 | | | problem might occur in the near |
499 | | | future (e.g. 'disk space low'). The |
500 | | | software is still working as |
501 | | | expected. |
502 +-----------------------+---------------+-------------------------------------+
503 | .. py:data:: ERROR | 40 | Due to a more serious problem, the |
504 | | | software has not been able to |
505 | | | perform some function. |
506 +-----------------------+---------------+-------------------------------------+
507 | .. py:data:: CRITICAL | 50 | A serious error, indicating that the|
508 | | | program itself may be unable to |
509 | | | continue running. |
510 +-----------------------+---------------+-------------------------------------+
511
512
513 .. _handler:
514
515 Handler Objects
516 ---------------
517
518 Handlers have the following attributes and methods. Note that :class:`Handler`
519 is never instantiated directly; this class acts as a base for more useful
520 subclasses. However, the :meth:`!__init__` method in subclasses needs to call
521 :meth:`Handler.__init__`.
522
523 .. class:: Handler
524
525 .. method:: Handler.__init__(level=NOTSET)
526
527 Initializes the :class:`Handler` instance by setting its level, setting the list
528 of filters to the empty list and creating a lock (using :meth:`createLock`) for
529 serializing access to an I/O mechanism.
530
531
532 .. method:: Handler.createLock()
533
534 Initializes a thread lock which can be used to serialize access to underlying
535 I/O functionality which may not be threadsafe.
536
537
538 .. method:: Handler.acquire()
539
540 Acquires the thread lock created with :meth:`createLock`.
541
542
543 .. method:: Handler.release()
544
545 Releases the thread lock acquired with :meth:`acquire`.
546
547
548 .. method:: Handler.setLevel(level)
549
550 Sets the threshold for this handler to *level*. Logging messages which are
551 less severe than *level* will be ignored. When a handler is created, the
552 level is set to :const:`NOTSET` (which causes all messages to be
553 processed).
554
555 See :ref:`levels` for a list of levels.
556
557 .. versionchanged:: 3.2
558 The *level* parameter now accepts a string representation of the
559 level such as 'INFO' as an alternative to the integer constants
560 such as :const:`INFO`.
561
562
563 .. method:: Handler.setFormatter(fmt)
564
565 Sets the formatter for this handler to *fmt*.
566 The *fmt* argument must be a :class:`Formatter` instance or ``None``.
567
568
569 .. method:: Handler.addFilter(filter)
570
571 Adds the specified filter *filter* to this handler.
572
573
574 .. method:: Handler.removeFilter(filter)
575
576 Removes the specified filter *filter* from this handler.
577
578
579 .. method:: Handler.filter(record)
580
581 Apply this handler's filters to the record and return ``True`` if the
582 record is to be processed. The filters are consulted in turn, until one of
583 them returns a false value. If none of them return a false value, the record
584 will be emitted. If one returns a false value, the handler will not emit the
585 record.
586
587
588 .. method:: Handler.flush()
589
590 Ensure all logging output has been flushed. This version does nothing and is
591 intended to be implemented by subclasses.
592
593
594 .. method:: Handler.close()
595
596 Tidy up any resources used by the handler. This version does no output
597 but removes the handler from an internal map of handlers, which is used
598 for handler lookup by name.
599
600 Subclasses should ensure that this gets called from overridden :meth:`close`
601 methods.
602
603
604 .. method:: Handler.handle(record)
605
606 Conditionally emits the specified logging record, depending on filters which may
607 have been added to the handler. Wraps the actual emission of the record with
608 acquisition/release of the I/O thread lock.
609
610
611 .. method:: Handler.handleError(record)
612
613 This method should be called from handlers when an exception is encountered
614 during an :meth:`emit` call. If the module-level attribute
615 :data:`raiseExceptions` is ``False``, exceptions get silently ignored. This is
616 what is mostly wanted for a logging system - most users will not care about
617 errors in the logging system, they are more interested in application
618 errors. You could, however, replace this with a custom handler if you wish.
619 The specified record is the one which was being processed when the exception
620 occurred. (The default value of :data:`raiseExceptions` is ``True``, as that is
621 more useful during development).
622
623
624 .. method:: Handler.format(record)
625
626 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
627 default formatter for the module.
628
629
630 .. method:: Handler.emit(record)
631
632 Do whatever it takes to actually log the specified logging record. This version
633 is intended to be implemented by subclasses and so raises a
634 :exc:`NotImplementedError`.
635
636 .. warning:: This method is called after a handler-level lock is acquired, which
637 is released after this method returns. When you override this method, note
638 that you should be careful when calling anything that invokes other parts of
639 the logging API which might do locking, because that might result in a
640 deadlock. Specifically:
641
642 * Logging configuration APIs acquire the module-level lock, and then
643 individual handler-level locks as those handlers are configured.
644
645 * Many logging APIs lock the module-level lock. If such an API is called
646 from this method, it could cause a deadlock if a configuration call is
647 made on another thread, because that thread will try to acquire the
648 module-level lock *before* the handler-level lock, whereas this thread
649 tries to acquire the module-level lock *after* the handler-level lock
650 (because in this method, the handler-level lock has already been acquired).
651
652 For a list of handlers included as standard, see :mod:`logging.handlers`.
653
654 .. _formatter-objects:
655
656 Formatter Objects
657 -----------------
658
659 .. currentmodule:: logging
660
661 .. class:: Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)
662
663 Responsible for converting a :class:`LogRecord` to an output string
664 to be interpreted by a human or external system.
665
666 :param fmt: A format string in the given *style* for
667 the logged output as a whole.
668 The possible mapping keys are drawn from the :class:`LogRecord` object's
669 :ref:`logrecord-attributes`.
670 If not specified, ``'%(message)s'`` is used,
671 which is just the logged message.
672 :type fmt: str
673
674 :param datefmt: A format string for the date/time portion of the logged output.
675 If not specified, the default described in :meth:`formatTime` is used.
676 :type datefmt: str
677
678 :param style: Can be one of ``'%'``, ``'{'`` or ``'$'`` and determines
679 how the format string will be merged with its data: using one of
680 :ref:`old-string-formatting` (``%``), :meth:`str.format` (``{``)
681 or :class:`string.Template` (``$``). This only applies to
682 *fmt* (e.g. ``'%(message)s'`` versus ``'{message}'``),
683 not to the actual log messages passed to the logging methods.
684 However, there are :ref:`other ways <formatting-styles>`
685 to use ``{``- and ``$``-formatting for log messages.
686 :type style: str
687
688 :param validate: If ``True`` (the default), incorrect or mismatched
689 *fmt* and *style* will raise a :exc:`ValueError`; for example,
690 ``logging.Formatter('%(asctime)s - %(message)s', style='{')``.
691 :type validate: bool
692
693 :param defaults: A dictionary with default values to use in custom fields.
694 For example,
695 ``logging.Formatter('%(ip)s %(message)s', defaults={"ip": None})``
696 :type defaults: dict[str, Any]
697
698 .. versionchanged:: 3.2
699 Added the *style* parameter.
700
701 .. versionchanged:: 3.8
702 Added the *validate* parameter.
703
704 .. versionchanged:: 3.10
705 Added the *defaults* parameter.
706
707
708 .. method:: format(record)
709
710 The record's attribute dictionary is used as the operand to a string
711 formatting operation. Returns the resulting string. Before formatting the
712 dictionary, a couple of preparatory steps are carried out. The *message*
713 attribute of the record is computed using *msg* % *args*. If the
714 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
715 to format the event time. If there is exception information, it is
716 formatted using :meth:`formatException` and appended to the message. Note
717 that the formatted exception information is cached in attribute
718 *exc_text*. This is useful because the exception information can be
719 pickled and sent across the wire, but you should be careful if you have
720 more than one :class:`Formatter` subclass which customizes the formatting
721 of exception information. In this case, you will have to clear the cached
722 value (by setting the *exc_text* attribute to ``None``) after a formatter
723 has done its formatting, so that the next formatter to handle the event
724 doesn't use the cached value, but recalculates it afresh.
725
726 If stack information is available, it's appended after the exception
727 information, using :meth:`formatStack` to transform it if necessary.
728
729
730 .. method:: formatTime(record, datefmt=None)
731
732 This method should be called from :meth:`format` by a formatter which
733 wants to make use of a formatted time. This method can be overridden in
734 formatters to provide for any specific requirement, but the basic behavior
735 is as follows: if *datefmt* (a string) is specified, it is used with
736 :func:`time.strftime` to format the creation time of the
737 record. Otherwise, the format '%Y-%m-%d %H:%M:%S,uuu' is used, where the
738 uuu part is a millisecond value and the other letters are as per the
739 :func:`time.strftime` documentation. An example time in this format is
740 ``2003-01-23 00:29:50,411``. The resulting string is returned.
741
742 This function uses a user-configurable function to convert the creation
743 time to a tuple. By default, :func:`time.localtime` is used; to change
744 this for a particular formatter instance, set the ``converter`` attribute
745 to a function with the same signature as :func:`time.localtime` or
746 :func:`time.gmtime`. To change it for all formatters, for example if you
747 want all logging times to be shown in GMT, set the ``converter``
748 attribute in the ``Formatter`` class.
749
750 .. versionchanged:: 3.3
751 Previously, the default format was hard-coded as in this example:
752 ``2010-09-06 22:38:15,292`` where the part before the comma is
753 handled by a strptime format string (``'%Y-%m-%d %H:%M:%S'``), and the
754 part after the comma is a millisecond value. Because strptime does not
755 have a format placeholder for milliseconds, the millisecond value is
756 appended using another format string, ``'%s,%03d'`` --- and both of these
757 format strings have been hardcoded into this method. With the change,
758 these strings are defined as class-level attributes which can be
759 overridden at the instance level when desired. The names of the
760 attributes are ``default_time_format`` (for the strptime format string)
761 and ``default_msec_format`` (for appending the millisecond value).
762
763 .. versionchanged:: 3.9
764 The ``default_msec_format`` can be ``None``.
765
766 .. method:: formatException(exc_info)
767
768 Formats the specified exception information (a standard exception tuple as
769 returned by :func:`sys.exc_info`) as a string. This default implementation
770 just uses :func:`traceback.print_exception`. The resulting string is
771 returned.
772
773 .. method:: formatStack(stack_info)
774
775 Formats the specified stack information (a string as returned by
776 :func:`traceback.print_stack`, but with the last newline removed) as a
777 string. This default implementation just returns the input value.
778
779 .. class:: BufferingFormatter(linefmt=None)
780
781 A base formatter class suitable for subclassing when you want to format a
782 number of records. You can pass a :class:`Formatter` instance which you want
783 to use to format each line (that corresponds to a single record). If not
784 specified, the default formatter (which just outputs the event message) is
785 used as the line formatter.
786
787 .. method:: formatHeader(records)
788
789 Return a header for a list of *records*. The base implementation just
790 returns the empty string. You will need to override this method if you
791 want specific behaviour, e.g. to show the count of records, a title or a
792 separator line.
793
794 .. method:: formatFooter(records)
795
796 Return a footer for a list of *records*. The base implementation just
797 returns the empty string. You will need to override this method if you
798 want specific behaviour, e.g. to show the count of records or a separator
799 line.
800
801 .. method:: format(records)
802
803 Return formatted text for a list of *records*. The base implementation
804 just returns the empty string if there are no records; otherwise, it
805 returns the concatenation of the header, each record formatted with the
806 line formatter, and the footer.
807
808 .. _filter:
809
810 Filter Objects
811 --------------
812
813 ``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
814 filtering than is provided by levels. The base filter class only allows events
815 which are below a certain point in the logger hierarchy. For example, a filter
816 initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C',
817 'A.B.C.D', 'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the
818 empty string, all events are passed.
819
820
821 .. class:: Filter(name='')
822
823 Returns an instance of the :class:`Filter` class. If *name* is specified, it
824 names a logger which, together with its children, will have its events allowed
825 through the filter. If *name* is the empty string, allows every event.
826
827
828 .. method:: filter(record)
829
830 Is the specified record to be logged? Returns false for no, true for
831 yes. Filters can either modify log records in-place or return a completely
832 different record instance which will replace the original
833 log record in any future processing of the event.
834
835 Note that filters attached to handlers are consulted before an event is
836 emitted by the handler, whereas filters attached to loggers are consulted
837 whenever an event is logged (using :meth:`debug`, :meth:`info`,
838 etc.), before sending an event to handlers. This means that events which have
839 been generated by descendant loggers will not be filtered by a logger's filter
840 setting, unless the filter has also been applied to those descendant loggers.
841
842 You don't actually need to subclass ``Filter``: you can pass any instance
843 which has a ``filter`` method with the same semantics.
844
845 .. versionchanged:: 3.2
846 You don't need to create specialized ``Filter`` classes, or use other
847 classes with a ``filter`` method: you can use a function (or other
848 callable) as a filter. The filtering logic will check to see if the filter
849 object has a ``filter`` attribute: if it does, it's assumed to be a
850 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
851 assumed to be a callable and called with the record as the single
852 parameter. The returned value should conform to that returned by
853 :meth:`~Filter.filter`.
854
855 .. versionchanged:: 3.12
856 You can now return a :class:`LogRecord` instance from filters to replace
857 the log record rather than modifying it in place. This allows filters attached to
858 a :class:`Handler` to modify the log record before it is emitted, without
859 having side effects on other handlers.
860
861 Although filters are used primarily to filter records based on more
862 sophisticated criteria than levels, they get to see every record which is
863 processed by the handler or logger they're attached to: this can be useful if
864 you want to do things like counting how many records were processed by a
865 particular logger or handler, or adding, changing or removing attributes in
866 the :class:`LogRecord` being processed. Obviously changing the LogRecord needs
867 to be done with some care, but it does allow the injection of contextual
868 information into logs (see :ref:`filters-contextual`).
869
870
871 .. _log-record:
872
873 LogRecord Objects
874 -----------------
875
876 :class:`LogRecord` instances are created automatically by the :class:`Logger`
877 every time something is logged, and can be created manually via
878 :func:`makeLogRecord` (for example, from a pickled event received over the
879 wire).
880
881
882 .. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
883
884 Contains all the information pertinent to the event being logged.
885
886 The primary information is passed in *msg* and *args*,
887 which are combined using ``msg % args`` to create
888 the :attr:`!message` attribute of the record.
889
890 :param name: The name of the logger used to log the event
891 represented by this :class:`!LogRecord`.
892 Note that the logger name in the :class:`!LogRecord`
893 will always have this value,
894 even though it may be emitted by a handler
895 attached to a different (ancestor) logger.
896 :type name: str
897
898 :param level: The :ref:`numeric level <levels>` of the logging event
899 (such as ``10`` for ``DEBUG``, ``20`` for ``INFO``, etc).
900 Note that this is converted to *two* attributes of the LogRecord:
901 :attr:`!levelno` for the numeric value
902 and :attr:`!levelname` for the corresponding level name.
903 :type level: int
904
905 :param pathname: The full string path of the source file
906 where the logging call was made.
907 :type pathname: str
908
909 :param lineno: The line number in the source file
910 where the logging call was made.
911 :type lineno: int
912
913 :param msg: The event description message,
914 which can be a %-format string with placeholders for variable data,
915 or an arbitrary object (see :ref:`arbitrary-object-messages`).
916 :type msg: typing.Any
917
918 :param args: Variable data to merge into the *msg* argument
919 to obtain the event description.
920 :type args: tuple | dict[str, typing.Any]
921
922 :param exc_info: An exception tuple with the current exception information,
923 as returned by :func:`sys.exc_info`,
924 or ``None`` if no exception information is available.
925 :type exc_info: tuple[type[BaseException], BaseException, types.TracebackType] | None
926
927 :param func: The name of the function or method
928 from which the logging call was invoked.
929 :type func: str | None
930
931 :param sinfo: A text string representing stack information
932 from the base of the stack in the current thread,
933 up to the logging call.
934 :type sinfo: str | None
935
936 .. method:: getMessage()
937
938 Returns the message for this :class:`LogRecord` instance after merging any
939 user-supplied arguments with the message. If the user-supplied message
940 argument to the logging call is not a string, :func:`str` is called on it to
941 convert it to a string. This allows use of user-defined classes as
942 messages, whose ``__str__`` method can return the actual format string to
943 be used.
944
945 .. versionchanged:: 3.2
946 The creation of a :class:`LogRecord` has been made more configurable by
947 providing a factory which is used to create the record. The factory can be
948 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
949 (see this for the factory's signature).
950
951 This functionality can be used to inject your own values into a
952 :class:`LogRecord` at creation time. You can use the following pattern::
953
954 old_factory = logging.getLogRecordFactory()
955
956 def record_factory(*args, **kwargs):
957 record = old_factory(*args, **kwargs)
958 record.custom_attribute = 0xdecafbad
959 return record
960
961 logging.setLogRecordFactory(record_factory)
962
963 With this pattern, multiple factories could be chained, and as long
964 as they don't overwrite each other's attributes or unintentionally
965 overwrite the standard attributes listed above, there should be no
966 surprises.
967
968
969 .. _logrecord-attributes:
970
971 LogRecord attributes
972 --------------------
973
974 The LogRecord has a number of attributes, most of which are derived from the
975 parameters to the constructor. (Note that the names do not always correspond
976 exactly between the LogRecord constructor parameters and the LogRecord
977 attributes.) These attributes can be used to merge data from the record into
978 the format string. The following table lists (in alphabetical order) the
979 attribute names, their meanings and the corresponding placeholder in a %-style
980 format string.
981
982 If you are using {}-formatting (:func:`str.format`), you can use
983 ``{attrname}`` as the placeholder in the format string. If you are using
984 $-formatting (:class:`string.Template`), use the form ``${attrname}``. In
985 both cases, of course, replace ``attrname`` with the actual attribute name
986 you want to use.
987
988 In the case of {}-formatting, you can specify formatting flags by placing them
989 after the attribute name, separated from it with a colon. For example: a
990 placeholder of ``{msecs:03.0f}`` would format a millisecond value of ``4`` as
991 ``004``. Refer to the :meth:`str.format` documentation for full details on
992 the options available to you.
993
994 +----------------+-------------------------+-----------------------------------------------+
995 | Attribute name | Format | Description |
996 +================+=========================+===============================================+
997 | args | You shouldn't need to | The tuple of arguments merged into ``msg`` to |
998 | | format this yourself. | produce ``message``, or a dict whose values |
999 | | | are used for the merge (when there is only one|
1000 | | | argument, and it is a dictionary). |
1001 +----------------+-------------------------+-----------------------------------------------+
1002 | asctime | ``%(asctime)s`` | Human-readable time when the |
1003 | | | :class:`LogRecord` was created. By default |
1004 | | | this is of the form '2003-07-08 16:49:45,896' |
1005 | | | (the numbers after the comma are millisecond |
1006 | | | portion of the time). |
1007 +----------------+-------------------------+-----------------------------------------------+
1008 | created | ``%(created)f`` | Time when the :class:`LogRecord` was created |
1009 | | | (as returned by :func:`time.time_ns` / 1e9). |
1010 +----------------+-------------------------+-----------------------------------------------+
1011 | exc_info | You shouldn't need to | Exception tuple (à la ``sys.exc_info``) or, |
1012 | | format this yourself. | if no exception has occurred, ``None``. |
1013 +----------------+-------------------------+-----------------------------------------------+
1014 | exc_text | You shouldn't need to | Exception information formatted as a string. |
1015 | | format this yourself. | This is set when :meth:`Formatter.format` is |
1016 | | | invoked, or ``None`` if no exception has |
1017 | | | occurred. |
1018 +----------------+-------------------------+-----------------------------------------------+
1019 | filename | ``%(filename)s`` | Filename portion of ``pathname``. |
1020 +----------------+-------------------------+-----------------------------------------------+
1021 | funcName | ``%(funcName)s`` | Name of function containing the logging call. |
1022 +----------------+-------------------------+-----------------------------------------------+
1023 | levelname | ``%(levelname)s`` | Text logging level for the message |
1024 | | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1025 | | | ``'ERROR'``, ``'CRITICAL'``). |
1026 +----------------+-------------------------+-----------------------------------------------+
1027 | levelno | ``%(levelno)s`` | Numeric logging level for the message |
1028 | | | (:const:`DEBUG`, :const:`INFO`, |
1029 | | | :const:`WARNING`, :const:`ERROR`, |
1030 | | | :const:`CRITICAL`). |
1031 +----------------+-------------------------+-----------------------------------------------+
1032 | lineno | ``%(lineno)d`` | Source line number where the logging call was |
1033 | | | issued (if available). |
1034 +----------------+-------------------------+-----------------------------------------------+
1035 | message | ``%(message)s`` | The logged message, computed as ``msg % |
1036 | | | args``. This is set when |
1037 | | | :meth:`Formatter.format` is invoked. |
1038 +----------------+-------------------------+-----------------------------------------------+
1039 | module | ``%(module)s`` | Module (name portion of ``filename``). |
1040 +----------------+-------------------------+-----------------------------------------------+
1041 | msecs | ``%(msecs)d`` | Millisecond portion of the time when the |
1042 | | | :class:`LogRecord` was created. |
1043 +----------------+-------------------------+-----------------------------------------------+
1044 | msg | You shouldn't need to | The format string passed in the original |
1045 | | format this yourself. | logging call. Merged with ``args`` to |
1046 | | | produce ``message``, or an arbitrary object |
1047 | | | (see :ref:`arbitrary-object-messages`). |
1048 +----------------+-------------------------+-----------------------------------------------+
1049 | name | ``%(name)s`` | Name of the logger used to log the call. |
1050 +----------------+-------------------------+-----------------------------------------------+
1051 | pathname | ``%(pathname)s`` | Full pathname of the source file where the |
1052 | | | logging call was issued (if available). |
1053 +----------------+-------------------------+-----------------------------------------------+
1054 | process | ``%(process)d`` | Process ID (if available). |
1055 +----------------+-------------------------+-----------------------------------------------+
1056 | processName | ``%(processName)s`` | Process name (if available). |
1057 +----------------+-------------------------+-----------------------------------------------+
1058 | relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
1059 | | | created, relative to the time the logging |
1060 | | | module was loaded. |
1061 +----------------+-------------------------+-----------------------------------------------+
1062 | stack_info | You shouldn't need to | Stack frame information (where available) |
1063 | | format this yourself. | from the bottom of the stack in the current |
1064 | | | thread, up to and including the stack frame |
1065 | | | of the logging call which resulted in the |
1066 | | | creation of this record. |
1067 +----------------+-------------------------+-----------------------------------------------+
1068 | thread | ``%(thread)d`` | Thread ID (if available). |
1069 +----------------+-------------------------+-----------------------------------------------+
1070 | threadName | ``%(threadName)s`` | Thread name (if available). |
1071 +----------------+-------------------------+-----------------------------------------------+
1072 | taskName | ``%(taskName)s`` | :class:`asyncio.Task` name (if available). |
1073 +----------------+-------------------------+-----------------------------------------------+
1074
1075 .. versionchanged:: 3.1
1076 *processName* was added.
1077
1078 .. versionchanged:: 3.12
1079 *taskName* was added.
1080
1081 .. _logger-adapter:
1082
1083 LoggerAdapter Objects
1084 ---------------------
1085
1086 :class:`LoggerAdapter` instances are used to conveniently pass contextual
1087 information into logging calls. For a usage example, see the section on
1088 :ref:`adding contextual information to your logging output <context-info>`.
1089
1090 .. class:: LoggerAdapter(logger, extra=None, merge_extra=False)
1091
1092 Returns an instance of :class:`LoggerAdapter` initialized with an
1093 underlying :class:`Logger` instance, an optional dict-like object (*extra*),
1094 and an optional boolean (*merge_extra*) indicating whether or not
1095 the *extra* argument of individual log calls should be merged with
1096 the :class:`LoggerAdapter` extra.
1097 The default behavior is to ignore the *extra* argument of individual log
1098 calls and only use the one of the :class:`LoggerAdapter` instance
1099
1100 .. method:: process(msg, kwargs)
1101
1102 Modifies the message and/or keyword arguments passed to a logging call in
1103 order to insert contextual information. This implementation takes the object
1104 passed as *extra* to the constructor and adds it to *kwargs* using key
1105 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
1106 (possibly modified) versions of the arguments passed in.
1107
1108 .. attribute:: manager
1109
1110 Delegates to the underlying :attr:`!manager` on *logger*.
1111
1112 .. attribute:: _log
1113
1114 Delegates to the underlying :meth:`!_log` method on *logger*.
1115
1116 In addition to the above, :class:`LoggerAdapter` supports the following
1117 methods of :class:`Logger`: :meth:`~Logger.debug`, :meth:`~Logger.info`,
1118 :meth:`~Logger.warning`, :meth:`~Logger.error`, :meth:`~Logger.exception`,
1119 :meth:`~Logger.critical`, :meth:`~Logger.log`, :meth:`~Logger.isEnabledFor`,
1120 :meth:`~Logger.getEffectiveLevel`, :meth:`~Logger.setLevel` and
1121 :meth:`~Logger.hasHandlers`. These methods have the same signatures as their
1122 counterparts in :class:`Logger`, so you can use the two types of instances
1123 interchangeably.
1124
1125 .. versionchanged:: 3.2
1126
1127 The :meth:`~Logger.isEnabledFor`, :meth:`~Logger.getEffectiveLevel`,
1128 :meth:`~Logger.setLevel` and :meth:`~Logger.hasHandlers` methods were added
1129 to :class:`LoggerAdapter`. These methods delegate to the underlying logger.
1130
1131 .. versionchanged:: 3.6
1132
1133 Attribute :attr:`!manager` and method :meth:`!_log` were added, which
1134 delegate to the underlying logger and allow adapters to be nested.
1135
1136 .. versionchanged:: 3.10
1137
1138 The *extra* argument is now optional.
1139
1140 .. versionchanged:: 3.13
1141
1142 The *merge_extra* parameter was added.
1143
1144
1145 Thread Safety
1146 -------------
1147
1148 The logging module is intended to be thread-safe without any special work
1149 needing to be done by its clients. It achieves this through using threading
1150 locks; there is one lock to serialize access to the module's shared data, and
1151 each handler also creates a lock to serialize access to its underlying I/O.
1152
1153 If you are implementing asynchronous signal handlers using the :mod:`signal`
1154 module, you may not be able to use logging from within such handlers. This is
1155 because lock implementations in the :mod:`threading` module are not always
1156 re-entrant, and so cannot be invoked from such signal handlers.
1157
1158
1159 Module-Level Functions
1160 ----------------------
1161
1162 In addition to the classes described above, there are a number of module-level
1163 functions.
1164
1165
1166 .. function:: getLogger(name=None)
1167
1168 Return a logger with the specified name or, if name is ``None``, return the
1169 root logger of the hierarchy. If specified, the name is typically a
1170 dot-separated hierarchical name like *'a'*, *'a.b'* or *'a.b.c.d'*. Choice
1171 of these names is entirely up to the developer who is using logging, though
1172 it is recommended that ``__name__`` be used unless you have a specific
1173 reason for not doing that, as mentioned in :ref:`logger`.
1174
1175 All calls to this function with a given name return the same logger instance.
1176 This means that logger instances never need to be passed between different parts
1177 of an application.
1178
1179
1180 .. function:: getLoggerClass()
1181
1182 Return either the standard :class:`Logger` class, or the last class passed to
1183 :func:`setLoggerClass`. This function may be called from within a new class
1184 definition, to ensure that installing a customized :class:`Logger` class will
1185 not undo customizations already applied by other code. For example::
1186
1187 class MyLogger(logging.getLoggerClass()):
1188 # ... override behaviour here
1189
1190
1191 .. function:: getLogRecordFactory()
1192
1193 Return a callable which is used to create a :class:`LogRecord`.
1194
1195 .. versionadded:: 3.2
1196 This function has been provided, along with :func:`setLogRecordFactory`,
1197 to allow developers more control over how the :class:`LogRecord`
1198 representing a logging event is constructed.
1199
1200 See :func:`setLogRecordFactory` for more information about the how the
1201 factory is called.
1202
1203 .. function:: debug(msg, *args, **kwargs)
1204
1205 This is a convenience function that calls :meth:`Logger.debug`, on the root
1206 logger. The handling of the arguments is in every way identical
1207 to what is described in that method.
1208
1209 The only difference is that if the root logger has no handlers, then
1210 :func:`basicConfig` is called, prior to calling ``debug`` on the root logger.
1211
1212 For very short scripts or quick demonstrations of ``logging`` facilities,
1213 ``debug`` and the other module-level functions may be convenient. However,
1214 most programs will want to carefully and explicitly control the logging
1215 configuration, and should therefore prefer creating a module-level logger and
1216 calling :meth:`Logger.debug` (or other level-specific methods) on it, as
1217 described at the beginning of this documentation.
1218
1219
1220 .. function:: info(msg, *args, **kwargs)
1221
1222 Logs a message with level :const:`INFO` on the root logger. The arguments and behavior
1223 are otherwise the same as for :func:`debug`.
1224
1225
1226 .. function:: warning(msg, *args, **kwargs)
1227
1228 Logs a message with level :const:`WARNING` on the root logger. The arguments and behavior
1229 are otherwise the same as for :func:`debug`.
1230
1231 .. note:: There is an obsolete function ``warn`` which is functionally
1232 identical to ``warning``. As ``warn`` is deprecated, please do not use
1233 it - use ``warning`` instead.
1234
1235
1236 .. function:: error(msg, *args, **kwargs)
1237
1238 Logs a message with level :const:`ERROR` on the root logger. The arguments and behavior
1239 are otherwise the same as for :func:`debug`.
1240
1241
1242 .. function:: critical(msg, *args, **kwargs)
1243
1244 Logs a message with level :const:`CRITICAL` on the root logger. The arguments and behavior
1245 are otherwise the same as for :func:`debug`.
1246
1247
1248 .. function:: exception(msg, *args, **kwargs)
1249
1250 Logs a message with level :const:`ERROR` on the root logger. The arguments and behavior
1251 are otherwise the same as for :func:`debug`. Exception info is added to the logging
1252 message. This function should only be called from an exception handler.
1253
1254 .. function:: log(level, msg, *args, **kwargs)
1255
1256 Logs a message with level *level* on the root logger. The arguments and behavior
1257 are otherwise the same as for :func:`debug`.
1258
1259 .. function:: disable(level=CRITICAL)
1260
1261 Provides an overriding level *level* for all loggers which takes precedence over
1262 the logger's own level. When the need arises to temporarily throttle logging
1263 output down across the whole application, this function can be useful. Its
1264 effect is to disable all logging calls of severity *level* and below, so that
1265 if you call it with a value of INFO, then all INFO and DEBUG events would be
1266 discarded, whereas those of severity WARNING and above would be processed
1267 according to the logger's effective level. If
1268 ``logging.disable(logging.NOTSET)`` is called, it effectively removes this
1269 overriding level, so that logging output again depends on the effective
1270 levels of individual loggers.
1271
1272 Note that if you have defined any custom logging level higher than
1273 ``CRITICAL`` (this is not recommended), you won't be able to rely on the
1274 default value for the *level* parameter, but will have to explicitly supply a
1275 suitable value.
1276
1277 .. versionchanged:: 3.7
1278 The *level* parameter was defaulted to level ``CRITICAL``. See
1279 :issue:`28524` for more information about this change.
1280
1281 .. function:: addLevelName(level, levelName)
1282
1283 Associates level *level* with text *levelName* in an internal dictionary, which is
1284 used to map numeric levels to a textual representation, for example when a
1285 :class:`Formatter` formats a message. This function can also be used to define
1286 your own levels. The only constraints are that all levels used must be
1287 registered using this function, levels should be positive integers and they
1288 should increase in increasing order of severity.
1289
1290 .. note:: If you are thinking of defining your own levels, please see the
1291 section on :ref:`custom-levels`.
1292
1293 .. function:: getLevelNamesMapping()
1294
1295 Returns a mapping from level names to their corresponding logging levels. For example, the
1296 string "CRITICAL" maps to :const:`CRITICAL`. The returned mapping is copied from an internal
1297 mapping on each call to this function.
1298
1299 .. versionadded:: 3.11
1300
1301 .. function:: getLevelName(level)
1302
1303 Returns the textual or numeric representation of logging level *level*.
1304
1305 If *level* is one of the predefined levels :const:`CRITICAL`, :const:`ERROR`,
1306 :const:`WARNING`, :const:`INFO` or :const:`DEBUG` then you get the
1307 corresponding string. If you have associated levels with names using
1308 :func:`addLevelName` then the name you have associated with *level* is
1309 returned. If a numeric value corresponding to one of the defined levels is
1310 passed in, the corresponding string representation is returned.
1311
1312 The *level* parameter also accepts a string representation of the level such
1313 as 'INFO'. In such cases, this functions returns the corresponding numeric
1314 value of the level.
1315
1316 If no matching numeric or string value is passed in, the string
1317 'Level %s' % level is returned.
1318
1319 .. note:: Levels are internally integers (as they need to be compared in the
1320 logging logic). This function is used to convert between an integer level
1321 and the level name displayed in the formatted log output by means of the
1322 ``%(levelname)s`` format specifier (see :ref:`logrecord-attributes`), and
1323 vice versa.
1324
1325 .. versionchanged:: 3.4
1326 In Python versions earlier than 3.4, this function could also be passed a
1327 text level, and would return the corresponding numeric value of the level.
1328 This undocumented behaviour was considered a mistake, and was removed in
1329 Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility.
1330
1331 .. function:: getHandlerByName(name)
1332
1333 Returns a handler with the specified *name*, or ``None`` if there is no handler
1334 with that name.
1335
1336 .. versionadded:: 3.12
1337
1338 .. function:: getHandlerNames()
1339
1340 Returns an immutable set of all known handler names.
1341
1342 .. versionadded:: 3.12
1343
1344 .. function:: makeLogRecord(attrdict)
1345
1346 Creates and returns a new :class:`LogRecord` instance whose attributes are
1347 defined by *attrdict*. This function is useful for taking a pickled
1348 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1349 it as a :class:`LogRecord` instance at the receiving end.
1350
1351
1352 .. function:: basicConfig(**kwargs)
1353
1354 Does basic configuration for the logging system by creating a
1355 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
1356 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
1357 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1358 if no handlers are defined for the root logger.
1359
1360 This function does nothing if the root logger already has handlers
1361 configured, unless the keyword argument *force* is set to ``True``.
1362
1363 .. note:: This function should be called from the main thread
1364 before other threads are started. In versions of Python prior to
1365 2.7.1 and 3.2, if this function is called from multiple threads,
1366 it is possible (in rare circumstances) that a handler will be added
1367 to the root logger more than once, leading to unexpected results
1368 such as messages being duplicated in the log.
1369
1370 The following keyword arguments are supported.
1371
1372 .. tabularcolumns:: |l|L|
1373
1374 +--------------+---------------------------------------------+
1375 | Format | Description |
1376 +==============+=============================================+
1377 | *filename* | Specifies that a :class:`FileHandler` be |
1378 | | created, using the specified filename, |
1379 | | rather than a :class:`StreamHandler`. |
1380 +--------------+---------------------------------------------+
1381 | *filemode* | If *filename* is specified, open the file |
1382 | | in this :ref:`mode <filemodes>`. Defaults |
1383 | | to ``'a'``. |
1384 +--------------+---------------------------------------------+
1385 | *format* | Use the specified format string for the |
1386 | | handler. Defaults to attributes |
1387 | | ``levelname``, ``name`` and ``message`` |
1388 | | separated by colons. |
1389 +--------------+---------------------------------------------+
1390 | *datefmt* | Use the specified date/time format, as |
1391 | | accepted by :func:`time.strftime`. |
1392 +--------------+---------------------------------------------+
1393 | *style* | If *format* is specified, use this style |
1394 | | for the format string. One of ``'%'``, |
1395 | | ``'{'`` or ``'$'`` for :ref:`printf-style |
1396 | | <old-string-formatting>`, |
1397 | | :meth:`str.format` or |
1398 | | :class:`string.Template` respectively. |
1399 | | Defaults to ``'%'``. |
1400 +--------------+---------------------------------------------+
1401 | *level* | Set the root logger level to the specified |
1402 | | :ref:`level <levels>`. |
1403 +--------------+---------------------------------------------+
1404 | *stream* | Use the specified stream to initialize the |
1405 | | :class:`StreamHandler`. Note that this |
1406 | | argument is incompatible with *filename* - |
1407 | | if both are present, a ``ValueError`` is |
1408 | | raised. |
1409 +--------------+---------------------------------------------+
1410 | *handlers* | If specified, this should be an iterable of |
1411 | | already created handlers to add to the root |
1412 | | logger. Any handlers which don't already |
1413 | | have a formatter set will be assigned the |
1414 | | default formatter created in this function. |
1415 | | Note that this argument is incompatible |
1416 | | with *filename* or *stream* - if both |
1417 | | are present, a ``ValueError`` is raised. |
1418 +--------------+---------------------------------------------+
1419 | *force* | If this keyword argument is specified as |
1420 | | true, any existing handlers attached to the |
1421 | | root logger are removed and closed, before |
1422 | | carrying out the configuration as specified |
1423 | | by the other arguments. |
1424 +--------------+---------------------------------------------+
1425 | *encoding* | If this keyword argument is specified along |
1426 | | with *filename*, its value is used when the |
1427 | | :class:`FileHandler` is created, and thus |
1428 | | used when opening the output file. |
1429 +--------------+---------------------------------------------+
1430 | *errors* | If this keyword argument is specified along |
1431 | | with *filename*, its value is used when the |
1432 | | :class:`FileHandler` is created, and thus |
1433 | | used when opening the output file. If not |
1434 | | specified, the value 'backslashreplace' is |
1435 | | used. Note that if ``None`` is specified, |
1436 | | it will be passed as such to :func:`open`, |
1437 | | which means that it will be treated the |
1438 | | same as passing 'errors'. |
1439 +--------------+---------------------------------------------+
1440
1441 .. versionchanged:: 3.2
1442 The *style* argument was added.
1443
1444 .. versionchanged:: 3.3
1445 The *handlers* argument was added. Additional checks were added to
1446 catch situations where incompatible arguments are specified (e.g.
1447 *handlers* together with *stream* or *filename*, or *stream*
1448 together with *filename*).
1449
1450 .. versionchanged:: 3.8
1451 The *force* argument was added.
1452
1453 .. versionchanged:: 3.9
1454 The *encoding* and *errors* arguments were added.
1455
1456 .. function:: shutdown()
1457
1458 Informs the logging system to perform an orderly shutdown by flushing and
1459 closing all handlers. This should be called at application exit and no
1460 further use of the logging system should be made after this call.
1461
1462 When the logging module is imported, it registers this function as an exit
1463 handler (see :mod:`atexit`), so normally there's no need to do that
1464 manually.
1465
1466
1467 .. function:: setLoggerClass(klass)
1468
1469 Tells the logging system to use the class *klass* when instantiating a logger.
1470 The class should define :meth:`!__init__` such that only a name argument is
1471 required, and the :meth:`!__init__` should call :meth:`!Logger.__init__`. This
1472 function is typically called before any loggers are instantiated by applications
1473 which need to use custom logger behavior. After this call, as at any other
1474 time, do not instantiate loggers directly using the subclass: continue to use
1475 the :func:`logging.getLogger` API to get your loggers.
1476
1477
1478 .. function:: setLogRecordFactory(factory)
1479
1480 Set a callable which is used to create a :class:`LogRecord`.
1481
1482 :param factory: The factory callable to be used to instantiate a log record.
1483
1484 .. versionadded:: 3.2
1485 This function has been provided, along with :func:`getLogRecordFactory`, to
1486 allow developers more control over how the :class:`LogRecord` representing
1487 a logging event is constructed.
1488
1489 The factory has the following signature:
1490
1491 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)``
1492
1493 :name: The logger name.
1494 :level: The logging level (numeric).
1495 :fn: The full pathname of the file where the logging call was made.
1496 :lno: The line number in the file where the logging call was made.
1497 :msg: The logging message.
1498 :args: The arguments for the logging message.
1499 :exc_info: An exception tuple, or ``None``.
1500 :func: The name of the function or method which invoked the logging
1501 call.
1502 :sinfo: A stack traceback such as is provided by
1503 :func:`traceback.print_stack`, showing the call hierarchy.
1504 :kwargs: Additional keyword arguments.
1505
1506
1507 Module-Level Attributes
1508 -----------------------
1509
1510 .. data:: lastResort
1511
1512 A "handler of last resort" is available through this attribute. This
1513 is a :class:`StreamHandler` writing to ``sys.stderr`` with a level of
1514 ``WARNING``, and is used to handle logging events in the absence of any
1515 logging configuration. The end result is to just print the message to
1516 ``sys.stderr``. This replaces the earlier error message saying that
1517 "no handlers could be found for logger XYZ". If you need the earlier
1518 behaviour for some reason, ``lastResort`` can be set to ``None``.
1519
1520 .. versionadded:: 3.2
1521
1522 .. data:: raiseExceptions
1523
1524 Used to see if exceptions during handling should be propagated.
1525
1526 Default: ``True``.
1527
1528 If :data:`raiseExceptions` is ``False``,
1529 exceptions get silently ignored. This is what is mostly wanted
1530 for a logging system - most users will not care about errors in
1531 the logging system, they are more interested in application errors.
1532
1533
1534 Integration with the warnings module
1535 ------------------------------------
1536
1537 The :func:`captureWarnings` function can be used to integrate :mod:`!logging`
1538 with the :mod:`warnings` module.
1539
1540 .. function:: captureWarnings(capture)
1541
1542 This function is used to turn the capture of warnings by logging on and
1543 off.
1544
1545 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
1546 be redirected to the logging system. Specifically, a warning will be
1547 formatted using :func:`warnings.formatwarning` and the resulting string
1548 logged to a logger named ``'py.warnings'`` with a severity of :const:`WARNING`.
1549
1550 If *capture* is ``False``, the redirection of warnings to the logging system
1551 will stop, and warnings will be redirected to their original destinations
1552 (i.e. those in effect before ``captureWarnings(True)`` was called).
1553
1554
1555 .. seealso::
1556
1557 Module :mod:`logging.config`
1558 Configuration API for the logging module.
1559
1560 Module :mod:`logging.handlers`
1561 Useful handlers included with the logging module.
1562
1563 :pep:`282` - A Logging System
1564 The proposal which described this feature for inclusion in the Python standard
1565 library.
1566
1567 `Original Python logging package <https://old.red-dove.com/python_logging.html>`_
1568 This is the original source for the :mod:`!logging` package. The version of the
1569 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1570 and 2.2.x, which do not include the :mod:`!logging` package in the standard
1571 library.