日志记录,StreamHandler和标准流 [英] Logging, StreamHandler and standard streams

查看:134
本文介绍了日志记录,StreamHandler和标准流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何将信息级别的消息记录到stdout,但将其他所有内容记录到stderr.我已经阅读过 http://docs.python.org/library/logging.html .有什么建议吗?

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?

推荐答案

以下脚本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:\temp>log1.py
A DEBUG message
An INFO message
A WARNING message
An ERROR message
A CRITICAL message

如您所料,因为在终端上,sys.stdoutsys.stderr是相同的.现在,让我们将标准输出重定向到文件tmp:

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:\temp>log1.py >tmp
A DEBUG message
A WARNING message
An ERROR message
A CRITICAL message

因此尚未将INFO消息打印到终端-但是已经打印了指向sys.stderr 的消息.让我们看看tmp中的内容:

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:\temp>type tmp
An INFO message

这种方法似乎可以满足您的要求.

So that approach appears to do what you want.

这篇关于日志记录,StreamHandler和标准流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