• [python]python中,使用traceback处理异常信息


      近来编写一个程序,该程序可以在设定时间内,获取指定文件夹更新的文件夹和文件列表,并根据获取到的更新列表,做一些操作。由于所写程序是放在服务器上运行,为了保证程序在运行的过程中,不时不时跳出些异常信息出来吓其他用户,就在程序中添加了异常处理。将网上的资料整理下,试着将sys.exce_info()和traceback搭配一起使用。效果还算不错,以下信息是我当前处理异常的方式,其中type是异常的类型,value是出现异常的原因,traceback则是通过traceback追中到的异常信息,能够定位到造成异常的代码。

    2016-11-07 22:07:56
    -------------------------------
    type: <type 'exceptions.TypeError'>
    value: string indices must be integers, not str
    traceback: [('文件名', 行号, '函数名', '出现异常的代码行')]

    在try...except中,使用下述两行记录异常情况。针对出现异常之后如何程序如何继续之后的工作,则需要看具体要求。

    tp,val,td = sys.exc_info()
    Log.logerexception(tp,val,td)

    具体代码如下

     1 import os
     2 import time
     3 import traceback
     4 import sys
     5 
     6 def logerexception(tp,val,td):
     7     etype = str(tp)
     8     evalue = str(val)
     9     etb = traceback.extract_tb(td)
    10     errormsg = "type: " + etype + "
    "
    11     errormsg += "value: " + evalue + "
    "
    12     errormsg += "traceback: " + str(etb) + "
    "
    13     writetofile(errormsg)
    14     
    15 def writetofile(errormsg):
    16     logfilepath = os.path.abspath('.') + "/log"
    17     if not os.path.exists(logfilepath):
    18         os.mkdir(logfilepath)
    19 
    20     logfile = time.strftime("%Y%m%d", time.localtime()) + ".txt"
    21     fp = open(logfilepath + "/" + logfile,"a")
    22     ISOTIMEFORMAT= "%Y-%m-%d %X"
    23     happeningtime =  time.strftime(ISOTIMEFORMAT, time.localtime())
    24     usermsg = ""
    25     usermsg += happeningtime + "
    -------------------------------
    "
    26     usermsg += errormsg
    27     fp.write(usermsg + "
    ")
    28     fp.close()
    View Code
  • 相关阅读:
    Springboot中使用Interceptor(拦截器)
    八大排序之冒泡排序
    八大排序之快速排序
    mysql 用户的增删改与授权
    基于Java8开发接口时,处理Java8中的日期
    Springboot中Filter的使用
    正则校验日期,不考虑闰年和闰月
    正则校验时间,24小时制
    记一下mybatis中foreach循环遇到的一个小问题
    sqlserver中一条语句执行查询与更新
  • 原文地址:https://www.cnblogs.com/CaDevil/p/6043135.html
Copyright © 2020-2023  润新知