最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 丰富你的日志信息:从Python调用堆栈获取行号等信息

    正文概述 掘金(职场亮哥)   2020-12-08   332

    程序中的日志打印,或者消息上传,比如kafka消息等等。经常上传的消息中需要上传堆栈信息中的文件名、行号、上层调用者等具体用于定位的消息。Python提供了以下两种方法:

    • sys._getframe, 基础方法
    • inspect.currentframe, 推荐方法,提供除了sys._getframe方法之外更多的frame相关的方法

    具体使用如下

    使用sys._getframe私有方法

    具体使用方法如下:

    import os
    import sys
    
    
    def get_cur_info():
    	"""
            获取调用时的文件名,行号,上层调用者的名称
            :return: 文件名,行号,上层调用者名称
        """
    	try:
    		current_frame = sys._getframe(2)
    		return os.path.basename(current_frame.f_code.co_filename), current_frame.f_lineno, current_frame.f_code.co_name
    	except ValueError:
    		return 'unknown', 0, 'unknown'
    
    

    具体的函数输出结果演示可以参见下面的inspect模块结果

    使用inspect模块(推荐)

    相比于sys的内置私有方法,更推荐inspect模块。inspect模块的具体使用方法如下

    import os
    import inspect
    
    def get_cur_info():
    	try:
    		current_frame = inspect.currentframe(2)
    		return os.path.basename(current_frame.f_code.co_filename), current_frame.f_lineno, current_frame.f_code.co_name
    	except ValueError:
    		return 'unknown', 0, 'unknown'
    
    
    def produce():
    	return get_cur_info()
    
    
    def business():
    	return produce()
    
    
    if __name__ == '__main__':
    	print(get_cur_info())  # 输出 ('unknown', 0, 'unknown')
    
    	print(produce())  # 输出 ('a.py', 22, '<module>')
    
    	print(business())  # 输出 ('a.py', 16, 'business')
    
    

    主要依赖inspect.currentframe方法,关于inspect.currentframe方法的使用见帮助文档

    >>> help(inspect.currentframe)
    Help on built-in function _getframe in module sys:
    
    _getframe(...)
        _getframe([depth]) -> frameobject
        
        Return a frame object from the call stack.  If optional integer depth is
        given, return the frame object that many calls below the top of the stack.
        If that is deeper than the call stack, ValueError is raised.  The default
        for depth is zero, returning the frame at the top of the call stack.
        
        This function should be used for internal and specialized
        purposes only.
    

    从调用堆栈返回一个帧对象。深度为整数,默认为0,返回调用堆栈顶部的帧。如果指定深度比调用堆栈深,会抛出ValueError异常。该功能应该只用于内部和专业目的。

    inspect.currentframe方法的实现见内置库inspect.py

    if hasattr(sys, '_getframe'):
        currentframe = sys._getframe
    else:
        currentframe = lambda _=None: None
    

    所以本质上inspect.currentframe方法等同于sys._getframe方法


    参考:

    1. Python frame hack

    2. StackOverFlow-In Python, how do I obtain the current frame?


    记得帮我点赞哦!

    丰富你的日志信息:从Python调用堆栈获取行号等信息

    念念不忘,必有回响,小伙伴们帮我点个赞吧,非常感谢。

    职场亮哥文章列表:更多文章

    本人所有文章、回答都与版权保护平台有合作,著作权归职场亮哥所有,未经授权,转载必究!


    起源地下载网 » 丰富你的日志信息:从Python调用堆栈获取行号等信息

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元