首页 > 解决方案 > 在 python 3 中捕获日志消息

问题描述

我想捕获python程序打印的日志,并将其保存到变量或文件中。有没有办法在不添加处理程序或修改记录器配置的情况下实现这一点?(这是因为 logger 类将被许多其他模块使用,我们希望它是通用的)

代码片段:

import logging
from io import StringIO
from contextlib import redirect_stdout

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")

with StringIO() as buf, redirect_stdout(buf), open("test.txt", "w+") as f:
    logger.debug("Debug message")
    logger.info("Info message")
    logger.error("Error message")
    buf.flush()
    f.write(buf.getvalue())

控制台输出:

xxxx-xx-xx xx:xx:xx,xxx DEBUG Debug message
xxxx-xx-xx xx:xx:xx,xxx INFO Info message
xxxx-xx-xx xx:xx:xx,xxx ERROR Error message

让我感到困惑的是,由于 logger 默认将所有日志打印到标准输出,使用上下文管理器重定向标准输出应该可以解决问题。但是,日志仍会打印到控制台,并且不会将任何内容写入文件。任何想法?

标签: python-3.xloggingio

解决方案


日志库已经有一个实用程序。

假设您想开始在文件中记录事件my.log然后

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.info('Some info')
logging.warning('Some warning')
logging.debug('Debug messages')

有关更多信息,请查看python 文档

编辑:OP询问是否有其他方法可以在不使用basicConfig方法的情况下做到这一点。是我发现的另一种利用文件处理程序的方法。使用它,您可以单独声明文件处理程序,然后将其分配给记录器。

logger = logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")

# create file handler
fh = logging.FileHandler('my.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)

推荐阅读