Skip to content

Instantly share code, notes, and snippets.

@twalker
Created November 11, 2010 20:26
Show Gist options
  • Save twalker/673116 to your computer and use it in GitHub Desktop.
Save twalker/673116 to your computer and use it in GitHub Desktop.
A condom for basic console logging.
/**
* @name UTIL.console
* UTIL.console acts as a proxy to native console, using window.status for ie6/7.
* For when you forget some console calls in your source and don't want the output
* shown in staging/production environments. We have enough stuff to remember, eh.
* Logging defaults to only being enabled on localhost (or other logic).
*
* @example
* UTIL.console.log("Hello", "World"); // outputs "Hello World"
* UTIL.console.disable();
* UTIL.console.log("Goodbye"); // no output
*/
var UTIL = (function (global, parent, enable) {
var self = parent.console = parent.console || {},
methodNames = ['log', 'info', 'warn', 'error', 'debug', 'dir'],
fnEmpty = function(){};
/**
* Disallows console logging methods from producing output.
*/
self.disable = function(){
for(var i = 0, len = methodNames.length; i < len; i++){
self[methodNames[i]] = fnEmpty;
}
};
/**
* Allows console logging methods to produce output.
*/
self.enable = function(){
for(var i = 0, len = methodNames.length; i < len; i++){
if('console' in global){
if(methodNames[i] in global.console){
// wrapping function since Chrome didn't like direct method borrowing.
(function(method){
self[method] = function(){
global.console[method].apply(global.console, arguments);
};
})(methodNames[i]);
} else {
// console doesn't support this method
self[methodNames[i]] = fnEmpty;
}
} else if('status' in global){
// Output to the window status for browsers without console.
self[methodNames[i]] = function(){
global.status = Array.prototype.slice.call(arguments).join(' ');
};
} else {
// No console, no status--stub it out.
self[methodNames[i]] = fnEmpty;
}
}
};
enable ? self.enable() : self.disable();
return parent;
}(window.top, UTIL || {}, /localhost/.test(window.location.hostname)));
// Enabled only on localhost by default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment