
给定以下 python 代码:
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')代码中使用了自定义日志过滤器 customfilter,意图只打印包含 'custom' 字符串的日志信息。然而,运行代码后,我们发现控制台只打印了警告、错误和严重错误级别的日志信息,而调试和信息级别的日志信息却不见踪影。
问题不在于自定义过滤器本身,而在于代码的使用方式。在给定的代码中,我们没有为日志器添加处理程序(handler),因此日志信息没有地方输出。
正确的做法是先创建一个 handler,再将其添加到日志器中。常用的 handler 有 streamhandler,它将日志信息输出到控制台。
import logging
# 创建一个流处理程序,将日志信息输出到控制台
handler = logging.StreamHandler()
# 创建一个自定义日志过滤器
class CustomFilter(logging.Filter):
def filter(self, record):
message = record.getMessage()
return 'custom' in message
# 创建一个日志器,并为其设置级别、添加过滤器和处理程序
logger = logging.getLogger(__file__)
logger.setLevel(logging.DEBUG)
logger.addFilter(CustomFilter())
logger.addHandler(handler)
# 记录不同等级的日志信息
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')修改后的代码将正确地打印包含 'custom' 字符串的调试和信息级别的日志信息。
以上就是为什么自定义 logging 过滤器无法打印指定等级日志信息?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号