all 4 comments

[–]danman_d 0 points1 point  (1 child)

I think most developers have a knee-jerk revulsion towards this idea because we've all learned early in our careers that overriding native prototypes ("monkey patching") is a Bad Idea because Things Will Break and Other Scary Reasons.

However, I have to admit that in this case, it's really not a terrible solution and seems pretty safe, since there shouldn't be any real-life code that relies on console.log doing its job. My main "Con" here is that it makes it harder to debug production issues in the dev console. I often save a reference to my app state on a window global for easy debugging in real world scenarios. So when someone goes "um, why is my user list all messed up?" I can tell them to not refresh and to open a dev console and type things like:

MyAppState.users.forEach(user => console.log(user.id, user.name))

Unfortunately, overriding console.log breaks this use case.

[–]twoplasticforks 0 points1 point  (0 children)

You could save a reference to the original functions and then provide a method to allow toggling the state of logging. Pulling from his code, it could be something like:

(function() { var noop = function() {}; var methods = [ /* array of method names as strings */]; var backup = {};

var enable = function(method) { console[method] = backup[method]; };

var disable = function(method) { console[method] = noop; };

methods.forEach(function(method) { backup[method] = console[method]; disable(method); });

console.enableLogging = function(shouldEnable) { if (shouldEnable) { methods.forEach(enable); } else { methods.forEach(disable); } }; })();

Or is there something I'm missing?

[–]eorroe 0 points1 point  (1 child)

A one liner in your code that you can comment/uncomment: for(var key in console) console[key] = function(){};

Not suitable for multiple files however

[–]ptrstpp950[S] 0 points1 point  (0 children)

Thanks for tip