Chinaunix

标题: Python异常信息写日志 [打印本页]

作者: xjtuhit    时间: 2014-09-30 20:30
标题: Python异常信息写日志
原文地址: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
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2