【问题标题】:Capture logging message in python 3在 python 3 中捕获日志消息
【发布时间】:2020-01-03 07:29:09
【问题描述】:

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

代码sn-p:

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 默认将所有日志打印到标准输出,使用上下文管理器重定向标准输出应该可以解决问题。但是,日志仍会打印到控制台,并且不会将任何内容写入文件。有什么想法吗?

【问题讨论】:

  • 有条件地添加额外的处理程序对你来说是正确的方法,初始化时说,如果 os.environ["YourTeam_YourLogger_Debug"] == "ON" ,你附加另一个 rsys 日志处理程序。否则,您将不得不跟踪/嗅探文件更改,而这是最糟糕的。

标签: python-3.x logging io


【解决方案1】:

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

假设您想开始在文件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 documentation

编辑:OP询问是否有不使用basicConfig方法的替代方法。 Here 是我发现的另一种利用文件处理程序的方法。使用它,您可以单独声明一个文件处理程序,然后将其分配给记录器。

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)

【讨论】:

  • 但是,我不想更改用于日志记录的 basicConfig。还有其他方法可以获取信息吗?
  • @Steph 我已经更新了答案。编辑部分可能会对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2011-06-09
相关资源
最近更新 更多