How do you cause uncaught exceptions to output via the logging
module rather than to stderr
?
I realize the best way to do this would be:
try:
raise Exception, 'Throwing a boring exception'
except Exception, e:
logging.exception(e)
But my situation is such that it would be really nice if logging.exception(...)
were invoked automatically whenever an exception isn't caught.
Why not:
Here is the output with
sys.excepthook
as seen above:Here is the output with the
sys.excepthook
commented out:The only difference is that the former has
ERROR:root:Unhandled exception:
at the beginning of the first line.As Ned pointed out,
sys.excepthook
is invoked every time an exception is raised and uncaught. The practical implication of this is that in your code you can override the default behavior ofsys.excepthook
to do whatever you want (including usinglogging.exception
).As a straw man example:
Override
sys.excepthook
:Commit obvious syntax error (leave out the colon) and get back custom error information:
For more information about
sys.excepthook
: http://docs.python.org/library/sys.html#sys.excepthookTo build on Jacinda's answer, but using a logger object:
The method
sys.excepthook
will be invoked if an exception is uncaught: http://docs.python.org/library/sys.html#sys.excepthookWrap your app entry call in a
try...except
block so you'll be able to catch and log (and perhaps re-raise) all uncaught exceptions. E.g. instead of:Do this:
Although @gnu_lorien's answer gave me good starting point, my program crashes on first exception.
I came with a customised (and/or) improved solution, which silently logs Exceptions of functions that are decorated with
@handle_error
.