code example for capturing detailed exception information in Python

Source: Internet
Author: User
In the process of development, you may often encounter a requirement that requires the output of Python's exception information to a log file.
Online methods are not very practical, the following is a practical, from the Python 2.7 source code to buckle out.
The nonsense does not say directly on the code, the code is not many, the annotation is more than just.

Import sys, tracebacktraceback_template = "Traceback (most recent call last): File"% (filename) S ", Line% (Lineno) s, in% (name) s% (type) s:% (message) s\n ' # skipping the ' actual line ' item# Also note:we don ' t walk all the ' the ' the ' through ' e Stack in this example# see hg.python.org/cpython/file/8dffb76faacc/lib/traceback.py#l280# (Imagine if the 1/0, below, we Re replaced by a call-to-test () which did 1/0.) Try:1/0except: # Http://docs.python.org/2/library/sys.html#sys.exc_info Exc_type, exc_value, exc_traceback = sys.exc_  info () # Most recent (if any) by default "Reason This _can_ is bad:if an (unhandled) exception happens after this,  Or if we do not delete the labels on (not much) older versions of Py, the reference we created can linger.  Traceback.format_exc/print_exc does this very thing, but note this creates a temp scope within the function. "' traceback_details = {' filename ': exc_traceback.tb_frame.f_code.co_filename, ' Lineno ': exc_t RaceBack.tb_lineno, ' name ': Exc_traceback.tb_frame.f_code.co_name, ' type ': exc_type.__name__, ' Message ': Exc_value.message, # or see Traceback._some_str ()} del (Exc_type, Exc_value, Exc_traceback  # so we don't leave our local labels/objects dangling # This still isn ' t "completely safe", though! # "Best (Recommended) Practice:replace all Exc_type, Exc_value, Exc_traceback # with Sys.exc_info () [0], Sys.exc_info () [1 ], Sys.exc_info () [2] # # Modified here can be traceback anywhere, or stored in a file print traceback_template% traceback_details
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.