具有额外详细深度的 Python 日志级别

mbi*_*nov 4 python logging

我想扩展现有的logging.LEVEL机制,以便我可以选择在不同的日志记录级别(例如 、 等)之间切换DEBUGINFO同时还为每个级别ERROR定义。depth

例如,假设日志记录级别设置为logging.DEBUG。所有log.DEBUG()呼叫都将可见。

log.debug('Limit event has occurred.')
Run Code Online (Sandbox Code Playgroud)

所以我得到:

[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
Run Code Online (Sandbox Code Playgroud)

我所追求的是将额外的深度级别传递给调用log.debug(),以便我可以控制消息中打印的详细信息量DEBUG,而不是完全启用禁用调试级别,而是控制调试消息将携带多少信息。因此,在所有情况下,我们都会看到调试消息,但在某些情况下,它不太详细,并且在某些情况下包含更多信息。

例如:

log.debug('Limit event has occurred.', verbosity=1)
log.debug('The following user has caused the limit event: %s' % (user), verbosity=3)
log.debug('The following files have been affected: %s' % [list_of_files], verbosity=7)
Run Code Online (Sandbox Code Playgroud)

因此,当日志记录级别设置为DEBUG且全局详细程度设置为 时,GLOBAL_VERBOSITY=1我们将得到以下结果:

[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
Run Code Online (Sandbox Code Playgroud)

如果全局详细程度设置为,GLOBAL_VERBOSITY=4我们将得到:

[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) The following user has caused the limit event: xpr
Run Code Online (Sandbox Code Playgroud)

如果全局详细程度设置为,GLOBAL_VERBOSITY=9我们将获得所有详细信息:

[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) The following user has caused the limit event: xpr
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) The following files have been affected: ['inside.ini', 'render.so']
Run Code Online (Sandbox Code Playgroud)

我应该如何解决这个问题?

Dan*_*ott 5

难道不能使用更细粒度的日志记录级别吗?DEBUG只是 10 级的包装。您可以使用

Logger.log(10, "message")
Run Code Online (Sandbox Code Playgroud)

以调试级别记录,然后

Logger.log(9, "message")
Run Code Online (Sandbox Code Playgroud)

它不会在调试级别显示,但如果你这样做的话会显示

Logger.setLevel(9)
Run Code Online (Sandbox Code Playgroud)

如果您执意要以其他方式进行操作,则应该查看“过滤器”。

使用过滤器记录

#!/usr/bin/env python
import logging

GLOBAL_VERBOSITY = 1

class LoggingErrorFilter(logging.Filter):
  def filter(self, record):
    if record.__dict__.get("verbosity", 0) > GLOBAL_VERBOSITY:
      print "Log message verbosity is greater than threshold, logging line:{0}".format(record)
      return True
    print "Log message verbosity is lower than threshold, not logging line:{0}".format(record)
    return False

logging.basicConfig(level=logging.DEBUG, filename="test.log")

logger = logging.getLogger()

filter = LoggingErrorFilter()

logger.addFilter(filter)


def main():
    logger.info("Message 1", extra={"verbosity":3})
    logger.info("Message 2", extra={"verbosity":1})


if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)