1. Python中的异常栈跟踪
Python,在2.x中,异常对象可以是任何对象,异常对象和异常栈是分开的。
python中用于处理异常栈的模块是traceback模块,它提供了print_exception、format_exception等输出异常栈等常用的工具函数。
1 deffunc(a, b):2 return a /b3 if __name__ == '__main__':4 importsys5 importtraceback6 try:7 func(1, 0)8 exceptException as e:9 print "print exc"
10 traceback.print_exc(file=sys.stdout)
输出结果:
1 printexc2 Traceback (most recent call last):3 File "./teststacktrace.py", line 7, in
4 func(1, 0)5 File "./teststacktrace.py", line 2, infunc6 return a / b
其实traceback.print_exc()函数只是traceback.print_exception()函数的一个简写形式,而它们获取异常相关的数据都是通过sys.exc_info()函数得到的。
1 deffunc(a, b):2 return a /b3 if __name__ == '__main__':4 importsys5 importtraceback6 try:7 func(1, 0)8 exceptException as e:9 print "print_exception()"
10 exc_type, exc_value, exc_tb =sys.exc_info()11 print 'the exc type is:', exc_type12 print 'the exc value is:', exc_value13 print 'the exc tb is:', exc_tb14 traceback.print_exception(exc_type, exc_value, exc_tb)
输出结果:
1 print_exception()2 the exc type is:
3 the exc value is: integer division ormodulo by zero4 the exc tb is:
5 Traceback (most recent call last):6 File "./teststacktrace.py", line 7, in
7 func(1, 0)8 File "./teststacktrace.py", line 2, infunc9 return a /b10 ZeroDivisionError: integer division or modulo by zero
sys.exc_info()返回的值是一个元组,其中第一个元素,exc_type是异常的对象类型,exc_value是异常的值,exc_tb是一个 traceback对象,对象中包含出错的行数、位置等数据。然后通过print_exception函数对这些异常数据进行整理输出。
traceback模块提供了extract_tb函数来更加详细的解释traceback对象所包含的数据:
1 deffunc(a, b):2 return a /b3 if __name__ == '__main__':4 importsys5 importtraceback6 try:7 func(1, 0)8 except:9 _, _, exc_tb =sys.exc_info()10 for filename, linenum, funcname, source intraceback.extract_tb(exc_tb):11 print "%-23s:%s '%s' in %s()" % (filename, linenum, source, funcname)
输出结果:
1 samchimac:tracebacktest samchi$ python ./teststacktrace.py2 ./teststacktrace.py :7 'func(1, 0)' in ()3 ./teststacktrace.py :2 'return a / b' in func()
2. 使用cgitb来简化异常调试
如果平时开发喜欢基于log的方式来调试,那么可能经常去做这样的事情,在log里面发现异常之后,因为信息不足,那么会再去额外加一些debug log来把相关变量的值输出。调试完毕之后再把这些debug log去掉。其实没必要这么麻烦,Python库中提供了cgitb模块来帮助做这些事情,它能够输出异常上下文所有相关变量的信息,不必每次自己再去手动加debug log。
cgitb的使用简单的不能想象:
1 deffunc(a, b):2 return a /b3 if __name__ == '__main__':4 importcgitb5 cgitb.enable(format='text')6 importsys7 importtraceback8 func(1, 0)
运行之后就会得到详细的数据:
1 A problem occurred in a Python script. Here isthe sequence of2 function calls leading up to the error, inthe order they occurred.3
4 /Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in ()5 4 importcgitb6 5 cgitb.enable(format='text')7 6 importsys8 7 importtraceback9 8 func(1, 0)10 func =
11
12 /Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in func(a=1, b=0)13 2 return a /b14 3 if __name__ == '__main__':15 4 importcgitb16 5 cgitb.enable(format='text')17 6 importsys18 a = 1
19 b = 0
完全不必再去log.debug("a=%d" % a)了,个人感觉cgitb在线上环境不适合使用,适合在开发的过程中进行调试,非常的方便。
也许你会问,cgitb为什么会这么屌?能获取这么详细的出错信息?其实它的工作原理同它的使用方式一样的简单,它只是覆盖了默认的sys.excepthook函数,sys.excepthook是一个默认的全局异常拦截器,可以尝试去自行对它修改:
1 deffunc(a, b):2 return a /b3 defmy_exception_handler(exc_type, exc_value, exc_tb):4 print "i caught the exception:", exc_type5 whileexc_tb:6 print "the line no:", exc_tb.tb_lineno7 print "the frame locals:", exc_tb.tb_frame.f_locals8 exc_tb =exc_tb.tb_next9
10 if __name__ == '__main__':11 importsys12 sys.excepthook =my_exception_handler13 importtraceback14 func(1, 0)
输出结果:
1 i caught the exception:
2 the line no: 14
3 the frame locals: {'my_exception_handler': , '__builtins__': , '__file__': './teststacktrace.py', 'traceback': , '__package__': None, 'sys': , 'func': , '__name__': '__main__', '__doc__': None}4 the line no: 2
5 the frame locals: {'a': 1, 'b': 0}
3. 使用logging模块来记录异常
在使用Java的时候,用log4j记录异常很简单,只要把Exception对象传递给log.error方法就可以了,但是在Python中就不行了,如果直接传递异常对象给log.error,那么只会在log里面出现一行异常对象的值。
在Python中正确的记录Log方式应该是这样的:
1 logging.exception(ex)2 logging.error(ex, exc_info=1) #指名输出栈踪迹, logging.exception的内部也是包了一层此做法
3 logging.critical(ex, exc_info=1) #更加严重的错误级别
转自:http://my.oschina.net/chihz/blog/180573