Skip to content
Advertisement

Logging uncaught exceptions in Python

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:

JavaScript

But my situation is such that it would be really nice if logging.exception(...) were invoked automatically whenever an exception isn’t caught.

Advertisement

Answer

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 of sys.excepthook to do whatever you want (including using logging.exception).

As a straw man example:

JavaScript

Override sys.excepthook:

JavaScript

Commit obvious syntax error (leave out the colon) and get back custom error information:

JavaScript

For more information about sys.excepthook, read the docs.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement