''' 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.
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 .
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.
Pytest does not support this by default, but you can add a custom option to your conftest.py to turn off specific loggers.
The way to do it -- in pytest.ini add:
[pytest]
log_cli = true
Then run pytest with
pytest --log-cli-level=10 func.py
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With