python - 将标准输出重定向到 Python 中的记录器

标签 python logging stdout

我可以将所有输出从 stdout 重定向到我使用标准 logging 模块设置的记录器吗? (我有 os.system 调用,我也想查看其输出或偶尔的打印语句)

最佳答案

您可以利用 this post 中的建议,总结如下:

import logging

class LoggerWriter:
    def __init__(self, logger, level):
        self.logger = logger
        self.level = level

    def write(self, message):
        if message != '\n':
            self.logger.log(self.level, message)

def main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("demo")
    info_fp = LoggerWriter(logger, logging.INFO)
    debug_fp = LoggerWriter(logger, logging.DEBUG)
    print >> info_fp, "An INFO message"
    print >> debug_fp, "A DEBUG message"

if __name__ == "__main__":
    main()

运行时,脚本打印:

INFO:demo:An INFO message
DEBUG:demo:An DEBUG message

关于python - 将标准输出重定向到 Python 中的记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410760/

相关文章:

c# - 让 NLog 发送带有正确 header 的 JSON?

python - 将 pandas.dataframe.plot() 与 matplotlib.pyplot.plot() 结合的最佳方法是什么?

scala - 使用 Scala 中的简单表达式链接日志记录

python - 使用 .loc 在 Pandas 中进行多选

.Net:如何抑制 TraceSource header ("SourceName TraceEventType: Id : ")?

java - 拦截源自 Tess4J 的控制台输出

audio - 让 gstreamer 将音频流拆分为单个输出流中的多个连接但离散的文件?

go - 重定向Go中子进程的stdout管道

Python Django 模板 : Iterate Through List

python - PyQt:如何将 QStandardItemModel 中的 QStandardItem 连接到函数