Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Created November 17, 2013 03:42
Show Gist options
  • Save nijikokun/7508798 to your computer and use it in GitHub Desktop.
Save nijikokun/7508798 to your computer and use it in GitHub Desktop.
Custom console logging system
/**
* Custom Logging Module to support older browsers & timestamp in console log.
*
* Caveats:
*
* - Errors are not logged on the correct line.
*
* @param {String} environment
* @return {Object}
*/
var log = function (environment) {
var environments = {
TESTING: 'TESTING',
PRODUCTION: 'PRODUCTION'
};
/*!
* Delegate
*
* @private
*/
var prepare = function (args, timestamp) {
var a = Array.prototype.slice.call(args, 0);
if (timestamp) a.unshift(self.timestamp());
return a;
};
/**
* Sugar to alias console methods to our log module.
*
* @param {String} method
* @return {Function}
* @private
*/
var type = function (method, timestamp) {
var terminal = window.console;
return function () {
if (terminal && terminal[method]) terminal[method].apply(terminal, prepare(arguments, timestamp));
}
};
/**
* Module
*
* @type {Function}
*/
var self = function () {
var alias = type('log', true);
return (environment == environments.TESTING) ? alias.apply(this, Array.prototype.slice.call(arguments)) : undefined;
};
/**
* Environment
*
* @type {String}
*/
self.environment = environment || environments.TESTING;
/*!
* Generate timestamp portion of the console log.
*/
self.timestamp = function () {
return "[" + Date() + "]";
};
/**
* Logger methods
*
* @type {Array}
*/
var methods = [
'debug', 'info', 'error', 'warn', 'assert', 'table', 'count', 'trace', 'dir', 'clear',
'group', 'groupEnd', 'time', 'timeEnd'
];
/**
* Generation
*/
(function next (index) {
if (index < methods.length) {
var method = methods[index];
self[method] = function () {
var alias = type(method, (method == 'debug' || method == 'info' || method == 'error' || method == 'warn'));
if (environment == environments.TESTING) {
return alias.apply(this, Array.prototype.slice.call(arguments));
} else if (method == 'error' || method == 'warn') {
return alias.apply(this, Array.prototype.slice.call(arguments));
}
return;
};
next(index + 1);
}
})(0);
/**
* Exposing the public interface to the log module
*
* @private
*/
return self;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment