有没有可能修饰/扩展python标准日志记录系统,以便在调用日志记录方法时,它还会记录被调用的文件和行号或者调用它的方法?
发布于 2017-06-07 08:08:32
在Seb's very useful answer之上,下面是一个方便的代码片段,它以合理的格式演示了记录器的用法:
#!/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")
生成以下输出:
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
发布于 2020-02-05 03:07:49
# your imports above ...
logging.basicConfig(
format='%(asctime)s,%(msecs)d %(levelname)-8s [%(pathname)s:%(lineno)d in
function %(funcName)s] %(message)s',
datefmt='%Y-%m-%d:%H:%M:%S',
level=logging.DEBUG
)
logger = logging.getLogger(__name__)
# your classes and methods below ...
# An naive Sample of usage:
try:
logger.info('Sample of info log')
# your code here
except Exception as e:
logger.error(e)
与其他答案不同,这将记录文件的完整路径和可能发生错误的函数名。如果您的项目包含多个模块,并且在这些模块中分布了多个同名文件,则此功能非常有用。
发布于 2018-09-20 01:36:43
要以将调试日志发送到标准输出的方式构建上述内容:
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
的文件中会产生以下输出:
[debug_logging_example.py:14 - <module>() ] I am sent to standard out.
然后,如果您想关闭日志记录,请注释掉root.setLevel(logging.DEBUG)
。
对于单个文件(例如类分配),我发现与使用print()
语句相比,这是一种更好的方法。它允许您在提交之前在单个位置关闭调试输出。
https://stackoverflow.com/questions/533048
复制相似问题