python-3.x - 在 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 默认将所有日志打印到标准输出,使用上下文管理器重定向标准输出应该可以解决问题。但是,日志仍会打印到控制台,并且不会将任何内容写入文件。任何想法?
解决方案
日志库已经有一个实用程序。
假设您想开始在文件中记录事件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)
推荐阅读
- java - 登录android studio后如何在另一个活动中打开应用程序
- c++ - 为什么我的可变参数模板实例化不起作用?
- python - 'TypeError:访问嵌套列表时只能将 str(不是“int”)连接到 str'
- node.js - 如何防止直接访问 IP Express node.js
- python - 如何使用熊猫一次以特定顺序在多列中提取值
- python-3.x - 如何通过 Heroku 调试 Django 视图?
- node.js - 错误:监听 EACCES:权限被拒绝 8085;
- python - MongoClient 不会在 python 可执行文件上加载
- php - 使用 React 进行条带支付
- python - Python,回归,决策树