简体   繁体   English

将stdout重定向到Python中的记录器

[英]Redirect stdout to logger in Python

Can I redirect all output from stdout to a logger I have set up with the standard logging module? 我可以将stdout所有输出重定向到我使用标准logging模块设置的logging器吗? (I have os.system calls whose output I'd also like to see or occational print statements) (我有os.system调用,其输出我也想看到或掩盖打印语句)

You might be able to make use of the suggestion in this post , summarised below: 你也许可以利用在建议的这个帖子 ,总结如下:

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()

When run, the script prints: 运行时,脚本会打印:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM