在使用“日志记录”模块的Python中,文档保证LogRecord实例将具有许多属性,这些属性在文档中明确列出。
但是,似乎并非总是如此。当我不使用日志记录模块的'basicConfig()'方法时,下面的程序显示在传递给LogHandler的'emit'方法的LogRecords中不存在属性'asctime'和'message'。
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")
Run Code Online (Sandbox Code Playgroud)
在Python 3上运行可以得到:
$python3 test_logging.py
LoggingHandler received LogRecord: <LogRecord: …Run Code Online (Sandbox Code Playgroud)