python查看函数调用栈

我在看开源框架代码的时候,有时候好几天都无法找到一个函数被调用的具体位置。。这个时候就需要记录一下函数调用栈。

源码如下

def Caller(func):
    def f(*args,**kwargs):
        import sys
        from oslo_log import log as logging
        LOG = logging.getLogger(__name__)
        f = sys._getframe()
        filename = f.f_back.f_code.co_filename
        lineno = f.f_back.f_lineno
        LOG.info('caller filename is %s'% filename)
        LOG.info('caller lineno is %s' % lineno)
        LOG.info('the passed args is %s %s' % (args,kwargs))
        func(*args,**kwargs)
    return f

使用方法:

@Caller
def start(self):
    self.manager.init_host()
    ........

结果

2019-03-04 18:25:49.537 100053 INFO neutron.service [-] caller filename is /usr/lib/python2.7/dist-packages/oslo_service/service.py
2019-03-04 18:25:49.537 100053 INFO neutron.service [-] caller lineno is 731
2019-03-04 18:25:49.537 100053 INFO neutron.service [-] the passed args is (<neutron.service.Service object at 0x7fa4aed1c990>,) {}
发布了48 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/m0_37313888/article/details/88130705
今日推荐