繁体   English   中英

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

[英]How to get the level of the logging record in a custom logging.Handler in Python?

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

例如:

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,我无法区分日志记录的级别。 是否有任何其他可能性来获取记录级别的运行时信息?

class ApplicationLoggerHandler(logging.Handler):

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

有什么建议么?

recordLogRecord的一个实例:

>>> import logging
>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)

并且你的方法可以访问感兴趣的属性(为了便于阅读,我正在分割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'

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM