我一直在尝试使用Python的日志记录模块。我的大部分基础工作都非常有用。但是,在我想要控制记录器的水平时,我碰到了一堵墙。
以下是我尝试实现的日志记录行为的表示:
if verbosityState == 0:
# Total silence
elif verbosityState == 1:
# Display only INFO, ERROR, CRITICAL
elif verbosityState == 2:
# Display INFO, DEBUG, ERROR, CRITICAL
elif verbosityState > 2:
# Display INFO, DEBUG, ERROR, CRITICAL, WARNING
else:
# Total silence
我在stackoverflow上找到了以下解决方案here,它涉及继承FILTER类并创建自定义过滤器。不幸的是,我无法适应我的情况。
你能帮帮我吗?
感谢。
答案 0 :(得分:1)
您可以使用自定义Filter
,就像您链接的答案一样:
class CustomFilter(logging.Filter):
def __init__(self, state):
self.state = state
def filter(self, record):
if self.state == 1:
return record.levelno in [logging.INFO, logging.ERROR,
logging.CRITICAL]
elif self.state == 2:
return record.levelno in [logging.INFO, logging.DEBUG,
logging.ERROR, logging.CRITICAL]
elif self.state > 2:
return record.levelno in [logging.INFO, logging.DEBUG,
logging.ERROR, logging.CRITICAL,
logging.WARNING]
else:
return False
h1 = logging.StreamHandler(sys.stdout)
logger = logging.getLogger("my.logger")
logger.setLevel(logging.DEBUG)
print("No logging:")
f1 = CustomFilter(0)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
print ("Level 1:")
h1.removeFilter(f1)
f1 = CustomFilter(1)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
print("Level 2:")
h1.removeFilter(f1)
logger.removeHandler(h1)
f1 = CustomFilter(2)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
print("Level 3:")
h1.removeFilter(f1)
logger.removeHandler(h1)
f1 = CustomFilter(3)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
输出:
No logging:
Level 1:
info
error
critical
Level 2:
info
debug
error
critical
Level 3:
info
debug
error
warning
critical