码迷,mamicode.com
首页 > 编程语言 > 详细

Python异常信息写日志

时间:2014-10-04 18:06:36      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   strong   

大家在开发的过程中可能时常碰到一个需求,需要把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\n‘‘‘ # 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;数百位业内高手和同行在等你交流

Python异常信息写日志

标签:style   blog   http   color   io   os   ar   for   strong   

原文地址:http://www.cnblogs.com/51reboot/p/4006087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!