10

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

gliptak
  • 3,592
  • 2
  • 29
  • 61

1 Answers1

10

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
CasualDemon
  • 5,790
  • 2
  • 21
  • 39
  • 5
    This would require wrapping all assert statements. Also this code doesn't exit when the assert fails, so it isn't exactly equivalent ... – gliptak Feb 17 '16 at 01:40
  • Correct for first part. Second part, you can make it stop by either still raising the error (as edit now shows) or making a call to `sys.exit()`. – CasualDemon Feb 17 '16 at 02:19
  • Agree with @gliptak: this answer isn't really helpful because it requires too much manual labor. There should be a policy to set that will log *all* assertions. – Robert P. Goldman Jun 28 '20 at 15:11
  • @Robert P. Goldman as I see it that's not necessarily true... as long as you want either all of them to be raised or all of them to be ignored you could also wrap everything in a `main()` function and then put the call to the `main()` function in a `try except AssertionError` and log and/or raise all assertions as you wish without having to wrap each one individually... (if you want to give one of them a special treatment you can still catch it individually before it is raised and treated by the general catch) – raphael Oct 15 '20 at 11:07