如何在Python中的自定义logging.Handler中获取日志记录的级别? [英] 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.
例如:
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
如果我通过重写emit方法使用自定义LoggerHandler,我无法区分日志记录的级别.还有其他可能获取记录级别的运行时信息吗?
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 know the level of the record (info, error, debug, critical)?
有什么建议吗?
推荐答案
record
是并且您的方法只能访问感兴趣的属性(为了方便阅读,我拆分了 dir
的结果):
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'
,依此类推.( rec.getMessage()
是您在 rec
上使用的一种方法,它将消息格式化为字符串,并插入参数).
and so on. (rec.getMessage()
is the one method you use on rec
-- it formats the message into a string, interpolating the arguments).
这篇关于如何在Python中的自定义logging.Handler中获取日志记录的级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!