如何在运行时查找调用当前指定方法的调用方?
如何在Odoo中追踪方法的调用来源
以下是几种实用的方法,帮你在运行时找到调用account.move.line.create()的方法:
1. 使用Python的inspect模块获取完整调用栈
直接在目标方法中插入代码,打印调用链的详细信息:
import inspect @api.model_create_multi def create(self, vals_list): # 获取调用栈,跳过当前create方法本身 stack_frames = inspect.stack() print("=== 调用链信息 ===") for idx, frame_info in enumerate(stack_frames[1:], 1): print(f"#{idx} 方法名: {frame_info.function}") print(f" 文件路径: {frame_info.filename}") print(f" 行号: {frame_info.lineno}\n") res = super(AccountMoveLine, self.with_context(context)).create(vals_list) return res
运行后会输出从当前方法往上的所有调用层级,你可以根据文件路径区分是业务自定义代码还是Odoo框架内部的调用。
2. 用Odoo日志记录关键调用信息
如果不想打印过多内容,适合生产环境的方式是用日志记录直接调用方:
import logging import inspect _logger = logging.getLogger(__name__) @api.model_create_multi def create(self, vals_list): # 取调用栈的上一层(直接调用方) caller_info = inspect.stack()[1] _logger.info( "account.move.line.create 被调用: 方法=%s, 文件=%s, 行号=%d", caller_info.function, caller_info.filename.split("/")[-1], # 只打印文件名,避免路径过长 caller_info.lineno ) res = super(AccountMoveLine, self.with_context(context)).create(vals_list) return res
日志会输出到Odoo的日志文件中,方便后续排查。
3. 用调试工具交互式查看调用链
在方法中插入调试断点,运行时通过调试器查看调用栈:
import pdb @api.model_create_multi def create(self, vals_list): pdb.set_trace() # 运行到此处会进入调试模式 res = super(AccountMoveLine, self.with_context(context)).create(vals_list) return res
进入调试后输入where命令,就能看到完整的调用栈层级,还可以用up/down命令切换栈帧查看上下文变量。
注意:Odoo的ORM操作可能会触发多层内部调用,比如create可能被create_multi或者其他ORM方法间接调用,需要结合业务场景筛选有效信息。
内容的提问来源于stack exchange,提问作者holydragon
相关产品推荐
相关产品推荐

