Skip to content Skip to sidebar Skip to footer

Py.test Logging Control

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

Solution 1:

Installing and using the pytest-capturelog plugin could satisfy most of your pytest/logging needs. If something is missing you should be able to implement it relatively easily.


Solution 2:

As Holger said you can use pytest-capturelog:

def test_foo(caplog):
    caplog.setLevel(logging.INFO)
    pass

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)

Solution 3:

A bit of a late contribution, but I can recommend pytest-logging for a simple drop-in logging capture solution. After pip install pytest-logging you can control the verbosity of the your logs (displayed on screen) with

$ py.test -s -v tests/your_test.py
$ py.test -s -vv tests/your_test.py
$ py.test -s -vvvv tests/your_test.py

etc... NB - the -s flag is important, without it py.test will filter out all the sys.stderr information.


Solution 4:

Pytest now has native support for logging control via the caplog fixture; no need for plugins.

You can specify the logging level for a particular logger or by default for the root logger:

import pytest

def test_bar(caplog):
    caplog.set_level(logging.CRITICAL, logger='root.baz')

Pytest also captures log output in caplog.records so you can assert logged levels and messages. For further information see the official documentation here and here.


Solution 5:

A bit of an even later contribution: you can try pytest-logger. Novelty of this plugin is logging to filesystem: pytest provides nodeid for each test item, which can be used to organize test session logs directory (with help of pytest tmpdir facility and it's testcase begin/end hooks).

You can configure multiple handlers (with levels) for terminal and filesystem separately and provide own cmdline options for filtering loggers/levels to make it work for your specific test environment - e.g. by default you can log all to filesystem and small fraction to terminal, which can be changed on per-session basis with --log option if needed. Plugin does nothing by default, if user defines no hooks.


Post a Comment for "Py.test Logging Control"