大家在开发的过程中可能时常碰到一个需求,需要把Python的异常信息输出到日志文件中
网上的办法都不太实用,下面介绍一种实用的,从Python 2.7源码中扣出来的
废话不说 直接上代码,代码不多,注释比较多而已
1 import sys, traceback 2 3 traceback_template = '''Traceback (most recent call last): 4 File "%(filename)s", line %(lineno)s, in %(name)s 5 %(type)s: %(message)s ''' # Skipping the "actual line" item 6 7 # Also note: we don't walk all the way through the frame stack in this example 8 # see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280 9 # (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.) 10 11 try: 12 1/0 13 except: 14 # http://docs.python.org/2/library/sys.html#sys.exc_info 15 exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default 16 17 ''' 18 Reason this _can_ be bad: If an (unhandled) exception happens AFTER this, 19 or if we do not delete the labels on (not much) older versions of Py, the 20 reference we created can linger. 21 22 traceback.format_exc/print_exc do this very thing, BUT note this creates a 23 temp scope within the function. 24 ''' 25 26 traceback_details = { 27 'filename': exc_traceback.tb_frame.f_code.co_filename, 28 'lineno' : exc_traceback.tb_lineno, 29 'name' : exc_traceback.tb_frame.f_code.co_name, 30 'type' : exc_type.__name__, 31 'message' : exc_value.message, # or see traceback._some_str() 32 } 33 34 del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling 35 # This still isn't "completely safe", though! 36 # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback 37 # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2] 38 39 40 ## 修改这里就可以把traceback打到任意地方,或者存储到文件中了 41 print traceback_template % traceback_details
欢迎加入运维开发技术分享QQ群:365534424;数百位业内高手和同行在等你交流