
<h3>python的logging模块自定义filter无法输出指定级别的日志信息</h3>
在python中,使用logging模块来记录日志非常方便。有时,我们需要仅记录特定级别的日志信息。我们可以通过自定义过滤器来实现此目的。但是,在某些情况下,logging模块的自定义filter无法输出指定级别的日志信息。
问题
以下代码演示了此问题:
立即学习“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')问题是:为什么上述代码不会在控制台打印出debug和info级别的日志信息?
答案
这不是过滤器的问题,而是使用方式的问题。正确的方法如下:
import logging
logging.getLogger().setLevel(logging.DEBUG)
logging.debug("This is a debug message with custom keyword")
logging.info("This is an info message with custom keyword")
logging.warning("This is a warning message with custom keyword")
logging.error("This is an error message with custom keyword")
logging.critical("This is a critical message with custom keyword")原因
这是因为logging模块中的过滤器不是自动应用的。我们需要在日志记录程序中添加一个处理器(handler),处理器才能应用过滤器并输出日志信息。
在修改后的代码中,我们添加了一个streamhandler,该处理器将日志信息输出到控制台。现在,将正确应用过滤器,并且只有包含“custom”关键字的日志信息才会输出。
以上就是Python logging模块自定义Filter为何无法输出指定级别的日志信息?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号