Created
June 20, 2012 14:46
-
-
Save mw44118/2960239 to your computer and use it in GitHub Desktop.
Use sys.excepthook to log uncaught exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.