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