Stackdriver Logging API returns 响应代码 200,但响应为空

Stackdriver Logging API returns response code 200, but response is empty

我正在尝试通过 Stackdriver Logging API v2 获取 stackdriver 日志。我通过从 google 应用程序脚本项目发出 POST 请求来执行此操作,特别是使用 UrlFetchApp。问题是,它运行成功,但日志中显示的响应是空的。但是,当我使用 apirequest.io、curl 和 Google API 资源管理器发出相同的请求时,我得到了必要的响应。

我进行了广泛的搜索,但无济于事。已尝试使用 header、url,但一无所获。

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)
}

我想获取的是一些日志,但是我只获取了{}

问题:

  • 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);
}

阅读:

出于某些奇怪的原因,在请求正文对象中添加 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())
}