Python 自定义回溯输出

Python 自定义回溯输出,python,exception,logging,error-handling,traceback,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

当出现未捕获的异常时,我使用此代码写入
.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
?

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


PS:我考虑过解析这4行,搜索第二行中的“行”,提取附近的
int
,等等。但这是一个相当肮脏的方法,我想这不会很好地工作我相信这可以满足您的需要:

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
ERROR 15 (test) ZeroDivisionError: integer division or modulo by zero