
python自定义日志过滤器无法输出指定级别日志的原因
在python中,日志模块提供了自定义过滤器,允许我们控制哪些日志信息被输出。然而,有时自定义过滤器无法正常工作,导致无法输出指定级别的日志信息。
考虑以下代码段:
import logging
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')这段代码预期只会输出包含'custom'关键字的警告、错误和致命错误级别日志信息,但实际却只输出警告、错误和致命错误级别日志信息。
立即学习“Python免费学习笔记(深入)”;
原因
问题不在于过滤器本身,而在于代码执行方式。正确的方法是使用日志句柄(handler),例如:
import logging
import sys
class CustomFilter(logging.Filter):
def filter(self, record):
message = record.getMessage()
return 'custom' in message
logger: logging.Logger = logging.getLogger(__file__)
handler = logging.StreamHandler(sys.stdout) # 关键在于此
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')










