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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM