LogRecord does not have expected fields
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Question
01:34 Accepted answer (Score 10)
03:03 Thank you
--
Full question
https://stackoverflow.com/questions/3230...
Accepted answer links:
[Formatter]: https://docs.python.org/3/library/loggin...
[format]: https://docs.python.org/3/library/loggin...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #logging
#avk47
ACCEPTED ANSWER
Score 13
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:
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.
Since your example code does not call self.format(record) it is therefore expected behaviour that those attributes are undefined.
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")