在通过try…except捕获到异常后,用traceback模块记录异常到日志里。
import traceback
import logging
logging.basicConfig(filename='d.txt',
format='%(asctime)s - %(filename)s - %(levelname)s - %(module)s : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=0)
try:
print(1/0)
except:
print('系统故障,联系工作人员')
logging.error(traceback.format_exc())
finally:
print('程序执行结束')
此时日志里显示:
2021-10-18 20:44:17 - test1.py - ERROR - test1 : Traceback (most recent call last):
File "C:/Users/DELL/PycharmProjects/pythonProject1/c/test1.py", line 394, in <module>
print(1/0)
ZeroDivisionError: division by zero
可以看到出错的具体时间,错误所在的文件行数和错误类型。
|