关于日志记录:如何在Python中记录源文件名和行号

How to log source file name and line number in Python

是否可以装饰/扩展python标准日志记录系统,以便在调用日志记录方法时,它还会记录文件和调用它的行号,或者调用它的方法?


当然,检查记录文档中的格式化程序。 特别是lineno和pathname变量。

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

%(filename)s Filename portion of pathname.

%(module)s Module (name portion of filename).

%(funcName)s Name of function containing the logging call.

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

看起来像这样:

1
formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')


除了Seb非常有用的答案之外,这里还有一个方便的代码片段,它以合理的格式演示了记录器的使用情况:

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
import logging

logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d:%H:%M:%S',
    level=logging.DEBUG)

logger = logging.getLogger(__name__)
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")

生成此输出:

1
2
3
4
2017-06-06:17:07:02,158 DEBUG    [log.py:11] This is a debug log
2017-06-06:17:07:02,158 INFO     [log.py:12] This is an info log
2017-06-06:17:07:02,158 CRITICAL [log.py:13] This is critical
2017-06-06:17:07:02,158 ERROR    [log.py:14] An error occurred


要以将调试日志记录发送到标准输出的方式构建上述内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
FORMAT ="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
formatter = logging.Formatter(FORMAT)
ch.setFormatter(formatter)
root.addHandler(ch)

logging.debug("I am sent to standard out.")

将上述内容放入名为debug_logging_example.py的文件中会产生输出:

1
[debug_logging_example.py:14 -             <module>() ] I am sent to standard out.

然后,如果要关闭记录注释root.setLevel(logging.DEBUG)

对于单个文件(例如类分配),我发现这是一种更好的方法,而不是使用print()语句。 它允许您在提交之前在单个位置关闭调试输出。