6.28 logging -- Logging facility for Python

New in version 2.3. This module defines functions and classes which implement a flexible error logging system for applications.

Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a name space hierarchy using dots (periods) as separators. For example, a logger named "scan" is the parent of loggers "scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want, and indicate the area of an application in which a logged message originates.

Logged messages also have levels of importance associated with them. The default levels provided are DEBUG, INFO, WARNING, ERROR and CRITICAL. As a convenience, you indicate the importance of a logged message by calling an appropriate method of Logger. The methods are debug(), info(), warning(), error() and critical(), which mirror the default levels. You are not constrained to use these levels: you can specify your own and use a more general Logger method, log(), which takes an explicit level argument.

Levels can also be associated with loggers, being set either by the developer or through loading a saved logging configuration. When a logging method is called on a logger, the logger compares its own level with the level associated with the method call. If the logger's level is higher than the method call's, no logging message is actually generated. This is the basic mechanism controlling the verbosity of logging output.

Logging messages are encoded as instances of the LogRecord class. When a logger decides to actually log an event, an LogRecord instance is created from the logging message.

Logging messages are subjected to a dispatch mechanism through the use of handlers, which are instances of subclasses of the Handler class. Handlers are responsible for ensuring that a logged message (in the form of a LogRecord) ends up in a particular location (or set of locations) which is useful for the target audience for that message (such as end users, support desk staff, system administrators, developers). Handlers are passed LogRecord instances intended for particular destinations. Each logger can have zero, one or more handlers associated with it (via the addHandler method of Logger). In addition to any handlers directly associated with a logger, all handlers associated with all ancestors of the logger are called to dispatch the message.

Just as for loggers, handlers can have levels associated with them. A handler's level acts as a filter in the same way as a logger's level does. If a handler decides to actually dispatch an event, the emit() method is used to send the message to its destination. Most user-defined subclasses of Handler will need to override this emit().

In addition to the base Handler class, many useful subclasses are provided:

  1. StreamHandler instances send error messages to streams (file-like objects).

  2. FileHandler instances send error messages to disk files.

  3. RotatingFileHandler instances send error messages to disk files, with support for maximum log file sizes and log file rotation.

  4. SocketHandler instances send error messages to TCP/IP sockets.

  5. DatagramHandler instances send error messages to UDP sockets.

  6. SMTPHandler instances send error messages to a designated email address.

  7. SysLogHandler instances send error messages to a Unix syslog daemon, possibly on a remote machine.

  8. NTEventLogHandler instances send error messages to a Windows NT/2000/XP event log.

  9. MemoryHandler instances send error messages to a buffer in memory, which is flushed whenever specific criteria are met.

  10. HTTPHandler instances send error messages to an HTTP server using either "GET" or "POST" semantics.

The StreamHandler and FileHandler classes are defined in the core logging package. The other handlers are defined in a sub- module, logging.handlers. (There is also another sub-module, logging.config, for configuration functionality.)

Logged messages are formatted for presentation through instances of the Formatter class. They are initialized with a format string suitable for use with the % operator and a dictionary.

For formatting multiple messages in a batch, instances of BufferingFormatter can be used. In addition to the format string (which is applied to each message in the batch), there is provision for header and trailer format strings.

When filtering based on logger level and/or handler level is not enough, instances of Filter can be added to both Logger and Handler instances (through their addFilter() method). Before deciding to process a message further, both loggers and handlers consult all their filters for permission. If any filter returns a false value, the message is not processed further.

The basic Filter functionality allows filtering by specific logger name. If this feature is used, messages sent to the named logger and its children are allowed through the filter, and all others dropped.

In addition to the classes described above, there are a number of module- level functions.

getLogger( [name])
Return a logger with the specified name or, if no name is specified, return a logger which is the root logger of the hierarchy.

All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.

debug( msg[, *args[, **kwargs]])
Logs a message with level DEBUG on the root logger. The msg is the message format string, and the args are the arguments which are merged into msg. The only keyword argument in kwargs which is inspected is exc_info which, if it does not evaluate as false, causes exception information (via a call to sys.exc_info()) to be added to the logging message.

info( msg[, *args[, **kwargs]])
Logs a message with level INFO on the root logger. The arguments are interpreted as for debug().

warning( msg[, *args[, **kwargs]])
Logs a message with level WARNING on the root logger. The arguments are interpreted as for debug().

error( msg[, *args[, **kwargs]])
Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug().

critical( msg[, *args[, **kwargs]])
Logs a message with level CRITICAL on the root logger. The arguments are interpreted as for debug().

exception( msg[, *args])
Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This function should only be called from an exception handler.

disable( lvl)
Provides an overriding level lvl for all loggers which takes precedence over the logger's own level. When the need arises to temporarily throttle logging output down across the whole application, this function can be useful.

addLevelName( lvl, levelName)
Associates level lvl with text levelName in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a Formatter formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity.

getLevelName( lvl)
Returns the textual representation of logging level lvl. If the level is one of the predefined levels CRITICAL, ERROR, WARNING, INFO or DEBUG then you get the corresponding string. If you have associated levels with names using addLevelName() then the name you have associated with lvl is returned. Otherwise, the string "Level %s" % lvl is returned.

makeLogRecord( attrdict)
Creates and returns a new LogRecord instance whose attributes are defined by attrdict. This function is useful for taking a pickled LogRecord attribute dictionary, sent over a socket, and reconstituting it as a LogRecord instance at the receiving end.

basicConfig( )
Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

shutdown( )
Informs the logging system to perform an orderly shutdown by flushing and closing all handlers.

setLoggerClass( klass)
Tells the logging system to use the class klass when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__(). This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior.

See Also:

PEP 282, A Logging System
The proposal which described this feature for inclusion in the Python standard library.
Original Python logging package
This is the original source for the logging package. The version of the package available from this site is suitable for use with Python 2.1.x and 2.2.x, which do not include the logging package in the standard library.

See About this document... for information on suggesting changes.