JavaScript Console.lite™
Been thinking that it would be nice to leave console.log() messages in the front end JavaScript code, with a switch to turn them on and off, making for quick on-demand production debug sessions. It also acts as a failsafe for the occasional console message that slips out of the dev environment and into production, which can cause a surprising number of people to email support regarding the loading screen that won’t go away.
So I created a light window.console wrapper that routes console calls to noop functions if debug is not enabled, but back to the original console if you have DEBUG = true (or any non-falsey value) in localStorage.
Side note: Turns out localStorage.DEBUG allows direct access, without using localStorage.getItem(). And it works with any all-caps properties (at least in Chrome and Safari). Neat.
_js_
window.console = (function(w) {
var wC = w.console, rC = {}, lS = w.localStorage || null,
fs = ["log", "debug", "warn", "info"],
isD = function() { return (!!(lS && lS.DEBUG)); };
for (var i in fs) {
rC[fs[i]] = function() {
return (!!wC && isD()) ? wC[fs[i]].apply(wC, arguments) : 'ohkay!';
};
}
return rC;
})(window);
I’m sure a few neck beards will blubber at such disregard for thorough deployment procedures. Yep, not going to argue, there are better ways to configure remote debug/logging, error handling, CI checks for silly mistakes, etc. But this took me 5 minutes to write, and now I can stop thinking about it until I have time for all that other stuff.
Here’ a link to the code in a Gist in case you want to improve on this and show me up.
