LogRecord does not have expected fields
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping
--
Chapters
00:00 Logrecord Does Not Have Expected Fields
01:17 Accepted Answer Score 13
02:40 Thank you
--
Full question
https://stackoverflow.com/questions/3230...
--
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")