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
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
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