google-apps-scriptgoogle-apps

Debug a Google Apps Script which is triggered by post request?


I have a simple script in Google Sheets which is trigger by a command in Slack and just adds the Slack message as a new row. It is quite a simple function and is deployed as a web app and does work:

function doPost(req) {
var sheet = SpreadsheetApp.openById('[My Sheet Id]');
var params = req.parameters;

Logger.log(params.text);

sheet.appendRow(params.text);

return ContentService.createTextOutput("Saved your entry:" + params.text);
}

However the Logger.log function never logs anything in the debugging logs. I expect it to be here:

enter image description here

Bizarrely the Executions lists is also empty:

enter image description here

But the script is being triggered and is appending the text message to the Google sheet.

So the question I suppose comes down to how exactly can I log from a script (deployed as a web app) when triggered by a post request and also how can I see its executions? In other words how do you debug such scripts?


Solution

  • When a doPost(e) is invoked remotely, it creates a server-side session whose logs you cannot access via Logger.log().

    However, there is an alternative, ie. StackDriver Logging (accessible from the Apps Script editor menu via View -> StackDriver Logging ).

    Once you have StackDriver Logging enabled, you'll need to replace all your Logger.log() calls with console.log().

    StackDriver Logging is no longer accessible from the Apps Script editor.

    But you're not without options. One alternative is to leverage BetterLog an AppScript library by Peter Herrmann. It's a wrapper for Logger.log() that enables developers to route logs to a Google Sheet.

    There may be another workaround. I'm not sure but I believe Stack Driver has been replaced with (or re-branded as ) Cloud Logging. So it might be possible that logs created using console.log() can be viewed under Cloud Logging for the GCP project linked to an Apps Script project.