Skip to content

Instantly share code, notes, and snippets.

@nathanl
Last active December 21, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanl/6368185 to your computer and use it in GitHub Desktop.
Save nathanl/6368185 to your computer and use it in GitHub Desktop.
Safer console.log
// A safer console object (https://gist.github.com/nathanl/6368185)
// - Ensures `console.log` doesn't cause errors in browsers with no console
// - Lets you enable/disable console logging (using console.enable = true/false)
// - Supports all console methods documented here: https://developer.mozilla.org/en-US/docs/Web/API/console
//
// Less fancy but lighter weight than this: http://benalman.com/projects/javascript-debug-console-log/
safe_console = {
enabled: false,
original_console: (function(){
// If the browser has no usable one, define a no-op
return (typeof(window.console === 'object') && typeof(window.console.log) === 'function') ? window.console : {log: function(){}};
})()
};
// Metaprogramming in JS! Wooooooooooooooo
methods = ['debug', 'dir', 'error', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'time', 'timeEnd', 'trace', 'warn'];
for (i = 0; i < methods.length; i++) {
method_name = methods[i];
(function(method_name){
safe_console[method_name] = function() {
if (!this.enabled) { return; }
// TODO: use `(new Error).stack.split("\n")` to output where were called from
this.original_console[method_name].apply(this.original_console, arguments);
};
}
)(method_name);
}
// In case we missed any methods: inherit, regardless of `enabled` switch
safe_console.__proto__ = safe_console.original_console;
window.console = safe_console;
@nathanl
Copy link
Author

nathanl commented Oct 5, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment