How can i get full traceback in the following case, including the calls of func2 and func functions?
import traceback
def func():
try:
raise Exception('Dummy')
except:
traceback.print_exc()
def func2():
func()
func2()
When i run this, i get:
Traceback (most recent call last):
File "test.py", line 5, in func
raise Exception('Dummy')
Exception: Dummy
traceback.format_stack() is not what i want, as need traceback object to be passed to a third party module.
I am particularly interested in this case:
import logging
def func():
try:
raise Exception('Dummy')
except:
logging.exception("Something awful happened!")
def func2():
func()
func2()
In this case i am getting:
ERROR:root:Something awful happened!
Traceback (most recent call last):
File "test.py", line 9, in func
raise Exception('Dummy')
Exception: Dummy
As mechmind answered, the stack trace consists only of frames between the site where the exception was raised and the site of the
tryblock. If you need the full stack trace, apparently you’re out of luck.Except that it’s obviously possible to extract the stack entries from top-level to the current frame—
traceback.extract_stackmanages it just fine. The problem is that the information obtained bytraceback.extract_stackcomes from direct inspection of stack frames without creating a traceback object at any point, and theloggingAPI requires a traceback object to affect traceback output.Fortunately,
loggingdoesn’t require an actual traceback object, it requires an object that it can pass to the formatting routines of thetracebackmodule.tracebackdoesn’t care either—it only uses two attributes of the traceback, the frame and the line number. So, it should be possible to create a linked list of duck-typed faux-traceback objects and pass it off as the traceback.With these functions in place, your code only requires a trivial modification:
…to give the expected output:
Note that the faux-traceback objects are fully usable for introspection—displaying local variables or as argument to
pdb.post_mortem()—because they contain references to real stack frames.