Skip to content

Instantly share code, notes, and snippets.

@neveldo
Last active November 5, 2020 18:25
Show Gist options
  • Save neveldo/06de4461538326ea701dd4981d19da16 to your computer and use it in GitHub Desktop.
Save neveldo/06de4461538326ea701dd4981d19da16 to your computer and use it in GitHub Desktop.
Google Apps Script : send server logs to the browser console

Google Apps Script : send server logs to the browser console

Here is a workaround to replace the default Google App logger which has some drawbacks from my point of view : First, it's restricted for logging only strings. You can't debug complex objects. Furthermore, it only accepts one argument by call, not very handy ... The Logger.gs file from this gist contains a log() function that stacks the logged objects into the document cache and a popLogs() function to retrieve them. In template.html file, the logs are retrieved from the server then pushed into the Javascript console every 500ms.

Install

  • 1 / Copy the Logger.gs file into your project
  • 2 / Copy the JS from template.html in your main template

Usage

  • Call log() function into your server code
  • Use your browser console to retrieve your logged messages when your Google Add-on is running

Enjoy ! Feel free to comment and improve !

/**
* Set of function that allow log messages to be retrieved from the view in order to be displayed
* into the regular JS console
*/
/**
* Push one or several objects into the log stack
* @param obj1 ... objN A list of JavaScript objects to log.
*/
function log() {
var logs = getLogsFromCache();
for (var i = 0; i < arguments.length; i++) {
logs.push(arguments[i]);
}
saveLogsIntoCache(logs);
}
/**
* Pops and returns the logged objects
* @return {array} logged objects
*/
function popLogs() {
var logs = getLogsFromCache();
saveLogsIntoCache([]);
return logs;
}
/**
* Returns the logged messages
* @return {array} logged messages
*/
function getLogsFromCache() {
var logs = CacheService.getDocumentCache().get('logs');
if (logs) {
return JSON.parse(logs);
;
}
return [];
}
/**
* Save log stack
* @param {array} logs The logs stack
*/
function saveLogsIntoCache(logs) {
CacheService.getDocumentCache().put('logs', JSON.stringify(logs));
}
<!DOCTYPE html>
<html>
<head>
(...)
</head>
<body>
(...)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
// Display logs from server into client console
// To be disabled in production mode ...
setInterval(function () {
google.script.run.withSuccessHandler(function (logs) {
for (var id in logs) {
console.log(logs[id]);
}
}).popLogs();
}, 500);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment