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

如何在Google Apps Script中获取当前正在运行的函数名称

Google Apps Script 获取当前运行函数名及日志实现

Google Apps Script 没有内置直接获取当前运行函数名的原生API,可通过解析Error对象的堆栈信息实现,效果和你提供的Python版日志逻辑完全等价,可直接使用的实现代码如下:

function getCurrentRunInfo() {
  // 生成Error对象获取调用堆栈
  const stack = new Error().stack.split('\n');
  // 取堆栈第2行,跳过当前函数自身的调用帧,得到上层调用方的堆栈信息
  const callerLine = stack[2];
  
  // 正则适配GAS默认堆栈格式:" at 函数名 (文件名:行号:列号)"
  const stackReg = /at\s+(.*)\s+\((.*):(\d+):\d+\)/;
  const matchResult = callerLine.match(stackReg);
  
  let fullFuncName = matchResult ? matchResult[1] : 'unknown';
  const fileName = matchResult ? matchResult[2].split('.')[0] : 'unknown';
  const lineNo = matchResult ? matchResult[3] : 'unknown';

  let className = '';
  let funcName = fullFuncName;
  // 识别类方法调用,提取类名
  if (fullFuncName.includes('.')) {
    const nameSplit = fullFuncName.split('.');
    className = nameSplit[0];
    funcName = nameSplit[1];
  }

  // 按你提供的Python代码格式输出日志
  const now = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss');
  return `--> ${fileName}.${className}().${funcName}().${lineNo} --> ${now}\n`;
}

使用示例

  • 普通函数调用:
function testNormalFunc() {
  console.log(getCurrentRunInfo());
  // 输出示例:--> 代码.gs..testNormalFunc().3 --> 2024-05-20 15:22:10
}
  • 类方法调用(自动识别类名):
class TestBizClass {
  testMethod() {
    console.log(getCurrentRunInfo());
    // 输出示例:--> 代码.gs.TestBizClass().testMethod().9 --> 2024-05-20 15:23:05
  }
}

function testClassCall() {
  const ins = new TestBizClass();
  ins.testMethod();
}

注意事项

  • 匿名函数会被识别为anonymous,建议需要日志采集的函数都声明明确的命名
  • 可自行修改Utilities.formatDate的第二个参数调整时间输出的时区

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:24:03