Skip to content

Instantly share code, notes, and snippets.

@impressiver
Last active December 9, 2015 23:28
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 impressiver/4343889 to your computer and use it in GitHub Desktop.
Save impressiver/4343889 to your computer and use it in GitHub Desktop.
Was thinking that it would be nice to leave console messages in the front end code, with a switch to turn them on and off, making quick production debug sessions hassle-free. So I made 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…
/*!
* Console Lite
* https://gist.github.com/impressiver/4343889
*
* Stop wayward debug messages from inadvertently jamming up browsers.
* Setting `localStorage.DEBUG = true` will turn console messages on
* again, though you still only get partial console functionality
* (which is intentional).
*
* Copyright 2013 Impressiver LLC
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
window.console = (function(w) {
"use strict";
var wC = w.console, rC = {}, lS = w.localStorage,
fs = ["log", "error", "warn", "info", "debug", "dir", "trace", "time", "timeEnd"],
isD = function() { return (!!(lS && lS.DEBUG)); }, noop = function(){}, i;
for (i in fs) {
rC[fs[i]] = (!!wC && isD()) ? wC[fs[i]].bind(wC) : noop;
}
return rC;
})(window);
@toekneestuck
Copy link

I modified the rC[fs[i]] assignment a bit to the following:

rC[fs[i]] = (!!wC && isD()) ? wC[fs[i]].bind(wC) : function(){};

I did this because the i context is lost when console functions are executed. Every console function will actually be executed as console.info (because the value of i is at the last index in the closure). You can test this out by putting 'warn' at the end of the fs array and executing any console.log/debug function.

Other than that though, this is great! I added a few other functions to the array, such as error, dir, trace, time, timeEnd, warn.

Thanks!

@impressiver
Copy link
Author

@toekneestuck: Good call - rookie mistake :) I'll update the gist to reflect your changes.

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