Python logging模块自定义Filter失效了?如何正确使用Filter筛选日志信息?

python logging模块自定义filter失效了?如何正确使用filter筛选日志信息?

深入探讨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生成,不代表软件指南立场。本站不负任何法律责任。

如若转载请注明出处:http://www.down96.com/tutorials/12683.html

热心网友热心网友
上一篇 2025-04-11 17:05
下一篇 2025-04-11 17:05

相关推荐

本站[软件指南]所有内容来自互联网投稿或AI智能生成,并不代表软件指南的立场。