Skip to content

Instantly share code, notes, and snippets.

@GirlBossRush
Last active August 29, 2015 13:55
Show Gist options
  • Save GirlBossRush/8727565 to your computer and use it in GitHub Desktop.
Save GirlBossRush/8727565 to your computer and use it in GitHub Desktop.
// General purpose logger.
// * Adds timestamps.
// * Retains line numbers.
(function loggerInitializer() {
"use strict";
// Stub common console methods when they are missing.
var method,
noop = function noop() {},
methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
],
length = methods.length,
console = (global.console = global.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
function basic() {
return {
debug: function () { console.log(arguments[1])},
error: function () { console.error(arguments[1])},
info: function () { console.log(arguments[1])},
log: function () { console.log(arguments[1])},
warn: function () { console.log(arguments[1])}
}
}
function advanced(options) {
options = typeof options !== 'undefined' ? options : {};
var methods = {},
dateString = noop,
levelOptions = {
debug: 'DeepPink',
error: 'Red',
info: 'DarkBlue',
log: 'DarkGreen',
warn: 'DarkOrange'
};
dateString.toString = function toString() {
var datetime = new Date();
return datetime.getHours() + ':' + datetime.getMinutes() + ':' + datetime.getMilliseconds();
};
Object.keys(levelOptions).forEach(function (level) {
// Stub our debug statements in production.
if (level === 'debug' && options.debug) {
return methods[level] = function () {};
}
methods[level] = console[level].bind(
console,
"%c[%s] %c[%s] %c[%s]",
("color: " + levelOptions[level]),
level,
"color: black",
dateString,
"color: blue")
});
return methods;
}
// IE8 is pain.
if (navigator.userAgent.match(/msie/i)) {
global.Logger = new basic();
} else {
global.Logger = new advanced({ debug: !global.logDebugStatements });
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment