mikey
mikey

Reputation: 2644

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.

Upvotes: 18

Views: 27375

Answers (4)

Matan Dobrushin
Matan Dobrushin

Reputation: 195

As other mentioned, --log-cli-level=DEBUG works, I just add it to the command line parameters in PyCharm:

Pycahrm configuration

Upvotes: 0

mikey
mikey

Reputation: 2644

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.

Upvotes: 43

Anders Åhsman
Anders Åhsman

Reputation: 41

You can also do it using only the command line (without creating a pytest.ini):

pytest -o log_cli=true --log-cli-level=10 func.py

Upvotes: 2

Konstantin Grigorov
Konstantin Grigorov

Reputation: 1602

I found this thread when I wondered how to expand the "warning summary" section on my PyTest run. Playing around with the environment variable PYTHONWARNINGS can help with that https://docs.python.org/3/using/cmdline.html#envvar-PYTHONWARNINGS. If you do export PYTHONWARNINGS=error, you'll see the full stack trace for the warning. However, the run will stop if you are running a test suite.

Upvotes: 2

Related Questions