Saturday, May 19, 2012

Logger and Log Level in Google Apps Script

If you have become used to some finer control for logging, you may not be very satisfied with the one in Apps Script.

To fix it, you only need a few lines of code:

this.log = function(/*level, args*/) {
    var args = Array.prototype.slice.call(arguments),
    level = args.shift();
    if (this.level >= level) {
      this.logger.log([new Date(), level].concat(args.map(function(o, i, a) {
         return Utilities.jsonStringify(o); })).join(this.delimiter));
    }
    return this;
};

For convenience, we may add some additional functions:

  var levels = ['', 'fatal', 'error', 'warn', 'info', 'debug', 'trace'];
  for (var i = 1; i < levels.length; i++) {
    this[levels[i]] = (function() {
      var args = Array.prototype.slice.call(arguments);
      return function() {
        return this.log.apply(this, args.concat(Array.prototype.slice.call(arguments)));
      };
    }(i));
  }

Here is the complete sample.

No comments: