深入探讨Python logging模块自定义Filter失效问题
在使用Python的logging模块时,自定义Filter来筛选日志信息是常见需求。然而,有时自定义的Filter却无法正常工作,导致部分日志信息丢失。本文将通过一个案例分析,解释为什么自定义Filter未能过滤debug和info级别的日志,并提供正确的解决方案。
问题描述:
以下代码意图使用自定义Filter仅输出包含”custom”关键字的日志信息:
立即学习“Python免费学习笔记(深入)”;
import loggingclass customfilter(logging.Filter): def filter(self, record): message = record.getmessage() return 'custom' in messagecustomfilter_instance = customfilter()logger = logging.getLogger()logger.setLevel(logging.DEBUG)logger.addFilter(customfilter_instance)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')
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。