您的位置 首页 知识分享

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

自定义日志过滤器无法输出指定级别日志的原因 在python中,日志模块提供了自定义过滤器,允许我们控制哪些日志…

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

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

在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’关键字的警告、错误和致命错误级别日志信息,但实际却只输出警告、错误和致命错误级别日志信息。

立即学习“”;

原因

问题不在于过滤器本身,而在于代码执行方式。正确的方法是使用日志句柄(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中文网其它相关文章!

本文来自网络,不代表甲倪知识立场,转载请注明出处:http://www.spjiani.cn/wp/5025.html

作者: nijia

发表评论

您的电子邮箱地址不会被公开。

联系我们

联系我们

0898-88881688

在线咨询: QQ交谈

邮箱: email@wangzhan.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部