以下脚本
log1.py:
import logging, sysclass SingleLevelFilter(logging.Filter): def __init__(self, passlevel, reject): self.passlevel = passlevel self.reject = reject def filter(self, record): if self.reject: return (record.levelno != self.passlevel) else: return (record.levelno == self.passlevel)h1 = logging.StreamHandler(sys.stdout)f1 = SingleLevelFilter(logging.INFO, False)h1.addFilter(f1)rootLogger = logging.getLogger()rootLogger.addHandler(h1)h2 = logging.StreamHandler(sys.stderr)f2 = SingleLevelFilter(logging.INFO, True)h2.addFilter(f2)rootLogger.addHandler(h2)logger = logging.getLogger("my.logger")logger.setLevel(logging.DEBUG)logger.debug("A DEBUG message")logger.info("An INFO message")logger.warning("A WARNING message")logger.error("An ERROR message")logger.critical("A CRITICAL message")
运行时,产生以下结果。
C: temp> log1.py调试消息INFO消息警告消息错误消息关键信息
正如你所期望的,因为在终端上
sys.stdout,并
sys.stderr是相同的。现在,让我们将标准输出重定向到文件
tmp:
C: temp> log1.py> tmp调试消息警告消息错误消息关键信息
因此,INFO消息没有被打印到终端-但指示消息
sys.stderr已 被打印。让我们看一下其中的内容
tmp:
C: temp>输入tmpINFO消息
So that approach appears to do what you want.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)