Python之logging模块 logging是python标准库中的模块,用于给程序添加日志,借此方便我们回溯程序的执行过程。

基本用法

以下面代码为例,介绍logging模块的基本用法:

import logging

logging.basicConfig(filename="example.log", filemode="a", format="%(levelname)s:%(message)s", level=logging.DEBUG)

logging.debug(">>>>>Log Message: %s, %s" % ("Hello", "I'm debug log"))
logging.info(">>>>>Log Message: %s, %s" % ("Hello", "I'm info log"))
logging.warning(">>>>>Log Message: %s, %s" % ("Hello", "I'm warning log"))
logging.error(">>>>>Log Message: %s, %s" % ("Hello", "I'm error log"))
logging.critical(">>>>>Log Message: %s, %s" % ("Hello", "I'm critical log"))

该段代码会把日志输出到名为"example.log"的文件中,并规定了日志的输出格式及最低日志级别,输出结果如下:

DEBUG:>>>>>Log Message: Hello, I'm debug log
INFO:>>>>>Log Message: Hello, I'm info log
WARNING:>>>>>Log Message: Hello, I'm warning log
ERROR:>>>>>Log Message: Hello, I'm error log
CRITICAL:>>>>>Log Message: Hello, I'm critical log

日志级别

logging模块中初始定义了五个日志级别,如表格所示。由上到下,级别对应的严重程度依次增加。在文章开头的例子中,我们调用logging.basicConfig()配置了想要输出的日志最低级别为DEBUG,这意味着DEBUG及其以上等级的日志都会被输出。同理,如果我们只想输出ERROR及以上的日志,则令level=logging.ERROR即可。

级别

|

何时使用

---|---

DEBUG

|

细节信息,仅当诊断问题时适用。

INFO

|

确认程序按预期运行

WARNING

|

表明有已经或即将发生的意外(例如:磁盘空间不足)。程序仍按预期进行

ERROR

|

由于严重的问题,程序的某些功能已经不能正常执行

CRITICAL

|

严重的错误,表明程序已不能继续执行

LogRecord属性

在logging.basicConfig()中,我们使用了format="%(levelname)s:%(message)s"来规定日志的输出格式。其中levelname和message都是LogRecord属性,它们能出现在format字符串中,令输出结果带上了日志等级名、日志消息。其他可以出现在format字符串中的内容,参见下表:

属性名称

|

格式

|

描述

---|---|---

args

|

不需要格式化。

|

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)s

|

Human-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)f

|

Time when the LogRecord was created (as returned by time.time()).

exc_info

|

不需要格式化。

|

Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.

filename

|

%(filename)s

|

Filename portion of pathname.

funcName

|

%(funcName)s

|

Name of function containing the logging call.

levelname

|

%(levelname)s

|

Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').

levelno

|

%(levelno)s

|

Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).

lineno

|

%(lineno)d

|

Source line number where the logging call was issued (if available).

message

|

%(message)s

|

The logged message, computed as msg % args. This is set when Formatter.format() is invoked.

module

|

%(module)s

|

模块 (filename 的名称部分)。

msecs

|

%(msecs)d

|

Millisecond portion of the time when the LogRecord was created.

msg

|

不需要格式化。

|

The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see 使用任意对象作为消息).

name

|

%(name)s

|

Name of the logger used to log the call.

pathname

|

%(pathname)s

|

Full pathname of the source file where the logging call was issued (if available).

process

|

%(process)d

|

进程ID(如果可用)

processName

|

%(processName)s

|

进程名(如果可用)

relativeCreated

|

%(relativeCreated)d

|

Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.

stack_info

|

不需要格式化。

|

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)d

|

线程ID(如果可用)

threadName

|

%(threadName)s

|

线程名(如果可用)

输出方式

在logging.basicConfig()中,我们使用了filename="example.log", filemode="a"来令日志输出至某个文件。如果不带filename和filemode参数,则会把日志直接打印出来。filemode参数值默认为"a",意味着在原有日志的基础上,追加写新的日志;如果不想追加写新的日志,而是覆盖原有的日志,令filemode="w"即可。

最后说明,本篇文章只对logging模块的基本用法做了介绍,logging模块还有更多强大的功能供使用,可以通过官方文档了解。

参考资料