如何在Python中自定义logging.Handler中获取日志记录的级别?

kol*_*eto 4 python logging

我想通过自定义日志记录处理程序或自定义记录器类来创建自定义记录器方法,并将记录记录分派给不同的目标.

例如:

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
Run Code Online (Sandbox Code Playgroud)

如果我通过重写emit方法使用自定义LoggerHandler,我无法区分日志记录的级别.是否有任何其他可能性来获取记录级别的运行时信息?

class ApplicationLoggerHandler(logging.Handler):

  def emit(self, record):
    # at this place I need to know the level of the record (info, error, debug, critical)?
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Ale*_*lli 11

recordLogRecord的一个实例:

>>> import logging
>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)
Run Code Online (Sandbox Code Playgroud)

并且你的方法可以访问感兴趣的属性(我dir为了便于阅读而分割结果):

>>> 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'
Run Code Online (Sandbox Code Playgroud)

等等.(rec.getMessage()是您使用的一种方法rec- 它将消息格式化为字符串,插入参数).