Last active
December 21, 2015 21:29
-
-
Save nathanl/6368185 to your computer and use it in GitHub Desktop.
Safer console.log
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Superseded by: https://github.com/nathanl/consolation