pytest-logger

1.1.1 · active · verified Thu Apr 16

pytest-logger is a pytest plugin that configures handlers for loggers from Python's standard `logging` module. It allows directing logs to the terminal or files in a configurable manner. The current version is 1.1.1, released on March 10, 2024, indicating active maintenance and an irregular release cadence.

Common errors

Warnings

Install

Imports

Quickstart

To quickly get started, define `pytest_logger_config` and `pytest_logger_logdirlink` hooks in your `conftest.py` to set up loggers and a directory for log files. Then, use standard Python's `logging` module within your test files. Run pytest with `-s` to see real-time console output, and specify which loggers to display with `--loggers` and their console level with `--log-cli-level`.

# content of conftest.py
import os
import logging

def pytest_logger_config(logger_config):
    logger_config.add_loggers(['foo', 'bar'], stdout_level='info', file_level='debug')
    logger_config.set_log_option_default('foo,bar')

def pytest_logger_logdirlink(config):
    return os.path.join(os.path.dirname(__file__), 'logs')

# content of test_example.py
import logging

foo_logger = logging.getLogger('foo')
bar_logger = logging.getLogger('bar')
baz_logger = logging.getLogger('baz')

def test_logging_output():
    foo_logger.info('This is an INFO message from foo')
    bar_logger.debug('This is a DEBUG message from bar, only in file')
    baz_logger.warning('This is a WARNING from baz, not configured by default')
    assert True

# To run: pytest -s -v --log-cli-level=info --loggers=foo,bar test_example.py
# This will output foo INFO messages to console and foo (INFO) and bar (DEBUG) to files in the 'logs' directory.

view raw JSON →