LogRecord没有期望的字段 [英] LogRecord does not have expected fields
问题描述
在使用日志记录"模块的Python中,该文档保证LogRecord实例将具有许多属性,这些属性已在文档中明确列出.
In Python using the "logging" module, the documentation promises that LogRecord instances will have a number of attributes, which are explicitly listed in the documentation.
但是,似乎并非总是如此.当我不使用日志记录模块的'basicConfig()'方法时,下面的程序将显示在传递给LogHandler的'emit'方法的LogRecords中不存在属性'asctime'和'message'.
However, it appears that this is not always true. When I do not use the logging module's 'basicConfig()' method, the program below shows that the attributes 'asctime' and 'message' are not present in the LogRecords that are passed to the LogHandler's 'emit' method.
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上运行此操作可得出:
Running this on Python 3 gives:
$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'属性,需要做些什么?
What is going on here? Did I misunderstand the documentation? What needs to be done to make sure that the LogRecord instances have the 'asctime' and 'message' attributes as promised?
推荐答案
这是 Formatter
设置asctime
和message
,因此在调用self.format(record)
之前,这些属性是未定义的.从 format
方法的文档中:
It is responsibility of the Formatter
to set asctime
and message
so prior to calling self.format(record)
, those attributes are undefined. From the doc of the format
method:
记录的属性字典用作字符串的操作数 格式化操作.返回结果字符串.格式化之前 在字典中,需要执行几个准备步骤.这 使用msg%args计算记录的message属性.如果 格式化字符串包含'(asctime)',formatTime()被调用为 格式化事件时间.
The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using msg % args. If the formatting string contains '(asctime)', formatTime() is called to format the event time.
由于您的示例代码未调用 self.format(record)
,因此可以预料到这些属性未定义.
Since your example code does not call self.format(record)
it is therefore expected behaviour that those attributes are undefined.
要设置message
和asctime
,必须首先在emit
方法内调用self.format(record)
.请尝试
To have message
and asctime
set, you must first call self.format(record)
inside the emit
method. Please try
import logging
class LoggingHandler(logging.Handler):
def emit(self, record):
assert isinstance(record, logging.LogRecord)
print("LoggingHandler received LogRecord: {}".format(record))
self.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))
formatter = logging.Formatter("%(asctime)s")
loggingHandler = LoggingHandler()
loggingHandler.setFormatter(formatter)
rootLogger = logging.getLogger()
rootLogger.addHandler(loggingHandler)
# emit an WARNING message
logging.warning("WARNING MESSAGE")
这篇关于LogRecord没有期望的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!