Aug 6, 2012

How to log an exception instance

http://blog.tplus1.com/index.php/2012/08/05/python-log-uncaught-exceptions-with-sys-excepthook/

If you do any of these, you probably won’t like what you get:
logging.error(ex)
logging.error(str(ex))
In both cases, you are just turning the exception to a string. You won’t see the traceback and you won’t see the exception type.
Instead of those, make sure you do one of these:
logging.exception(ex) # this is exactly what logging.exception does inside
logging.error(ex, exc_info=1) # sets a higher log level than error 
logging.critical(ex, exc_info=1)
For the last two, without that exc_info=1 parameter, you won’t see the traceback in your logs. You’ll just see the message from the exception.

No comments: