How to use custom log handler in pytest

Viewed 244

I would like to use rich.logging.RichHandler from the rich library to handle all captured logs in pytest.

Say I have two files,

# library.py
import logging

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())


def func():
    x = {"value": 5}
    logger.info(x)
# test_library.py
from library import func


def test_func():
    func()
    assert False

Running pytest shows the log message as expected, but I want it formatted by rich so I tried to put the following into conftest.py:

import logging
import pytest
from rich.logging import RichHandler


@pytest.hookimpl
def pytest_configure(config: pytest.Config):
    logger = logging.getLogger()
    logger.addHandler(RichHandler())

which results in the following output: enter image description here

Under "captured stdout call" the log message appears as formatted by the RichHandler but below that it appears a second time under "captured log call" which is not what I want. Instead the message below "captured log call" should be formatted by the RichHandler and should not appear twice.

1 Answers

It does not perfectly answer your question however it could help getting a closest result.

  1. Disable live logs: log_cli = 0 in pytest.ini
  2. Disable capture: -s flag equivalent to --capture=no
  3. Disable showing captured logs: --show-capture=no (should be disabled when capture is turned off, but ...)

So by disabling live logs and by running pytest -s --show-capture=no you should get rid of the duplicated logs and get only rich-formatted logs.

Related