I am trying to catch all exceptions and log them into a log file with the following code, but for some reason it does not catch them. The code is:
# Prepares logging
import logging
import time
output_folder='whatever'
# Logging to file:
today=time.strftime("%Y%M%d %H:%M:%S")
logging.basicConfig(filename=output_folder+'/logger '+today+'.log',level=logging.DEBUG,
format='%(asctime)s %(message)s', filemode='w')
logging.info('Program started.')
# Every time there is an error, catch it
import sys
#def error_catching(exctype, value, tb):
def log_uncaught_exceptions(ex_cls, ex, tb):
print "Error found"
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(ex_cls, ex))
sys.excepthook = log_uncaught_exceptions
Then I generate an error, for example by calling a variable that does not exist ('m') and I get the error but nothing is log in the logging file:
m #this should generate a NameError, which is the following
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-69b64623f86d> in <module>()
----> 1 m
NameError: name 'm' is not defined
And, as said, the log file does not catch anything. What did I do wrong?
Thanks!