自定义回溯输出

时间:2014-03-11 22:46:45

标签: python exception logging error-handling traceback

当存在未捕获的异常时,我使用此代码写入.log文件:

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

输出的例子:

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

如何自定义日志记录并改为:

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

(注意:11是发生错误的行号,test是当前文件)

PS:我考虑解析这4行,在第二行搜索“line”,提取附近的int等,但这是一种相当肮脏的方法,我想这会赢了'健壮地工作

1 个答案:

答案 0 :(得分:1)

我相信这可以满足您的需求:

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

这导致文件(mylog.log)包含以下行:

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