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