当存在未捕获的异常时,我使用以下代码写入.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:UsersAbcDesktoptest.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行,在第二行搜索"行",提取附近的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: %sn" % (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