Google Apps Script执行时如何查看console.log输出?
问题与代码
相关代码
function setCredentials(request) { var key = request.key; // Optional // Check if the provided key is valid through a call to your service. // You would have to have a `checkForValidKey` function defined for // this to work. var fetchOptions = { headers: { Accept: 'application/json', Authorization: 'Bearer ' + key }, 'muteHttpExceptions' : true }; var res = UrlFetchApp.fetch('https://example.com/api/check', fetchOptions) console.log("res ", res) if (res.getResponseCode() == 200) { return cc.newSetCredentialsResponse() .setIsValid(true) .build(); }else{ var userProperties = PropertiesService.getUserProperties(); userProperties.setProperty('dscc.key', key); return cc.newSetCredentialsResponse() .setIsValid(false) .build(); } }
问题
上述代码中使用console.log打印了UrlFetch请求的响应,请问在代码执行过程中该如何查看这些日志?我已尝试在脚本的execution log中查找,但未找到。
解决方法
这段代码是Looker Studio(原Data Studio)社区连接器的setCredentials认证函数,它的执行环境是Looker Studio平台而非普通脚本编辑器环境,所以直接在脚本的Execution Log里看不到console.log的输出,你可以通过以下几种方式查看日志:
- 改用Logger.log查看旧日志:把
console.log("res ", res)替换成Logger.log("res " + res.toString()),然后在脚本编辑器顶部菜单栏选择查看 > 日志,就能看到输出内容。 - 将日志存入属性存储:在
console.log之后添加一行代码,把响应内容存入用户属性:
再写一个测试函数读取并打印这个属性:userProperties.setProperty('debug_response', res.toString());
运行这个函数就能在Execution Log里看到日志。function getDebugLog() { var log = PropertiesService.getUserProperties().getProperty('debug_response'); console.log(log); } - 写测试函数模拟调用:新增一个模拟请求的测试函数,直接调用
setCredentials,让代码在普通执行环境下运行:
运行这个测试函数后,就能在脚本的Execution Log里看到function testSetCredentials() { // 替换成你的测试密钥 const mockRequest = { key: 'your_test_api_key' }; setCredentials(mockRequest); }console.log的输出了。
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

