Log exception in python - part 2

The logExecption

Let’s define the logExecption in log module. For simplicity, we will print the exception to screen – You can change it to your needs.

logException
 import sys
 import traceback

 def logException():
     ( exception_type, exception , tb ) = sys.exc_info()
     ss = '{0} => {1}\n'.format( exception_type , exception )
     ii = 0
     for (fn, linenum , func , line ) in traceback.extract_tb(tb):
         ss += '   {4} | {2:<20} | {0:<20} | {1:>3} | {3:<20}\n'.format(fn,linenum,func,line,ii);
         ii += 1
     print ss

The following demo demonstrates the format of the exception in the log

logException sample
 import log

 def f1():
     try:
         f2()
     except Exception,ee:
         log.logException()
 def f2():
     f3()
 def f3():
     xx = '1' + 5
 f1()
logException sample output
 <type 'exceptions.TypeError'> => cannot concatenate 'str' and 'int' objects
     0 | f1                   | 03.py                |   5 | f2()
     1 | f2                   | 03.py                |  10 | f3()
     2 | f3                   | 03.py                |  13 | xx = '1' + 5

Summery

The logException will allow you to log exception to a log file and continue with execution of the program. Later, With this information at hand, you can easily find the reason why the exception was raised.