免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2182 | 回复: 0
打印 上一主题 下一主题

Python异常信息写日志 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-09-30 20:30 |只看该作者 |倒序浏览
原文地址:http://51reboot.com/python-except-log/  
蛮有用的

大家在开发的过程中可能时常碰到一个需求,需要把Python的异常信息输出到日志文件中
网上的办法都不太实用,下面介绍一种实用的,从Python 2.7源码中扣出来的
废话不说 直接上代码,代码不多,注释比较多而已
  1. import sys, traceback

  2. traceback_template = '''Traceback (most recent call last):
  3.   File "%(filename)s", line %(lineno)s, in %(name)s
  4. %(type)s: %(message)s\n''' # Skipping the "actual line" item

  5. # Also note: we don't walk all the way through the frame stack in this example
  6. # see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
  7. # (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)

  8. try:
  9.     1/0
  10. except:
  11.     # http://docs.python.org/2/library/sys.html#sys.exc_info
  12.     exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default

  13.     '''
  14.     Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
  15.     or if we do not delete the labels on (not much) older versions of Py, the
  16.     reference we created can linger.

  17.     traceback.format_exc/print_exc do this very thing, BUT note this creates a
  18.     temp scope within the function.
  19.     '''

  20.     traceback_details = {
  21.                          'filename': exc_traceback.tb_frame.f_code.co_filename,
  22.                          'lineno'  : exc_traceback.tb_lineno,
  23.                          'name'    : exc_traceback.tb_frame.f_code.co_name,
  24.                          'type'    : exc_type.__name__,
  25.                          'message' : exc_value.message, # or see traceback._some_str()
  26.                         }

  27.     del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
  28.     # This still isn't "completely safe", though!
  29.     # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
  30.     # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]


  31.     ## 修改这里就可以把traceback打到任意地方,或者存储到文件中了
  32.     print traceback_template % traceback_details
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP