Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python catch any exception, and print or log traceback with variable values

Tags:

python

When I catch unexpected error with sys.excepthook

import sys
import traceback

def handleException(excType, excValue, trace):
    print 'error'
    traceback.print_exception(excType, excValue, trace)

sys.excepthook = handleException

h = 1
k = 0

print h/k

This is output I get

error
Traceback (most recent call last):
   File "test.py", line 13, in <module>
      print h/k
ZeroDivisionError: integer division or modulo by zero

How can I include variable values (h, k, ...) in traceback simillar to http://www.doughellmann.com/PyMOTW/cgitb/ ? When I include cgitb result is same.

EDIT:

Great answer I only modified it like this so it logs trace in a file

def handleException(excType, excValue, trace):
    cgitb.Hook(logdir=os.path.dirname(__file__),
      display=False,
      format='text')(excType, excValue, trace)
like image 743
Ib33X Avatar asked Jan 02 '12 14:01

Ib33X


People also ask

How do I log an exception logger in Python?

To log an exception in Python we can use logging module and through that we can log the error. Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger.

How do I print a traceback in Python logger?

import traceback traceback. format_exc() # this will print a complete trace to stout. Save this answer.


1 Answers

By looking at the source of cgitb.py, you should be able to use something like this:

import sys
import traceback
import cgitb

def handleException(excType, excValue, trace):
    print 'error'
    cgitb.Hook(format="text")(excType, excValue, trace)

sys.excepthook = handleException

h = 1
k = 0

print h/k
like image 64
Niklas B. Avatar answered Sep 29 '22 02:09

Niklas B.