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