在使用“logging”模块的Python中,文档承诺LogRecord实例将具有许多属性,这些属性在文档中明确列出。
然而,情况似乎并不总是如此。当我不使用日志记录模块的“basicConfig()”方法时,下面的程序显示属性“asctime”和“message”不存在于传递给 LogHandler 的“emit”方法的 LogRecord 中。
import logging
class LoggingHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
def emit(self, record):
assert isinstance(record, logging.LogRecord)
print("LoggingHandler received LogRecord: {}".format(record))
# List of LogRecord attributes expected when reading the
# documentation of the logging module:
expected_attributes = \
"args,asctime,created,exc_info,filename,funcName,levelname," \
"levelno,lineno,module,msecs,message,msg,name,pathname," \
"process,processName,relativeCreated,stack_info,thread,threadName"
for ea in expected_attributes.split(","):
if not hasattr(record, ea):
print("UNEXPECTED: LogRecord does not have the '{}' field!".format(ea))
loggingHandler = LoggingHandler()
rootLogger = logging.getLogger()
rootLogger.addHandler(loggingHandler)
# emit an WARNING message
logging.warning("WARNING MESSAGE")
在 Python 3 上运行它会给出:
$python3 test_logging.py
LoggingHandler received LogRecord: <LogRecord: root, 30, test_logging.py, 28, "WARNING MESSAGE">
UNEXPECTED: LogRecord does not have the 'asctime' field!
UNEXPECTED: LogRecord does not have the 'message' field!
这里发生了什么?我是否误解了文档?需要做什么来确保 LogRecord 实例具有承诺的“asctime”和“message”属性?