Search code examples
debuggingloggingpytest

pytest: How to show messages from logging.debug in the function under test


''' func.py '''
import logging

def func():
    ''' func '''
    logging.basicConfig(
        format="\t %(filename)s"
        " %(funcName)s"
        "-ln%(lineno)d"
        " %(levelname)s \n%(message)s",
        level=logging.DEBUG,
        # stream=sys.stdout,
    )
    logger = logging.getLogger()
    logger.info(" >>> logger func info")
    logger.warning(" >>> logger func warning")
    print(" >>> print func info")


def test_func():
    ''' test func '''
    # caplog.set_level(logging.DEBUG)
    func()


if __name__ == "__main__":
    test_func()

Suppose I save the code above as func.py. When I run

pytest -s func.py

I obtain

" >>> print func info".

How can I obtain

" >>> logger func info" 

and

" >>> logger func warning"

when I run

pytest -s func.py

I wish I can do this for the following reason. I normally insert logging.debug/info etc in the my codes. Sometimes, I want to see messages emitted by logging.debug/info when I run pytest. I searched the net for quite a while but cant find a way. Thanks in advance for any help.


Solution

  • To do it by default with every run, add to pytest.ini:

    [pytest]
    log_cli = true
    log_cli_level = DEBUG
    

    Note: if using a very old pytest, pre-3.5, you will need to set log_cli = true in pytest.ini to use the following commands.

    Otherwise, for 3.5 and later, you can use just the command line for a case-by-case basis:

    pytest --log-cli-level=10 func.py
    

    Or more clearly:

    pytest --log-cli-level=DEBUG func.py
    

    The command line will always override pytest.ini settings.