16.6. logging — Python的日志功能

源代码: Lib/logging/__init__.py

该模块定义了为应用程序和库实现灵活事件记录系统的函数和类。

由标准库模块提供的日志记录API的主要好处是所有Python模块都可以参与日志记录,因此您的应用程序日志可以包括您自己的消息以及来自第三方模块的消息。

该模块提供了很多功能和灵活性。如果您不熟悉日志记录,那么最好的方法是查看教程(请参阅右侧的链接)。

下面列出了模块定义的基本类及其功能。

  • 记录器公开了应用程序代码直接使用的接口。
  • 处理程序将日志记录(由记录器创建)发送到适当的目的地。
  • 筛选器提供了更细粒度的功能,用于确定要输出的日志记录。
  • 格式化程序在最终输出中指定日志记录的布局。

16.6.1. Logger Objects

Loggers have the following attributes and methods. Logger对象一般不会直接实例化得到,而是通过模块级别的函数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. 例如,对于给定的一个logger对象 foo,其它logger对象foo.bar, foo.bar.baz, foo.bam,它们都是foo的子辈。logger对象名字的层级和python包的层级是相似的,并且如果你使用推荐的结构logging.getLogger(__name__)来管理你的loggers对象的话,那就与python包的层级结构是一模一样的。因为在一个模块中__name__是一个在python包中名字空间的模块的名称。

class logging.Logger
Logger.propagate

If this 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.

The constructor sets this attribute to True.

Note

如果将处理程序附加到记录器其一个或多个祖先,它可能会多次发出相同的记录。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.

Logger.setLevel(lvl)

Sets the threshold for this logger to lvl. Logging messages which are less severe than lvl will be ignored. 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 level WARNING.

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 lvl parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO. 然而,注意,级别在内部存储为整数,并且方法例如getEffectiveLevel()isEnabledFor()将返回/期望被传递的整数。

Logger.isEnabledFor(lvl)

Indicates if a message of severity lvl would be processed by this logger. This method checks first the module-level level set by logging.disable(lvl) and then the logger’s effective level as determined by getEffectiveLevel().

Logger.getEffectiveLevel()

Indicates the effective level for this logger. If a value other than NOTSET has been set using setLevel(), it is returned. 否则,将向根向前遍历层次结构,直到找到除NOTSET之外的值,并返回该值。返回的值是一个整数,通常为logging.DEBUGlogging.INFO等。

Logger.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 by logging.getLogger('abc.def.ghi'). 这是一个方便的方法,当父记录器使用例如__ name __而不是字面值字符串。

版本3.2中的新功能。

Logger.debug(msg, *args, **kwargs)

Logs a message with level DEBUG on 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.)

kwargs中有三个关键字参数,它们被检查:exc_infostack_infoextra

如果exc_info不计算为假,则会导致将异常信息添加到日志记录消息中。如果提供了异常元组(以sys.exc_info()返回的格式)或异常实例,则使用它;否则,调用sys.exc_info()以获取异常信息。

第二个可选的关键字参数是stack_info,默认为False如果为true,则将堆栈信息添加到日志记录消息中,包括实际的日志调用。注意,这不是通过指定exc_info显示的堆栈信息:前者是从堆栈底部到当前线程中的日志调用的堆栈帧,而后者是有关堆栈帧,它们在寻找异常处理程序时例外之后被解开。

您可以独立于exc_info指定stack_info,例如只是展示你如何到达代码中的某一点,即使没有引发异常。堆栈帧打印在标题行后面,说:

Stack (most recent call last):

This mimics the Traceback (most recent call last): which is used when displaying exception frames.

第三个关键字参数是extra,可用于传递一个字典,用于填充为具有用户定义属性的日志记录事件创建的LogRecord的__dict__。These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:

FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)

would print something like

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the Formatter documentation for more information on which keys are used by the logging system.)

If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the Formatter has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the extra dictionary with these keys.

While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized Formatters would be used with particular Handlers.

New in version 3.2: The stack_info parameter was added.

Changed in version 3.5: The exc_info parameter can now accept exception instances.

Logger.info(msg, *args, **kwargs)

Logs a message with level INFO on this logger. The arguments are interpreted as for debug().

Logger.warning(msg, *args, **kwargs)

Logs a message with level WARNING on this logger. The arguments are interpreted as for debug().

Note

有一个过时的方法warn,其功能与warning相同。由于warn已弃用,请不要使用它 - 请改用warning

Logger.error(msg, *args, **kwargs)

Logs a message with level ERROR on this logger. The arguments are interpreted as for debug().

Logger.critical(msg, *args, **kwargs)

Logs a message with level CRITICAL on this logger. The arguments are interpreted as for debug().

Logger.log(lvl, msg, *args, **kwargs)

Logs a message with integer level lvl on this logger. The other arguments are interpreted as for debug().

Logger.exception(msg, *args, **kwargs)

Logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.

Logger.addFilter(filt)

Adds the specified filter filt to this logger.

Logger.removeFilter(filt)

Removes the specified filter filt from this logger.

Logger.filter(record)

Applies this logger’s filters to the record and returns a true value if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs.

Logger.addHandler(hdlr)

Adds the specified handler hdlr to this logger.

Logger.removeHandler(hdlr)

Removes the specified handler hdlr from this logger.

Logger.findCaller(stack_info=False)

Finds the caller’s source filename and line number. 将文件名,行号,函数名和堆栈信息作为4元素元组返回。除非stack_infoTrue,否则堆栈信息将作为返回。

Logger.handle(record)

Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of propagate is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using filter().

Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

This is a factory method which can be overridden in subclasses to create specialized LogRecord instances.

Logger.hasHandlers()

检查此记录器是否已配置任何处理程序。这是通过在记录器层次结构中查找此记录器及其父节点中的处理程序来完成的。如果找到处理程序,则返回True,否则False当找到具有“propagate”属性设置为False的记录器时,该方法停止搜索层次结构 - 这将是检查处理程序是否存在的最后一个记录器。

New in version 3.2.

16.6.2. Logging Levels

The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. 如果定义具有相同数值的级别,它将覆盖预定义值;预定义的名称将丢失。

LevelNumeric value
CRITICAL50
ERROR40
WARNING30
INFO20
DEBUG10
NOTSET0

16.6.3. Handler Objects

Handlers have the following attributes and methods. 注意:Handler不应该直接被实例化,此类应该作为基类来子类化出一些有用的类。然而,__init__()方法在子类中需要被Handler.__init__()来调用。

Handler.__init__(level=NOTSET)

Initializes the Handler instance by setting its level, setting the list of filters to the empty list and creating a lock (using createLock()) for serializing access to an I/O mechanism.

Handler.createLock()

Initializes a thread lock which can be used to serialize access to underlying I/O functionality which may not be threadsafe.

Handler.acquire()

Acquires the thread lock created with createLock().

Handler.release()

Releases the thread lock acquired with acquire().

Handler.setLevel(lvl)

Sets the threshold for this handler to lvl. Logging messages which are less severe than lvl will be ignored. When a handler is created, the level is set to NOTSET (which causes all messages to be processed).

See Logging Levels for a list of levels.

在版本3.2中更改: lvl参数现在接受级别的字符串表示形式,如“INFO”,作为整数常量的替代,如INFO

Handler.setFormatter(form)

Sets the Formatter for this handler to form.

Handler.addFilter(filt)

Adds the specified filter filt to this handler.

Handler.removeFilter(filt)

Removes the specified filter filt from this handler.

Handler.filter(record)

Applies this handler’s filters to the record and returns a true value if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be emitted. If one returns a false value, the handler will not emit the record.

Handler.flush()

Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.

Handler.close()

Tidy up any resources used by the handler. This version does no output but removes the handler from an internal list of handlers which is closed when shutdown() is called. Subclasses should ensure that this gets called from overridden close() methods.

Handler.handle(record)

Conditionally emits the specified logging record, depending on filters which may have been added to the handler. Wraps the actual emission of the record with acquisition/release of the I/O thread lock.

Handler.handleError(record)

此方法应该在调用emit()时遇到异常后从handlers被调用。If the module-level attribute raiseExceptions is False, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The specified record is the one which was being processed when the exception occurred. (The default value of raiseExceptions is True, as that is more useful during development).

Handler.format(record)

Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module.

