Question

I use this code to write into a .log file when there is an uncaught exception :

import sys
import traceback

def uncaught_exc_handler(ex_cls, ex, tb):
   with open('mylog.log', 'w') as f: 
      traceback.print_last(file=f)

sys.excepthook = uncaught_exc_handler

1/0

Exemple of output :

Traceback (most recent call last):
  File "C:\Users\Abc\Desktop\test.py", line 11, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

How to customize the logging and have this instead :

ERROR 11 (test): ZeroDivisionError: integer division or modulo by zero

?

(note : 11 is the number of the line where the error occured, test is the current file)

PS : I thought about parsing these 4 lines, search for "line" in the second line, extract the int nearby, etc. but that's a rather dirty method, and I imagine this won't work robustly

Was it helpful?

Solution

I believe this does what you need:

import sys
import traceback

def uncaught_exc_handler(ex_cls, ex, tb):
    last_traceback = (traceback.extract_tb(tb))[-1]
    line_number = last_traceback[1]
    file_name = last_traceback[0].split(".")[0]
    class_name = ex_cls.__name__
    with open('mylog.log', 'w') as f: 
        f.write("ERROR %s (%s) %s: %s\n" % (line_number, file_name, class_name, str(ex)))

sys.excepthook = uncaught_exc_handler


1/0

Which results in a file (mylog.log) that contains the line:

ERROR 15 (test) ZeroDivisionError: integer division or modulo by zero
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top