logging — Logging facility for Python¶
Source code: Lib/logging/__init__.py
This module defines functions and classes which implement a flexible event logging system for applications and libraries.
The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.
Here’s a simple example of idiomatic usage:
# myapp.py
import logging
import mylib
logger = logging.getLogger(__name__)
def main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logger.info('Started')
mylib.do_something()
logger.info('Finished')
if __name__ == '__main__':
main()
# mylib.py
import logging
logger = logging.getLogger(__name__)
def do_something():
logger.info('Doing something')
If you run myapp.py, you should see this in myapp.log:
INFO:__main__:Started
INFO:mylib:Doing something
INFO:__main__:Finished
The key feature of this idiomatic usage is that the majority of code is simply
creating a module level logger with getLogger(__name__), and using that
logger to do any needed logging. This is concise, while allowing downstream
code fine-grained control if needed. Logged messages to the module-level logger
get forwarded to handlers of loggers in higher-level modules, all the way up to
the highest-level logger known as the root logger; this approach is known as
hierarchical logging.
For logging to be useful, it needs to be configured: setting the levels and
destinations for each logger, potentially changing how specific modules log,
often based on command-line arguments or application configuration. In most
cases, like the one above, only the root logger needs to be so configured, since
all the lower level loggers at module level eventually forward their messages to
its handlers. basicConfig() provides a quick way to configure
the root logger that handles many use cases.
The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to view the tutorials (see the links above and on the right).
The basic classes defined by the module, together with their attributes and methods, are listed in the sections below.
Loggers expose the interface that application code directly uses.
Handlers send the log records (created by loggers) to the appropriate destination.
Filters provide a finer grained facility for determining which log records to output.
Formatters specify the layout of log records in the final output.
Logger Objects¶
Loggers have the following attributes and methods. Note that Loggers should
NEVER be instantiated directly, but always through the module-level function
logging.getLogger(name). Multiple calls to getLogger() with the same
name will always return a reference to the same Logger object.
The name is potentially a period-separated hierarchical value, like
foo.bar.baz (though it could also be just plain foo, for example).
Loggers that are further down in the hierarchical list are children of loggers
higher up in the list. For example, given a logger with a name of foo,
loggers with names of foo.bar, foo.bar.baz, and foo.bam are all
descendants of foo. In addition, all loggers are descendants of the root
logger. The logger name hierarchy is analogous to the Python package hierarchy,
and identical to it if you organise your loggers on a per-module basis using
the recommended construction logging.getLogger(__name__). That’s because
in a module, __name__ is the module’s name in the Python package namespace.
- class logging.Logger¶
- name¶
This is the logger’s name, and is the value that was passed to
getLogger()to obtain the logger.Note
This attribute should be treated as read-only.
- level¶
The threshold of this logger, as set by the
setLevel()method.Note
Do not set this attribute directly - always use
setLevel(), which has checks for the level passed to it.
- parent¶
The parent logger of this logger. It may change based on later instantiation of loggers which are higher up in the namespace hierarchy.
Note
This value should be treated as read-only.
- propagate¶
If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
Spelling it out with an example: If the propagate attribute of the logger named
A.B.Cevaluates to true, any event logged toA.B.Cvia a method call such aslogging.getLogger('A.B.C').error(...)will [subject to passing that logger’s level and filter settings] be passed in turn to any handlers attached to loggers namedA.B,Aand the root logger, after first being passed to any handlers attached toA.B.C. If any logger in the chainA.B.C,A.B,Ahas itspropagateattribute set to false, then that is the last logger whose handlers are offered the event to handle, and propagation stops at that point.The constructor sets this attribute to
True.Note
If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to
True. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest.
- handlers¶
The list of handlers directly attached to this logger instance.
Note
This attribute should be treated as read-only; it is normally changed via the
addHandler()andremoveHandler()methods, which use locks to ensure thread-safe operation.
- disabled¶
This attribute disables handling of any events. It is set to
Falsein the initializer, and only changed by logging configuration code.Note
This attribute should be treated as read-only.
- setLevel(level)¶
Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.
When a logger is created, the level is set to
NOTSET(which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with levelWARNING.The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.
If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.
If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.
See Logging Levels for a list of levels.
Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as
INFO. Note, however, that levels are internally stored as integers, and methods such as e.g.getEffectiveLevel()andisEnabledFor()will return/expect to be passed integers.
- isEnabledFor(level)¶
Indicates if a message of severity level would be processed by this logger. This method checks first the module-level level set by
logging.disable(level)and then the logger’s effective level as determined bygetEffectiveLevel().
- getEffectiveLevel()¶
Indicates the effective level for this logger. If a value other than
NOTSEThas been set usingsetLevel(), it is returned. Otherwise, the hierarchy is traversed towards the root until a value other thanNOTSETis found, and that value is returned. The value returned is an integer, typically one oflogging.DEBUG,logging.INFOetc.
- getChild(suffix)¶
Returns a logger which is a descendant to this logger, as determined by the suffix. Thus,
logging.getLogger('abc').getChild('def.ghi')would return the same logger as would be returned bylogging.getLogger('abc.def.ghi'). This is a convenience method, useful when the parent logger is named using e.g.__name__rather than a literal string.Added in version 3.2.
- getChildren()¶
Returns a set of loggers which are immediate children of this logger. So for example
logging.getLogger().getChildren()might return a set containing loggers namedfooandbar, but a logger namedfoo.barwouldn’t be included in the set. Likewise,logging.getLogger('foo').getChildren()might return a set including a logger namedfoo.bar, but it wouldn’t include one namedfoo.bar.baz.Added in version 3.12.
- debug(msg, *args, **kwargs)¶
Logs a message with level
DEBUGon this logger. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on msg when no args are supplied.There are four keyword arguments in kwargs which are inspected: exc_info, stack_info, stacklevel and extra.
If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by