为什么Python的logging模块自定义Filter无法输出给定级别的日志信息?

class CustomFilter(logging.Filter):
    def filter(self, record):
        message = record.getMessage()
        return 'custom' in message

customFilter = CustomFilter()

logger: Logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addFilter(customFilter)

logger.debug('This is a debug message with custom keyword')
logger.info('This is an info message with custom keyword')
logger.warning('This is a warning message with custom keyword')
logger.error('This is an error message with custom keyword')
logger.critical('This is a critical message with custom keyword')

为什么上述代码不会在控制台打印出 debug 和 info 级别的日志信息?

只会输出:

This is a warning message with custom keyword
This is an error message with custom keyword
This is a critical message with custom keyword
阅读 1.8k
2 个回答
✓ 已被采纳

不是filter的问题,是你使用的问题

import logging

logging.getLogger().setLevel(logging.DEBUG)

logging.debug("This is a debug message with custom keyword")
logging.info("This is an info message with custom keyword")
logging.warning("This is a warning message with custom keyword")
logging.error("This is an error message with custom keyword")
logging.critical("This is a critical message with custom keyword")
DEBUG:root:This is a debug message with custom keyword
INFO:root:This is an info message with custom keyword
WARNING:root:This is a warning message with custom keyword
ERROR:root:This is an error message with custom keyword
CRITICAL:root:This is a critical message with custom keyword

原因

image.png

正确的使用方法是

import logging


class CustomFilter(logging.Filter):
    def filter(self, record):
        message = record.getMessage()
        return "custom" in message


logger: logging.Logger = logging.getLogger(__file__)
handler = logging.StreamHandler()  # handler才是关键
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
customFilter = CustomFilter()
logger.addFilter(customFilter)

logger.debug("This is a debug message with custom keyword")
logger.info("This is an info message with custom keyword")
logger.warning("This is a warning message with custom keyword")
logger.error("This is an error message with custom keyword")
logger.critical("This is a critical message with custom keyword")

使用了自定义的 filter,该 filter 只会对包含 "custom" 关键字的日志信息进行过滤,只有 warning 级别及以上的日志信息中包含 "custom" 关键字,所以只输出了 warning、error 和 critical 级别的日志信息。

要在控制台打印出 debug 和 info 的日志信息,可以移除自定义的 filter 或者修改 filter 过滤条件,例如将 return 'custom' in message 修改为 return true(返回true),从而让所有日志信息都符合该 filter,即:不进行任何过滤。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