1
votes

I'm trying to fetch stackdriver logs via Stackdriver Logging API v2. I do this by making a POST request from google apps script project, in particular using UrlFetchApp. The thing is, it runs successfully, but the response shown in log is empty. However, when I made the same request using apirequest.io, curl and Google API explorer, I got the necessary response.

I searched extensively, but to no avail. Tried experimenting with header, url, but nothing.

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

What I want to get is some logs, but I'm only getting {}

2

2 Answers

3
votes

Issue:

  • Unacceptable keys are used in options object.

Solution:

  • payload is the only acceptable parameter for including request body.

Code:

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

To Read:

1
votes

For some strange reason, adding an orderBy sort property in the request body object is the only way I could get results to be retrieved.

Also, a filter should be added to get only Apps Script logs.

load.filter = 'resource.type="app_script_function"';//Only from Apps Script 

See example code at GitHub: Apps Script Download Stackdriver Logs

Code:

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