code example for capturing detailed exception information in Python _python

Source: Internet
Author: User

You may often encounter a requirement during development that requires the output of Python exception information to the log file.
The online approach is not very practical, the following describes a practical, from the Python 2.7 source button.
Nonsense does not say directly on the code, the code is not much, the annotation is more.

Import sys, traceback traceback_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 way through T He frame stack in this example # hg.python.org/cpython/file/8dffb76faacc/lib/traceback.py#l280 # (Imagine if 1/0,

Below, were replaced by a call to test () which did 1/0.) try:1/0 except: # Http://docs.python.org/2/library/sys.html#sys.exc_info Exc_type, exc_value, exc_traceback = SYS.E Xc_info () # Most recent (if any) by default "Reason this _can_ to be bad:if a (unhandled) exception happens after T

  His, or if we don't delete the labels on (don't much) older versions of Py, the reference we created can linger.
  Traceback.format_exc/print_exc do 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_traceback.tb_lineno, ' name ': Exc_traceback.tb_frame.f_code.co_name, ' Ty PE ': exc_type.__name__, ' message ': Exc_value.message, # or TRACEBACK._SOME_STR ()} del (  Exc_type, Exc_value, Exc_traceback) # so we don ' t leave my 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] # # Modify here to place traceback to anywhere, or save to a file in 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.