This article mainly introduces the code example for capturing detailed exception information in Python. The code in this article is obtained from the source code of Python2.7, which can obtain the file location, row number, function, exception information, and so on, if you need Python, you may need to output the exception information of Python to the log file.
The methods on the Internet are not practical. The following describes a practical method, which is deducted from the Python 2.7 source code.
If you don't need to talk about Code directly, there are not many codes and there are more comments.
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 way through the frame stack in this example # see References (Imagine if the 1/0, below, were replaced by a call to test () which did 1/0 .) try: 1/0 running T :# 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 _ be 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 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, '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] # modify the traceback to any location or store it in the file with print traceback_template % traceback_details.