Get full traceback

前端 未结 5 1085
陌清茗
陌清茗 2020-12-12 22:55

How can i get full traceback in the following case, including the calls of func2 and func functions?

import traceback

def func():
         


        
5条回答
  •  -上瘾入骨i
    2020-12-12 23:21

    This is based on @user4815162342 s answer, but a bit more minimalistic:

    import sys
    import collections
    
    FauxTb = collections.namedtuple("FauxTb", ["tb_frame", "tb_lineno", "tb_next"])
    
    def full_exc_info():
        """Like sys.exc_info, but includes the full traceback."""
        t, v, tb = sys.exc_info()
        f = sys._getframe(2)
        while f is not None:
            tb = FauxTb(f, f.f_lineno, tb)
            f = f.f_back
        return t, v, tb
    

    It avoids throwing the dummy exception, at the cost of requiring the usage of sys._getframe(). It assumes being using the the except clause where the exception was caught, as it goes up to stack frames (full_exc_info and the function that calls full_exc_info -- that would be the function that calls the raising code, and as such is already included in the original traceback).

    This gives the same output as the code in user4815162342 s answer.

    If you don't mind the slight differences in formatting, you can also use

    import logging
    
    def func():
        try:
            raise Exception('Dummy')
        except:
            logging.exception("Something awful happened!", stack_info=True)
    
    def func2():
        func()
    
    func2()
    

    which results in

    ERROR:root:Something awful happened!
    Traceback (most recent call last):
      File "test.py", line 5, in func
        raise Exception('Dummy')
    Exception: Dummy
    Stack (most recent call last):
      File "test.py", line 12, in 
        func2()
      File "test.py", line 10, in func2
        func()
      File "test.py", line 7, in func
        logging.exception("Something awful happened!", stack_info=True)
    

    In this case, you'll get on trace from the try to the exception, and a second from the root call to the location of the logging call.

提交回复
热议问题