Handler.emit(record)

Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError.

For a list of handlers included as standard, see logging.handlers.

16.6.4. Formatter Objects

Formatter对象有以下属性和方法。它负责将LogRecord转换(通常)成人类和其它系统可以理解的字符串。基类Formatter允许指定某个格式的字符串。如果提供None,那么'%(message)s'将会作为默认值,它仅仅包括日志调用中的信息。如果想加入一些额外的格式输出(例如时间戳)信息项,请继续阅读下去。

Formatter对象可以用一个使LogRecord的属性的反应信息有用的字符串来进行实例化。例如上面提到的用来使用户信息和参数预格式化进LogRecord对象的 message属性有效的默认值。This format string contains standard Python %-style mapping keys. 欲了解更多关于字符串格式化的信息,请参见printf-style String Formatting

LogRecord对象中,有效的映射键存在于LogRecord attributes属性中。

class logging.Formatter(fmt=None, datefmt=None, style='%')

返回一个Formatter类的新实例。The instance is initialized with a format string for the message as a whole, as well as a format string for the date/time portion of a message. 如果fmt不被指定, '%(message)s'将会被使用。If no datefmt is specified, the ISO8601 date format is used.

style可以是 ‘%’, ‘{‘ or ‘$’中的任何一个,并且它决定格式化字符串将会怎样与它的数据融合: 使用%格式化的更多信息参考str.format() or string.Template.有关使用{ - 和$ - 格式化日志消息的详细信息,请参阅在应用程序中使用特定格式样式

在版本3.2中已更改:添加了样式参数。

format(record)

The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using msg % args. If the formatting string contains '(asctime)', formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. Note that the formatted exception information is cached in attribute exc_text. This is useful because the exception information can be pickled and sent across the wire, but you should be careful if you have more than one Formatter subclass which customizes the formatting of exception information. In this case, you will have to clear the cached value after a formatter has done its formatting, so that the next formatter to handle the event doesn’t use the cached value but recalculates it afresh.

If stack information is available, it’s appended after the exception information, using formatStack() to transform it if necessary.

formatTime(record, datefmt=None)

此方法应该被从想使用格式化时间的formatter对象的format()调用。This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned.

This function uses a user-configurable function to convert the creation time to a tuple. 默认情况下,使用time.localtime();为特定格式化程序更改此属性实例,将转换器属性设置为具有与time.localtime()time.gmtime()To change it for all formatters, for example if you want all logging times to be shown in GMT, set the converter attribute in the Formatter class.

在版本3.3中更改:以前,默认的ISO 8601格式是硬编码的,如在此示例中:2010-09-06 22:38: 15,292其中逗号之前的部分由strptime格式字符串处理('%Y-%m-%d %H:%M :%S'),逗号后面的部分是毫秒值。因为strptime没有毫秒的格式占位符,所以使用另一个格式字符串'%s,%03d'附加毫秒值,并且这两个格式字符串都已硬编码到此方法中。随着改变,这些字符串被定义为类级别的属性,在需要时可以在实例级别被覆盖。属性的名称为default_time_format(对于strptime格式字符串)和default_msec_format(用于追加毫秒值)。

formatException(exc_info)

Formats the specified exception information (a standard exception tuple as returned by sys.exc_info()) as a string. This default implementation just uses traceback.print_exception(). The resulting string is returned.

formatStack(stack_info)

格式化指定的堆栈信息(由traceback.print_stack()返回的字符串,但删除了最后一个换行符)作为字符串。这个默认实现只返回输入值。

16.6.5. Filter Objects

Filters can be used by Handlers and Loggers for more sophisticated filtering than is provided by levels. The base filter class only allows events which are below a certain point in the logger hierarchy. 例如,用“A.B”初始化的过滤器将允许由记录器“A.B”,“A.B.C”,“A.B.C.D”,“A.B.D”等记录的事件。但是,不接受“A.BB”,“B.A.B”等的格式。If initialized with the empty string, all events are passed.

class logging.Filter(name='')

Returns an instance of the Filter class. If name is specified, it names a logger which, together with its children, will have its events allowed through the filter. If name is the empty string, allows every event.

filter(record)

Is the specified record to be logged? Returns zero for no, nonzero for yes. If deemed appropriate, the record may be modified in-place by this method.

注意,在处理程序发出事件之前,请参考处理程序附带的过滤器,而记录事件时会查询附加到日志记录器的过滤器(使用debug()info 等。), before sending an event to handlers. This means that events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant loggers.

You don’t actually need to subclass Filter: you can pass any instance which has a filter method with the same semantics.

Changed in version 3.2: You don’t need to create specialized Filter classes, or use other classes with a filter method: you can use a function (or other callable) as a filter. The filtering logic will check to see if the filter object has a filter attribute: if it does, it’s assumed to be a Filter and its filter() method is called. Otherwise, it’s assumed to be a callable and called with the record as the single parameter. The returned value should conform to that returned by filter().

Although filters are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they’re attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the LogRecord being processed. Obviously changing the LogRecord needs to be done with some care, but it does allow the injection of contextual information into logs (see Using Filters to impart contextual information).

16.6.6. LogRecord Objects

每次某个事件被日志记录时LogRecord实例就会被Logger自动创建,并且可以被手动创建,通过 makeLogRecord() (例如,一个网络序列化事件).

class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)

Contains all the information pertinent to the event being logged.

主要信息由msgargs传入,which are combined using msg % args to create the message field of the record.

Parameters:
  • name - 用于记录由此LogRecord表示的事件的记录器的名称。Note that this name will always have this value, even though it may be emitted by a handler attached to a different (ancestor) logger.
  • level - 记录事件的数字级别(DEBUG,INFO等之一)请注意,将其转换为LogRecord的两个属性:levelno表示数字值,levelname表示相应的级别名称。
  • pathname - 进行记录调用的源文件的完整路径名。
  • lineno - 进行日志调用的源文件中的行号。
  • msg - 事件描述消息,可能是带有变量数据占位符的格式字符串。
  • args - 要合并到msg参数中的变量数据,以获取事件描述。
  • exc_info - 当前异常信息的异常元组,如果没有异常信息,则为None
  • func - 调用日志记录调用的函数或方法的名称。
  • sinfo - 表示当前线程中堆栈基址的堆栈信息的文本字符串,直到日志调用。
getMessage()

LogRecord实例在融合用户提供的参数后返回一条message。If the user-supplied message argument to the logging call is not a string, str() is called on it to convert it to a string. This allows use of user-defined classes as messages, whose __str__ method can return the actual format string to be used.

在版本3.2中已更改:通过提供用于创建记录的工厂,可以更轻松地创建LogRecord可以使用getLogRecordFactory()setLogRecordFactory()来设置工厂(参见工厂的签名)。

此功能可用于在创建时将自己的值注入LogRecord。您可以使用以下模式:

old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)

使用这种模式,多个工厂可以链接,并且只要它们不会覆盖彼此的属性或无意地覆盖上面列出的标准属性,就不会有任何意外。

16.6.7. LogRecord attributes

The LogRecord has a number of attributes, most of which are derived from the parameters to the constructor. (Note that the names do not always correspond exactly between the LogRecord constructor parameters and the LogRecord attributes.) These attributes can be used to merge data from the record into the format string. The following table lists (in alphabetical order) the attribute names, their meanings and the corresponding placeholder in a %-style format string.

如果使用{} -formatting(str.format()),则可以使用{attrname}作为格式字符串中的占位符。如果您使用$ -formatting(string.Template),请使用形式$ {attrname}在这两种情况下,当然,将attrname替换为要使用的实际属性名称。

在{}格式化的情况下,您可以通过将属性名称放在属性名称后面指定格式化标记,并用冒号分隔。例如:{msecs:03d}的占位符会将4的毫秒值格式化为004有关可用选项的完整详细信息,请参阅str.format()文档。

Attribute nameFormatDescription
argsYou shouldn’t need to format this yourself.The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).
asctime%(asctime)sHuman-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
created%(created)fTime when the LogRecord was created (as returned by time.time()).
exc_infoYou shouldn’t need to format this yourself.Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename%(filename)sFilename portion of pathname.
funcName%(funcName)sName of function containing the logging call.
levelname%(levelname)sText logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno%(levelno)sNumeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
行号%(lineno)dSource line number where the logging call was issued (if available).
module%(module)sModule (name portion of filename).
msecs%(msecs)dMillisecond portion of the time when the LogRecord was created.
message%(message)sThe logged message, computed as msg % args. This is set when Formatter.format() is invoked.
msgYou shouldn’t need to format this yourself.The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
name%(name)sName of the logger used to log the call.
pathname%(pathname)sFull pathname of the source file where the logging call was issued (if available).
process%(process)dProcess ID (if available).
processName%(processName)sProcess name (if available).
relativeCreated%(relativeCreated)dTime in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
stack_infoYou shouldn’t need to format this yourself.Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
thread%(thread)dThread ID (if available).
threadName%(threadName)sThread name (if available).

Changed in version 3.1: processName was added.

16.6.8. LoggerAdapter Objects

LoggerAdapter实例用来方便的传递文本信息给logging调用。For a usage example, see the section on adding contextual information to your logging output.

class logging.LoggerAdapter(logger, extra)

Returns an instance of LoggerAdapter initialized with an underlying Logger instance and a dict-like object.

process(msg, kwargs)

Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as extra to the constructor and adds it to kwargs using key ‘extra’. The return value is a (msg, kwargs) tuple which has the (possibly modified) versions of the arguments passed in.

In addition to the above, LoggerAdapter supports the following methods of Logger: debug(), info(), warning(), error(), exception(), critical(), log(), isEnabledFor(), getEffectiveLevel(), setLevel() and hasHandlers(). These methods have the same signatures as their counterparts in Logger, so you can use the two types of instances interchangeably.

Changed in version 3.2: The isEnabledFor(), getEffectiveLevel(), setLevel() and hasHandlers() methods were added to LoggerAdapter. These methods delegate to the underlying logger.

16.6.9. Thread Safety

The logging module is intended to be thread-safe without any special work needing to be done by its clients. 它实现了这一点,虽然使用线程锁;有一个锁来串行访问模块的共享数据,并且每个处理程序还创建一个锁以串行化对其底层I / O的访问。

If you are implementing asynchronous signal handlers using the signal module, you may not be able to use logging from within such handlers. This is because lock implementations in the threading module are not always re-entrant, and so cannot be invoked from such signal handlers.

16.6.10. Module-Level Functions

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

logging.getLogger(name=None)

返回具有指定名称的记录器,如果名称为,则返回一个记录器,它是层次结构的根记录器。如果指定,名称通常是点分隔的分层名称,如'a''a.b''a.b.c.d'Choice of these names is entirely up to the developer who is using logging.

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.

logging.getLoggerClass()

Return either the standard Logger class, or the last class passed to setLoggerClass(). This function may be called from within a new class definition, to ensure that installing a customized Logger class will not undo customizations already applied by other code. For example:

class MyLogger(logging.getLoggerClass()):
    # ... override behaviour here
logging.getLogRecordFactory()

Return a callable which is used to create a LogRecord.

New in version 3.2: This function has been provided, along with setLogRecordFactory(), to allow developers more control over how the LogRecord representing a logging event is constructed.

See setLogRecordFactory() for more information about the how the factory is called.

logging.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 using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.

You can specify stack_info independently of exc_info, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says:

Stack (most recent call last):

This mimics the Traceback (most recent call last): which is used when displaying exception frames.

The third optional keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:

FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)

would print something like:

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the Formatter documentation for more information on which keys are used by the logging system.)

If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the Formatter has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the extra dictionary with these keys.

While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized Formatters would be used with particular Handlers.

New in version 3.2: The stack_info parameter was added.

logging.info(msg, *args, **kwargs)

Logs a message with level INFO on the root logger. The arguments are interpreted as for debug().

logging.warning(msg, *args, **kwargs)

Logs a message with level WARNING on the root logger. The arguments are interpreted as for debug().

Note

There is an obsolete function warn which is functionally identical to warning. As warn is deprecated, please do not use it - use warning instead.

logging.error(msg, *args, **kwargs)

Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug().

logging.critical(msg, *args, **kwargs)

Logs a message with level CRITICAL on the root logger. The arguments are interpreted as for debug().

logging.exception(msg, *args, **kwargs)

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.

