深入探究Python logging模块自定义Filter失效的原因
本文分析一个Python logging模块自定义Filter失效的常见问题。代码中自定义了一个Filter,预期只输出包含“custom”关键字的日志信息,但实际只输出了警告、错误和严重错误级别的日志。我们将分析问题原因并提供正确的使用方法。
问题代码及分析:
以下代码演示了问题所在:
立即学习“Python免费学习笔记(深入)”;
import logging class customfilter(logging.Filter): def filter(self, record): message = record.getMessage() return 'custom' in message customfilter = customfilter() logger: logging.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')
运行这段代码,你只会看到警告、错误和严重错误级别的日志。 这并非Filter本身的问题,而是因为缺少日志处理器(Handler)。getLogger() 获取的根日志器默认没有处理器,setLevel() 只设置了日志级别(决定哪些级别日志会被处理),而addFilter() 仅控制日志记录是否通过,但日志记录需要通过处理器才能输出。
正确的代码及解释:
正确的代码如下:
import logging class CustomFilter(logging.Filter): def filter(self, record): message = record.getMessage() return "custom" in message logger: logging.Logger = logging.getLogger(__name__) # 使用 __name__ 更佳 handler = logging.StreamHandler() # 添加日志处理器 handler.addFilter(CustomFilter()) # 将filter添加到handler logger.addHandler(handler) logger.setLevel(logging.DEBUG) 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”关键字的日志信息(无论级别)才会被输出到控制台。 这才是解决自定义Filter失效问题的关键。 通过这个例子,我们学习到,logging模块中,Handler负责输出日志,Filter负责过滤日志,两者缺一不可。
以上就是Python logging模块自定义Filter失效的原因是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号