本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

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

网络教程 app 1℃

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

原因

问题不在于过滤器本身,而在于代码执行方式。正确的方法是使用日志句柄(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 自定义日志过滤器无法输出指定级别日志的原因是什么?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » Python自定义日志过滤器无法输出指定级别日志的原因是什么?

喜欢 (0)