logging.log(level, msg, *args, **kwargs)

Logs a message with level level on the root logger. The other arguments are interpreted as for debug().

Note

The above module-level convenience functions, which delegate to the root logger, call basicConfig() to ensure that at least one handler is available. Because of this, they should not be used in threads, in versions of Python earlier than 2.7.1 and 3.2, unless at least one handler has been added to the root logger before the threads are started. In earlier versions of Python, due to a thread safety shortcoming in basicConfig(), this can (under rare circumstances) lead to handlers being added multiple times to the root logger, which can in turn lead to multiple messages for the same event.

logging.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. Its effect is to disable all logging calls of severity lvl and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level. If logging.disable(logging.NOTSET) is called, it effectively removes this overriding level, so that logging output again depends on the effective levels of individual loggers.

logging.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.

Note

If you are thinking of defining your own levels, please see the section on Custom Levels.

logging.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. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string ‘Level %s’ % lvl is returned.

Note

Levels are internally integers (as they need to be compared in the logging logic). This function is used to convert between an integer level and the level name displayed in the formatted log output by means of the %(levelname)s format specifier (see LogRecord attributes).

Changed in version 3.4: In Python versions earlier than 3.4, this function could also be passed a text level, and would return the corresponding numeric value of the level. This undocumented behaviour was considered a mistake, and was removed in Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility.

logging.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.

logging.basicConfig(**kwargs)

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.

This function does nothing if the root logger already has handlers configured for it.

Note

This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log.

The following keyword arguments are supported.

FormatDescription
filenameSpecifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.
filemodeSpecifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to ‘a’).
formatUse the specified format string for the handler.
datefmtUse the specified date/time format.
styleIf format is specified, use this style for the format string. One of ‘%’, ‘{‘ or ‘$’ for %-formatting, str.format() or string.Template respectively, and defaulting to ‘%’ if not specified.
levelSet the root logger level to the specified level.
streamUse the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ‘filename’ - if both are present, a ValueError is raised.
handlersIf specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with ‘filename’ or ‘stream’ - if both are present, a ValueError is raised.

Changed in version 3.2: The style argument was added.

Changed in version 3.3: The handlers argument was added. Additional checks were added to catch situations where incompatible arguments are specified (e.g. handlers together with stream or filename, or stream together with filename).

logging.shutdown()

Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call.

logging.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.

logging.setLogRecordFactory(factory)

Set a callable which is used to create a LogRecord.

Parameters:factory – The factory callable to be used to instantiate a log record.

New in version 3.2: This function has been provided, along with getLogRecordFactory(), to allow developers more control over how the LogRecord representing a logging event is constructed.

The factory has the following signature:

factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)

name:The logger name.
level:The logging level (numeric).
fn:The full pathname of the file where the logging call was made.
lno:The line number in the file where the logging call was made.
msg:The logging message.
args:The arguments for the logging message.
exc_info:An exception tuple, or None.
func:The name of the function or method which invoked the logging call.
sinfo:A stack traceback such as is provided by traceback.print_stack(), showing the call hierarchy.
kwargs:Additional keyword arguments.

16.6.11. Module-Level Attributes

logging.lastResort

A “handler of last resort” is available through this attribute. This is a StreamHandler writing to sys.stderr with a level of WARNING, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to sys.stderr. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, lastResort can be set to None.

New in version 3.2.

16.6.12. Integration with the warnings module

The captureWarnings() function can be used to integrate logging with the warnings module.

logging.captureWarnings(capture)

This function is used to turn the capture of warnings by logging on and off.

If capture is True, warnings issued by the warnings module will be redirected to the logging system. Specifically, a warning will be formatted using warnings.formatwarning() and the resulting string logged to a logger named 'py.warnings' with a severity of WARNING.

If capture is False, the redirection of warnings to the logging system will stop, and warnings will be redirected to their original destinations (i.e. those in effect before captureWarnings(True) was called).

See also

Module logging.config
Configuration API for the logging module.
Module logging.handlers
Useful handlers included with the logging module.
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. 该站点此版本的包适用与Python 1.5.2, 2.1.x 和 2.2.x,在这些版本的Python标准库中并不包括logging包。