简体   繁体   中英

Python3 production: logging exceptions without using traceback module

In our production code, we log errors like this:

error = {'tos': str(sys.exc_info()[0:2])}

But it only allows to see this kind of info about the error:

"tos": "(<class 'AttributeError'>, AttributeError(\"'NoneType' object has no attribute 'group'\",))"

Which is not enough - I want to see line number and name of the file with code. However, I could get that info with this code:

import traceback
meta['error'] = {'tos': str(traceback.format_exc())}

But we DO NOT use traceback module in production because it is considered too heavy. So how can I get line number and filename without using traceback ?

sys.exc_info returns the tuple of 3 elements, where the third is the traceback.

The returned tuple is like - (type, value, traceback) .

You are doing - str(sys.exc_info()[0:2]) which only selects first two elements.

Try -

str(sys.exc_info())

If you cannot use the traceback module to format the traceback. And if you just want the exception's line number and filename, 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 these can be internal names, and best is to use traceback module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM