Python traceback 模块, 打印异常信息

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

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

 1 # -*- coding:utf-8 -*-
 2 
 3 import os
 4 import logging
 5 import traceback
 6 
 7 #设置log, 这里使用默认log
 8 logging.basicConfig(
 9         level=logging.INFO,
10         format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
11         datefmt='[%Y-%m_%d %H:%M:%S]',
12         filename=os.path.dirname(os.path.realpath(__file__)) + "/" + 'test.log',
13         filemode='a')
14 
15 a=10
16 b=0 #设置为0, 走异常流程; 否则, 走正常流程
17 
18 try:
19     res=a/b
20     logging.info("exec success, res:" + str(res))
21 except Exception,e:
22     #format_exc()返回字符串,print_exc()则直接给打印出来
23     traceback.print_exc()
24     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
点赞