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
相关产品推荐
相关产品推荐

