[Python] How to use custom log handler in pytest

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    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: [​IMG]

    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.

    Continue reading...

Compartilhe esta Página