为什么自定义 logging 过滤器无法打印指定等级日志信息?
怎么入门文章编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《为什么自定义 logging 过滤器无法打印指定等级日志信息?》,涉及到,有需要的可以收藏一下
给定以下 python 代码:
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')
代码中使用了自定义日志过滤器 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 过滤器无法打印指定等级日志信息?》文章吧,也可关注公众号了解相关技术文章。