问题描述
我们最近切换到 py.test 进行 python 测试(顺便说一句,这太棒了).但是,我试图弄清楚如何控制日志输出(即内置的 python 日志记录模块).我们已经安装了 pytest-capturelog,它按预期工作,当我们想查看日志时,我们可以传递 --nologcapture 选项.
We have recently switched to py.test for python testing (which is fantastic btw). However, I'm trying to figure out how to control the log output (i.e. the built-in python logging module). We have pytest-capturelog installed and this works as expected and when we want to see logs we can pass --nologcapture option.
但是,您如何控制日志记录级别(例如信息、调试等)并过滤日志记录(如果您只对特定模块感兴趣).是否有现有的 py.test 插件来实现这一点,还是我们需要自己推出?
However, how do you control the logging level (e.g. info, debug etc.) and also filter the logging (if you're only interested in a specific module). Is there existing plugins for py.test to achieve this or do we need to roll our own?
谢谢,乔尼
推荐答案
正如 Holger 所说,你可以使用 pytest-capturelog:
As Holger said you can use pytest-capturelog:
def test_foo(caplog):
caplog.setLevel(logging.INFO)
pass
如果您不想使用 pytest-capturelog,您可以使用标准输出 StreamHandler 在您的日志配置中,这样 pytest 将捕获日志输出.这是一个示例 basicConfig
If you don't want to use pytest-capturelog you can use a stdout StreamHandler in your logging config so pytest will capture the log output. Here is an example basicConfig
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
这篇关于py.test 日志控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!