◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
python logging模块自定义filter无法输出给定级别的日志信息的原因
在python中使用logging模块时,自定义filter无法输出特定级别的日志信息,这可能是由于你使用handler不当造成的。
以下代码演示了正确的方法:
import logging class CustomFilter(logging.Filter): def filter(self, record): message = record.getMessage() return "custom" in message logger = logging.getLogger(__file__) handler = logging.StreamHandler() # 关键步骤:添加handler 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")
运行此代码后,你会在控制台中看到所有级别的日志信息,包括debug和info级别的信息。
立即学习“Python免费学习笔记(深入)”;
原因:
默认情况下,logger没有输出目的地。通过添加handler,你可以将日志信息定向到控制台或其他目的地。如果不添加handler,即使添加了filter,日志信息也不会输出。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。