
自定义 logging 过滤器无法打印指定等级日志信息的问题
给定以下 python 代码:
class 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')
代码中使用了自定义日志过滤器 customfilter,意图只打印包含 ‘custom’ 字符串的日志信息。然而,运行代码后,我们发现控制台只打印了警告、错误和严重错误级别的日志信息,而调试和信息级别的日志信息却不见踪影。
问题原因
问题不在于自定义过滤器本身,而在于代码的使用方式。在给定的代码中,我们没有为日志器添加处理程序(handler),因此日志信息没有地方输出。
正确的做法是先创建一个 handler,再将其添加到日志器中。常用的 handler 有 streamhandler,它将日志信息输出到控制台。
修改后的代码
import logging# 创建一个流处理程序,将日志信息输出到控制台handler = logging.StreamHandler()# 创建一个自定义日志过滤器class CustomFilter(logging.Filter): def filter(self, record): message = record.getMessage() return 'custom' in message# 创建一个日志器,并为其设置级别、添加过滤器和处理程序logger = logging.getLogger(__file__)logger.setLevel(logging.DEBUG)logger.addFilter(CustomFilter())logger.addHandler(handler)# 记录不同等级的日志信息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’ 字符串的调试和信息级别的日志信息。
以上就是为什么自定义 logging 过滤器无法打印指定等级日志信息?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1353146.html
微信扫一扫
支付宝扫一扫