我需要一种方法让python记录器不记录ERROR或更高版本。需要它只记录少于ERROR。
import logging
from logging import StreamHandler
def get_log_formatter():
datefmt = '%b %d %y %H:%M:%S'
formatter = logging.Formatter('%(asctime)s [%(module)s:%(levelname)s] %(message)s',
datefmt=datefmt)
return formatter
class MyHandler(StreamHandler):
def __init__(self, max_level, *args, **kwargs):
super(MyHandler, self).__init__(*args, **kwargs)
self.max_level = max_level
def emit(self, record):
if record.levelno >= self.max_level:
return
return super(MyHandler, self).emit(record)
handl = MyHandler(logging.ERROR)
handl.setLevel(logging.INFO)
handl.setFormatter(get_log_formatter())
logger = logging.getLogger("testing_logger")
logger.addHandler(handl)
logger.setLevel(logging.INFO)
这似乎有效,但它有意义吗?有没有更好的方法来过滤掉日志?
In [3]: logger_num = 0
In [4]: logger = remake()
In [5]: logger.info("Why")
May 16 01 16:50:10 [<ipython-input-5-c350362291ad>:INFO] Why
In [6]: logger.warn("Why")
May 16 01 16:50:13 [<ipython-input-6-56809439d5a4>:WARNING] Why
In [7]: logger.error("Why")
In [8]:
答案 0 :(得分:0)
回顾你的解决方案是你必须继承你想要使用的每个处理程序。
上下文过滤器的意图更清晰:
class MaxFilter:
def __init__(max_level):
self.max_level = max_level
def filter(self, record):
if record.levelno < self.max_level:
return True
并且可以应用于任何处理程序:
any_concrete_handler.addFilter(MaxFilter(logging.INFO))