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

4 投票
1 回答
5946 浏览
提问于 2025-04-16 00:06

我想创建一些自定义的日志记录方法,可以通过自定义的日志处理器或者自定义的日志类来实现,并把日志记录发送到不同的目标。

举个例子:

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)?

有什么建议吗?

1 个回答

12

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 上使用的唯一方法——它会把消息格式化成字符串,并把参数插入进去)。

撰写回答