|
Kinda off-topic, since the article is about not making errors, instead of logging them, but sometimes you are not in control of input, and you expect some exceptions that you want to log. In Python, instead of the example in the blog: try:
do_something_complex(*args, **kwargs)
except MyException as ex:
logger.log(ex)
Use the almost undocumented `exc_info=True`, like this try:
do_something_complex(*args, **kwargs)
except MyException as ex:
logger.error(ex, exc_info=True)
This will log the entire exception.Even cooler, every un-caught exception calls `sys.excepthook()`. The function is supposed to be monkey patched by anyone who wants to do something with uncaught exceptions, so you can do the following if you want to log all uncaught exceptions: def exception_logger_hook(exc_type, exc_value, exc_traceback):
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
sys.__excepthook__(exc_type, exc_value, exc_traceback)
sys.excephook = exception_logger_hook
This will send all uncaught exceptions to the logger and then continue with raising the exception normally. |
Why not simply use logger.exception()?
Called from within an exception handler, logger.exception() automatically includes exception information.