pytest日志记录到文件和stdout

Dan*_*ian 4 python pytest logbook

I'm trying to setup logbook in a PyTest test to output everything to both stderr and a file. The file should get every log level, but stderr should have a higher threshold (which PyTest will manage with it's usual capture settings).

I've got the pytest-logbook plugin. That redirects stderr into PyTest capture, but I'm not sure how to add the file output.

This is (hopefully) obvious to someone that knows logbook, but it's new to me.

One more thing, I want the file logging to be real time. My tests are generally long running and PyTest's normal behavior of only showing output on failure isn't helping when I need to see if things are hung.

Here is code that I think should work, but doesn't. I get the log file, but nothing to stdout/stderr (even on fail):

conftest.py:

import os
import pytest
import logbook
import sys

@pytest.fixture(scope='module')
def modlog(request):
    """Logger that also writes to a file."""
    name = request.module.__name__
    if name.startswith('test_'):
        name = name[5:]
    logname = 'TEST-'+name+'.log'
    if os.path.exists(logname):
        os.rename(logname, logname+"~")
    logger = logbook.Logger(name)
    logger.handlers.append(logbook.FileHandler(logname, level='DEBUG'))
    logger.handlers.append(logbook.StreamHandler(sys.stdout, level='INFO'))
    logger.warn("Start of logging")
    return logger
Run Code Online (Sandbox Code Playgroud)

test_loggy.py:

import pytest

def test_foo(modlog):
    modlog.info('hello')
    modlog.info('world')
    assert 0                       # logs will only print on test fail
Run Code Online (Sandbox Code Playgroud)

Dan*_*ian 6

回答我自己的问题(以防其他人碰到同样的事情)。

日志处理程序形成一个堆栈,您必须允许消息“冒泡”通过。创建处理程序时,这是一个选项。

因此,处理程序的创建应为:

logger.handlers.append(logbook.FileHandler(logname, level='DEBUG', bubble=True))
logger.handlers.append(logbook.StreamHandler(sys.stderr, level='INFO', bubble=True))
Run Code Online (Sandbox Code Playgroud)

如果您运行py.test -s,那么您将实时看到信息级别的消息。如果测试失败,则日志插件将显示失败测试的所有日志消息(包括调试)。您还将在文件中(实时)获得一个副本。