Search code examples
pythonloggingpytestpython-logging

Disabling specific logger in pytest


In my project I'm parsing some PDF files using pdfplumber. During tests execution (pytest) I sometimes would like to see logs from my code for debugging purposes. This can be done by setting --log-cli-level=DEBUG. However, this turns on messages from all code, also pdfplumber - which is very verbose and makes debugging difficult. Is there a way to selectively enable/disable loggers during test run?

pytest 4.6.3
python 3.7.3

Thanks for help!


Solution

  • Pytest does not support this by default, but you can add a custom option to your conftest.py to turn off specific loggers.

    import pytest
    import logging
    
    def pytest_addoption(parser):
        """Add a command line option to disable logger."""
        parser.addoption(
            "--log-disable", action="append", default=[], help="disable specific loggers"
        )
    
    def pytest_configure(config):
        """Disable the loggers."""
        for name in config.getoption("--log-disable", default=[]):
            logger = logging.getLogger(name)
            logger.propagate = False
    

    For pytest 7.3.0 and later:

    pytest now supports --log-disable without a custom option. https://docs.pytest.org/en/7.4.x/how-to/logging.html