为什么Python的logging模块自定义Filter无法输出给定级别的日志信息?
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 级别的日志信息?
只会输出:
This is a warning message with custom keyword
This is an error message with custom keyword
This is a critical message with custom keyword
回复
1个回答

test
2024-07-04
不是filter的问题,是你使用的问题
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")
DEBUG:root:This is a debug message with custom keyword
INFO:root:This is an info message with custom keyword
WARNING:root:This is a warning message with custom keyword
ERROR:root:This is an error message with custom keyword
CRITICAL:root:This is a critical message with custom keyword
原因
正确的使用方法是
import logging
class CustomFilter(logging.Filter):
def filter(self, record):
message = record.getMessage()
return "custom" in message
logger: logging.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")
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容