Python traceback 模块, 打印异常信息

时间:2023-03-09 19:23:17
Python traceback 模块, 打印异常信息

Python感觉是模仿Java, 到处都需要加try..catch...。

这里记录一下用法,方便后续使用。

 # -*- coding:utf-8 -*-

 import os
import logging
import traceback #设置log, 这里使用默认log
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='[%Y-%m_%d %H:%M:%S]',
filename=os.path.dirname(os.path.realpath(__file__)) + "/" + 'test.log',
filemode='a') a=10
b=0 #设置为0, 走异常流程; 否则, 走正常流程 try:
res=a/b
logging.info("exec success, res:" + str(res))
except Exception,e:
#format_exc()返回字符串,print_exc()则直接给打印出来
traceback.print_exc()
logging.warning("exec failed, failed msg:" + traceback.format_exc())

logging默认打印级别是warning.

format_exc()返回字符串,print_exc()则直接给打印出来

日志打印:

[2017-11_17 07:51:02] trace.py[line:24] WARNING exec failed, failed msg:Traceback (most recent call last):
File "trace.py", line 19, in <module>
res=a/b
ZeroDivisionError: integer division or modulo by zero