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

5次阅读

共计 2143 个字符,预计需要花费 6 分钟才能阅读完成。

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

  • sys._getframe,根底办法
  • inspect.currentframe,举荐办法,提供除了 sys._getframe 办法之外更多的 frame 相干的办法

<!–more–>

具体应用如下

应用 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 办法

currentframe = lambda _=None: None 等同于 currentframe = lambda _: None,即 lambda 函数接管一个参数,返回 None


参考:

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

记得帮我点赞哦!

精心整顿了计算机各个方向的从入门、进阶、实战的视频课程和电子书,依照目录正当分类,总能找到你须要的学习材料,还在等什么?快去关注下载吧!!!

朝思暮想,必有回响,小伙伴们帮我点个赞吧,非常感谢。

我是职场亮哥,YY 高级软件工程师、四年工作教训,回绝咸鱼争当龙头的斜杠程序员。

听我说,提高多,程序人生一把梭

如果有幸能帮到你,请帮我点个【赞】,给个关注,如果能顺带评论给个激励,将不胜感激。

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

自己所有文章、答复都与版权保护平台有单干,著作权归职场亮哥所有,未经受权,转载必究!

正文完
 0