问题描述
我不知道如何将信息级消息记录到标准输出,但其他所有信息都记录到标准错误.我已经读过这个 http://docs.python.org/library/logging.html.有什么建议吗?
以下脚本,log1.py
:
导入日志,sys类 SingleLevelFilter(logging.Filter):def __init__(self, passlevel, reject):self.passlevel = passlevelself.reject = 拒绝def过滤器(自我,记录):如果自我拒绝:返回 (record.levelno != self.passlevel)别的:返回(记录.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("一条调试消息")logger.info("一条信息消息")logger.warning("警告信息")logger.error("错误信息")logger.critical("一条关键信息")
运行时,产生以下结果.
C:emp>log1.py一条调试消息一条 INFO 消息警告信息错误信息一条重要信息如您所料,因为在终端上 sys.stdout
和 sys.stderr
是相同的.现在,让我们将标准输出重定向到一个文件,tmp
:
所以 INFO 消息还没有打印到终端 - 但是指向 sys.stderr
已 的消息已打印.让我们看看 tmp
中的内容:
所以这种方法似乎可以满足您的需求.
I can't figure out how to log info-level messages to stdout, but everything else to stderr. I already read this http://docs.python.org/library/logging.html. Any suggestion?
The following script, log1.py
:
import logging, sys
class 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")
when run, produces the following results.
C: emp>log1.py A DEBUG message An INFO message A WARNING message An ERROR message A CRITICAL message
As you'd expect, since on a terminal sys.stdout
and sys.stderr
are the same. Now, let's redirect stdout to a file, tmp
:
C: emp>log1.py >tmp A DEBUG message A WARNING message An ERROR message A CRITICAL message
So the INFO message has not been printed to the terminal - but the messages directed to sys.stderr
have been printed. Let's look at what's in tmp
:
C: emp>type tmp An INFO message
So that approach appears to do what you want.
这篇关于日志记录、StreamHandler 和标准流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!