Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Forked from jareware/logger.js
Created February 16, 2016 11:50
Show Gist options
  • Save eyecatchup/1e6939b54be80fd3e41a to your computer and use it in GitHub Desktop.
Save eyecatchup/1e6939b54be80fd3e41a to your computer and use it in GitHub Desktop.
Simple utility for unified logging to the console, with optional timestamping.
/**
* Simple utility for unified logging to the console, with optional timestamping.
*
* @example // Create several loggers around the application:
* var log = logger.create('main');
* var logInAnotherModule = logger.create('anotherModule');
*
* // Call the created loggers:
* log('Application started');
* logInAnotherModule('Module started');
*
* // Produces the following in the console:
* // 59.771 [main] Application started logger.js:53
* // 59.775 [anotherModule] Module started
*
* @author Jarno Rantanen <[email protected]>
* @license http://opensource.org/licenses/MIT
*/
define(function() {
"use strict";
var ENABLED = true;
var TIMESTAMP = true;
var topLabelLength = 0; // this is shared across the application so that log lines align
return {
create: function(label, enabled) {
enabled = !!enabled || enabled === undefined; // allow enabling/disabling individual loggers
topLabelLength = window.Math.max(topLabelLength, label.length);
var boxedLabel = '[' + label + ']';
/**
* Main logging method returned by create(). Writes any arguments directly to window.console.
*
* @example log('foobar', { baz: 123 });
* // => "[main] foobar Object {baz: 123}"
*/
var logger = function() {
if (!ENABLED || !enabled || !window.console || !window.console.log) {
return;
}
var now = new Date();
var secPadded = now.getSeconds() > 9 ? now.getSeconds() : '0' + now.getSeconds();
var ms = now.getMilliseconds();
var msPadded = ms > 99 ? ms : (ms > 9 ? '0' + ms : '00' + ms);
var timestamp = TIMESTAMP ? (secPadded + '.' + msPadded + ' ') : '';
var tagPadding = new Array(topLabelLength - label.length + 1).join(' ');
var argsToLog = Array.prototype.slice.call(arguments);
window.console.log.apply(window.console, [ timestamp + tagPadding + boxedLabel ].concat(argsToLog));
};
/**
* Helper for writing out objects.
*
* @example log.hash({ herp: 123, derp: 456 });
* // => "[main] herp: 123 , derp: 456"
*/
logger.hash = function(hash) {
var pieces = [];
Object.keys(hash).forEach(function(key) {
pieces.push(key + ':');
pieces.push(hash[key]);
pieces.push(',');
});
pieces.pop();
logger.apply(logger, pieces);
};
return logger;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment