How to get the level of the logging record in a custom logging.Handler in Python?
I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets.
For example:
log = logging.getLogger('application')
log.progress('time remaining %d sec' % i)
custom method for logging to:
- database status filed
- console custom handler showing changes in a single console line
log.data(kindOfObject)
custom method for logging to:
- database
- special data format
log.info
log.debug
log.error
log.critical
all standard logging methods:
- database status/error/debug filed
- console: append text line
- logfile
If I use a custom LoggerHandler by overriding the emit method, I can not distinguishe the level of the logging record. Is there any other posibility to get in runtime information of the record level?
class ApplicationLoggerHandler(logging.Handler):
def emit(self, record):
# at this place I need to kn开发者_开发问答ow the level of the record (info, error, debug, critical)?
Any suggestions?
record
is an instance of LogRecord:
>>> import logging
>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)
and your method can just access the attributes of interest (I'm splitting dir
's result for ease of reading):
>>> dir(rec)
['__doc__', '__init__', '__module__', '__str__', 'args', 'created',
'exc_info', 'exc_text', 'filename', 'funcName', 'getMessage', 'levelname',
'levelno', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process',
'processName', 'relativeCreated', 'thread', 'threadName']
>>> rec.levelno
1
>>> rec.levelname
'Level 1'
and so on. (rec.getMessage()
is the one method you use on rec
-- it formats the message into a string, interpolating the arguments).
精彩评论