Python 自定义日志过滤器无法输出指定级别日志的原因是什么?

python 自定义日志过滤器无法输出指定级别日志的原因是什么?

python自定义日志过滤器无法输出指定级别日志的原因

在python中,日志模块提供了自定义过滤器,允许我们控制哪些日志信息被输出。然而,有时自定义过滤器无法正常工作,导致无法输出指定级别的日志信息。

考虑以下代码段:

import loggingclass customfilter(logging.filter):    def filter(self, record):        message = record.getmessage()        return 'custom' in messagecustomfilter = 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 loggingimport sysclass CustomFilter(logging.Filter):    def filter(self, record):        message = record.getMessage()        return 'custom' in messagelogger: 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 自定义日志过滤器无法输出指定级别日志的原因是什么?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1353126.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 17:25:36
下一篇 2025年12月13日 17:25:48

相关推荐

发表回复

登录后才能评论
关注微信