Skip to content

Instantly share code, notes, and snippets.

@mw44118
Created June 20, 2012 14:46
Show Gist options
  • Save mw44118/2960239 to your computer and use it in GitHub Desktop.
Save mw44118/2960239 to your computer and use it in GitHub Desktop.
Use sys.excepthook to log uncaught exceptions
# vim: set expandtab ts=4 sw=4 filetype=python:
import logging
import sys
import traceback
def f():
return g()
def g():
return h()
def h():
return i()
def i():
1/0
def log_uncaught_exceptions(ex_cls, ex, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(ex_cls, ex))
if __name__ == '__main__':
sys.excepthook = log_uncaught_exceptions
logging.basicConfig(level=logging.DEBUG)
logging.debug('About to do f().')
f()
# You will never see this logging statement.
logging.debug('All finished!')
@mw44118
Copy link
Author

mw44118 commented Jun 20, 2012

Play around by commenting out line 29 and see what happens.

If you're running this in a bash terminal, do "echo $?" to see the system error code. Notice that when the script crashes, you will always get error code 1 (remember in Unix-land, zero means success) with or without sys.excepthook.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment