Python3 production: logging exceptions without using a trace module
In our production code, we log errors like this:
error = {'tos': str(sys.exc_info()[0:2])}
But this only allows you to see such error information:
"tos": "(<class 'AttributeError'>, AttributeError(\"'NoneType' object has no attribute 'group'\",))"
This is not enough - I want to see the line number and file name with the code. However, I could get this information with this code:
import traceback
meta['error'] = {'tos': str(traceback.format_exc())}
But we are NOT using the module traceback
in production because it is considered too heavy. So how can I get the line number and filename without using it traceback
?
source to share
sys.exc_info
returns a tuple of 3 elements, where the third is a traceback.
The returned tuple is like - (type, value, traceback)
.
You do - str(sys.exc_info()[0:2])
, which only selects the first two items.
Try -
str(sys.exc_info())
If you cannot use the trace module to format the trace. And if you just want the exception line number and file name, you can use the following -
sys.exc_info()[2].tb_frame.f_code.co_filename #<---- filename
sys.exc_info()[2].tb_lineno # <------ line number
Please note that these can be internal names and it is best to use a module traceback
.
source to share