我正在尝试通过Stackdriver Logging API v2来获取stackdriver日志。我通过从Google Apps脚本项目发出POST请求来实现此目的,尤其是使用UrlFetchApp。问题是,它运行成功,但是日志中显示的响应为空。但是,当我使用apirequest.io,curl和Google API资源管理器发出相同的请求时,我得到了必要的响应。
我进行了广泛搜索,但无济于事。尝试使用标头,网址,但一无所获。
function exportLogs () {
var options = {
"method" : "post",
"headers": {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
"resourceNames": [
"projects/MyProject"
],
"pageSize": 1,
}
var response = UrlFetchApp.fetch('https://logging.googleapis.com/v2/entries:list?key=MyApiKey', options)
Logger.log(response)
}
我想要获取一些日志,但是我只得到{}
答案 0 :(得分:3)
options
对象中使用了不可接受的密钥。payload
是包括请求正文的唯一可接受的参数。 function exportLogs() {
var options = {
method: "post",
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() }, //Include https://www.googleapis.com/auth/cloud-platform in scopes
payload: JSON.stringify({
resourceNames: ['projects/[PROJECT_ID]'],
pageSize: 1,
}),
};
var response = UrlFetchApp.fetch(
'https://logging.googleapis.com/v2/entries:list?key=MyApiKey',
options
);
Logger.log(response);
}
答案 1 :(得分:0)
出于某些奇怪的原因,在请求正文对象中添加orderBy
排序属性是我获取要检索的结果的唯一方法。
此外,应该添加过滤器以仅获取Apps脚本日志。
load.filter = 'resource.type="app_script_function"';//Only from Apps Script
在GitHub上查看示例代码: Apps Script Download Stackdriver Logs
代码:
function exportStackdriverLogs() {
var id,load,options,param,response;
id = 'Enter your Cloud Project ID here';//See your console at:
//https://console.cloud.google.com/iam-admin/settings
param = "projects/" + id;
load = {};
load.resourceNames = [param];
load.orderBy = "timestamp desc";
load.filter = 'resource.type="app_script_function"';//Only get logs that
//came from Apps Script
load.pageSize = 1;//You will probably want more than 1 but this is for an example
options = {};
options.method = "post";
options.headers = { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() };
options.payload = JSON.stringify(load);
options.muteHttpExceptions = true;
options.contentType = "application/json";
response = UrlFetchApp.fetch('https://logging.googleapis.com/v2/entries:list',options);
//Logger.log('response: ' + response.getResponseCode())
//Logger.log('content: ' + response.getContentText())
}