0

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!

Escachator
  • 1,742
  • 1
  • 16
  • 32
  • I'm not sure iPython relies on this hook. I think it has an hook on its own. I'll try to write a better answer if none is provided in the next 24 hours. – SylvainD Apr 23 '17 at 20:53
  • See http://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook (probably duplicate question...) – SylvainD Apr 23 '17 at 20:55
  • Josay, thanks for your comments. Although there are a few commonalities with the answer marked as duplicated, the selected answer in that question is not the right answer, which is possibly yours. Will try your method and come back to you. – Escachator Apr 24 '17 at 14:58

1 Answers1

4

Disclaimer: Apparently, a question with a open bounty cannot be closed. Thus, my answer is mostly based on this other similar question/answer.

Changing sys.excepthook does not work on iPython.

A workaround is to update IPython.core.interactiveshell.InteractiveShell.showtraceback.

You'll find additional explanation and a implementation of a fix about it in some projects such as danrobinson/tracestack.

Community
  • 1
  • 1
SylvainD
  • 1,743
  • 1
  • 11
  • 27