获得完整的追溯

时间:2012-11-03 15:13:28

标签: python traceback

如何在以下情况下获得完整的追溯,包括func2func函数的调用?

import traceback

def func():
    try:
        raise Exception('Dummy')
    except:
        traceback.print_exc()

def func2():
    func()


func2()

当我运行时,我得到:

Traceback (most recent call last):
  File "test.py", line 5, in func
    raise Exception('Dummy')
Exception: Dummy

traceback.format_stack()不是我想要的,因为需要将traceback个对象传递给第三方模块。

我对此案特别感兴趣:

import logging


def func():
    try:
        raise Exception('Dummy')
    except:
        logging.exception("Something awful happened!")


def func2():
    func()


func2()

在这种情况下我得到:

ERROR:root:Something awful happened!
Traceback (most recent call last):
  File "test.py", line 9, in func
    raise Exception('Dummy')
Exception: Dummy

5 个答案:

答案 0 :(得分:33)

正如mechmind所回答的那样,堆栈跟踪仅包含引发异常的站点与try块的站点之间的帧。如果你需要完整的堆栈跟踪,显然你运气不好。

除了显然可以将堆栈条目从顶层提取到当前帧之外 - traceback.extract_stack管理它就好了。问题是traceback.extract_stack获得的信息来自堆栈帧的直接检查,而不会在任何时候创建回溯对象,logging API需要回溯对象来影响回溯输出。

幸运的是,logging并不需要实际的追踪对象,它需要一个可以传递给traceback模块的格式化例程的对象。 traceback并不关心 - 它只使用了追溯的两个属性,即框架和行号。因此,应该可以创建一个鸭型faux-traceback对象的链接列表,并将其作为回溯传递出去。

import sys

class FauxTb(object):
    def __init__(self, tb_frame, tb_lineno, tb_next):
        self.tb_frame = tb_frame
        self.tb_lineno = tb_lineno
        self.tb_next = tb_next

def current_stack(skip=0):
    try: 1/0
    except ZeroDivisionError:
        f = sys.exc_info()[2].tb_frame
    for i in xrange(skip + 2):
        f = f.f_back
    lst = []
    while f is not None:
        lst.append((f, f.f_lineno))
        f = f.f_back
    return lst

def extend_traceback(tb, stack):
    """Extend traceback with stack info."""
    head = tb
    for tb_frame, tb_lineno in stack:
        head = FauxTb(tb_frame, tb_lineno, head)
    return head

def full_exc_info():
    """Like sys.exc_info, but includes the full traceback."""
    t, v, tb = sys.exc_info()
    full_tb = extend_traceback(tb, current_stack(1))
    return t, v, full_tb

有了这些功能,您的代码只需要进行一些简单的修改:

import logging

def func():
    try:
        raise Exception('Dummy')
    except:
        logging.error("Something awful happened!", exc_info=full_exc_info())

def func2():
    func()

func2()

...给出预期的输出:

ERROR:root:Something awful happened!
Traceback (most recent call last):
  File "a.py", line 52, in <module>
    func2()
  File "a.py", line 49, in func2
    func()
  File "a.py", line 43, in func
    raise Exception('Dummy')
Exception: Dummy

请注意,faux-traceback对象完全可用于内省显示局部变量或作为pdb.post_mortem()的参数 - 因为它们包含对实际堆栈帧的引用。

答案 1 :(得分:3)

异常冒泡时收集堆栈跟踪。所以你应该在所需的堆栈上打印回溯:

import traceback

def func():
    raise Exception('Dummy')

def func2():
    func()


try:
    func2()
except:
    traceback.print_exc()

答案 2 :(得分:1)

我写了一个写一个更完整的追溯的模块

该模块是here文档docs

(你也可以从pypi获得模块

sudo pip install pd

要捕获和pring例外,请执行以下操作:

import pd

try:
    <python code>
except BaseException:       
    pd.print_exception_ex( follow_objects = 1 )

堆栈跟踪在这里看起来像这样:

Exception: got it

#1  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 1) at      t  test_pd.py:29
Calls next frame at:
    raise Exception('got it') at: test_pd.py:29

#2  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 2) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#3  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 3) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#4  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 4) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#5  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 5) at     test_pd.py:28
 Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#6  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 6) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#7  def main() at test_pd.py:44
Local variables:
n = {'a': 42, 'b': [1, 2, 3, 4]}
Calls next frame at:
    pd.print_exception_ex( follow_objects = 1 ) at: test_pd.py:44

follow_objects = 0不会打印出对象内容(使用复杂的数据结构follow_objects可能需要很长时间)。

答案 3 :(得分:0)

这是基于@ user4815162342的答案,但更为简单:

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

它避免引发伪异常,但以要求使用sys._getframe()为代价。假定正在使用捕获了异常的except子句,因为它上升到堆栈帧(full_exc_info和调用full_exc_info的函数-那将是调用该函数提升代码,因此已包含在原始回溯中。

这将提供与user4815162342的答案中的代码相同的输出。

如果您不介意格式上的细微差别,也可以使用

import logging

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

def func2():
    func()

func2()

这将导致

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 <module>
    func2()
  File "test.py", line 10, in func2
    func()
  File "test.py", line 7, in func
    logging.exception("Something awful happened!", stack_info=True)

在这种情况下,您将获得从try到异常的跟踪,从根调用到日志记录调用的位置的跟踪。

答案 4 :(得分:-1)

可以从回溯中提取更多信息,我有时更喜欢更整洁,更“逻辑”的信息,而不是带有文件,行号和跟踪返回的代码片段的多行blob。最好一行说出所有必需品。

为实现这一点,我使用以下功能:

def raising_code_info():
    code_info = ''
    try:    
        frames = inspect.trace()
        if(len(frames)):
            full_method_name = frames[0][4][0].rstrip('\n\r').strip()
            line_number      = frames[1][2]
            module_name      = frames[0][0].f_globals['__name__']
            if(module_name == '__main__'):
                module_name = os.path.basename(sys.argv[0]).replace('.py','')
            class_name = ''
            obj_name_dot_method = full_method_name.split('.', 1)
            if len(obj_name_dot_method) > 1:
                obj_name, full_method_name = obj_name_dot_method
                try:
                    class_name = frames[0][0].f_locals[obj_name].__class__.__name__
                except:
                    pass
            method_name = module_name + '.'
            if len(class_name) > 0:
                method_name += class_name + '.'
            method_name += full_method_name
            code_info = '%s, line %d' % (method_name, line_number)
    finally:
        del frames
        sys.exc_clear()
    return code_info

它给出了。和行号,例如:

(示例模块名称:test.py):

(line 73:)
def function1():
    print 1/0

class AClass(object):    
    def method2(self):
        a = []
        a[3] = 1

def try_it_out():
    # try it with a function
    try:
        function1()
    except Exception, what:
        print '%s: \"%s\"' % (raising_code_info(), what)

    # try it with a method
    try:
        my_obj_name = AClass()
        my_obj_name.method2()       
    except Exception, what:
        print '%s: \"%s\"' % (raising_code_info(), what)

if __name__ == '__main__':
     try_it_out()


test.function1(), line 75: "integer division or modulo by zero"
test.AClass.method2(), line 80: "list assignment index out of range"

在某些用例中可能会稍微整洁一些。