简体   繁体   English

如何在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. 我想通过自定义日志记录处理程序或自定义记录器类来创建自定义记录器方法,并将记录记录分派给不同的目标。

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. 如果我通过重写emit方法使用自定义LoggerHandler,我无法区分日志记录的级别。 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)?

Any suggestions? 有什么建议么?

record is an instance of LogRecord : recordLogRecord的一个实例:

>>> 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的结果):

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

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

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