Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"canonical" way to use logging for Python asserts

Tags:

python

logging

In this following code, assert is used outside of unit test:

import logging

if __name__ == "__main__":
    logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
    logger = logging.getLogger(__name__)
    logger.info("info level")
    assert 1 == 0

which prints as follows:

2016-02-16 14:56:58,445 - __main__ - INFO - info level
Traceback (most recent call last):
   File "logtest.py", line 7, in <module>
    assert 1 == 0
AssertionError

What is the "canonical" way to use the timestamped logging format for AssertionError raised by the assert (possibly without rewriting each assert in the code)?

There were a number of similar questions asked, mostly dealing with asserts in unit testing context ... Thanks

like image 562
gliptak Avatar asked Feb 16 '16 20:02

gliptak


1 Answers

When you're dealing with logging an exception, you have the code that may error in a try except and then log the exception, for example:

try:
    assert 1 == 0 
except AssertionError as err:
    logger.exception("My assert failed :( ")
    raise err

Then it would log:

2016-02-16 15:29:43,009 - __main__ - INFO - info level
2016-02-16 15:29:43,009 - __main__ - ERROR - My assert failed :( 
Traceback (most recent call last):
  File "/home/james/PycharmProjects/scratchyard/test_time.py", line 8, in <module>
    assert 1 == 0
AssertionError
like image 180
CasualDemon Avatar answered Sep 22 '22 05:09

CasualDemon