Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 488
mikey Avatar asked Jul 22 '18 15:07

mikey


People also ask

How do I view pytest logs?

Live Logs. By setting the log_cli configuration option to true , pytest will output logging records as they are emitted directly into the console. You can specify the logging level for which log records with equal or higher level are printed to the console by passing --log-cli-level .

How do you show logging information in Python?

Python Logging – INFO Level To log an INFO line using Python Logging, Check if the logger has atleast a logging level of INFO. Use logging.info() method, with the message passed as argument, to print the INFO line to the console or log file.

Does pytest disable logging?

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


2 Answers

The way to do it -- in pytest.ini add:

   [pytest]
   log_cli = true  

Then run pytest with

   pytest --log-cli-level=10 func.py
like image 76
mikey Avatar answered Nov 07 '22 03:11

mikey


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
like image 31
Anders Åhsman Avatar answered Nov 07 '22 03:11

Anders Åhsman