Python 3.x 在Python3中捕获日志消息

Python 3.x 在Python3中捕获日志消息,python-3.x,logging,io,Python 3.x,Logging,Io,我想捕获python程序打印的日志,并将其保存到变量或文件中。有没有办法在不添加处理程序或修改记录器配置的情况下实现这一点?(这是因为logger类将被许多其他模块使用,我们希望它是通用的) 代码段: import logging from io import StringIO from contextlib import redirect_stdout logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelna

我想捕获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

让我困惑的是,由于记录器默认将所有日志打印到stdout,所以使用上下文管理器重定向stdout应该可以做到这一点。但是,日志仍然打印到控制台,并且没有写入任何文件。有什么想法吗?

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

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

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.info('Some info')
logging.warning('Some warning')
logging.debug('Debug messages')
有关更多信息,请查看

Edit: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)

有条件地添加额外的处理程序对您来说是正确的方式,初始化时说,如果os.environ[“YourTeam\u YourLogger\u Debug”]=“ON”,您可以附加另一个rsys日志处理程序。否则,您将不得不跟踪/嗅探文件更改,而这是最糟糕的。但是,我不想更改日志记录的基本配置。有没有其他方法获取信息?@Steph我已经更新了答案。编辑的部分可能会对您有所帮助。