You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 如何在自定义log函数中获取调用它的上层方法名称

实现方案

直接使用Python标准库的inspect模块读取调用栈信息即可,不需要修改log函数的入参定义,完整实现代码如下:

import inspect

def log(msg):
    # 栈列表索引0对应log函数自身,索引1对应调用log的上层函数
    running_method = inspect.stack()[1].function
    print(f'{running_method}: {msg}')

def testFunc():
    log("Running")

testFunc()

运行后直接输出你要求的结果:

testFunc: Running

补充说明

  • 如果直接在模块全局作用域调用log,获取到的函数名会显示为<module>,符合实际调用上下文
  • 普通日志场景下该方案性能足够,若有高频调用需求,可以改用inspect.currentframe()进一步优化栈读取速度,示例如下:
import inspect

def log(msg):
    current_frame = inspect.currentframe()
    running_method = current_frame.f_back.f_code.co_name
    print(f'{running_method}: {msg}')

内容的提问来源于stack exchange,提问作者esantix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:54:05