
<h3>python自定义日志过滤器无法输出指定级别日志的原因</h3>
在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')以上就是Python 自定义日志过滤器无法输出指定级别日志的原因是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号