Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override console.log(); for production [duplicate]

I'm fairly new to Javascript development so this might be a real newbie question.

I've got a sencha-touch application riddled with console.log(); for debugging purposes.

I've got chirpy doing all of my build time combining. It outputs a app.debug.js for debugging as well as a app.min.js for production

Now I could go through all of my code files looking for console.log(); and delete it manually when I'm ready to go to production, but I'm wondering if there's a way to override the method.

Basically, whenever the console.log(); method is called, DO NOTHING.

That way, I can put the override code file in my production config, and NOT in my debug config.

Is this possible?

like image 319
Chase Florell Avatar asked Aug 12 '11 15:08

Chase Florell


People also ask

Can I override console log?

log. To override a console method, we just need to redefine how the method is executed. You'll need to wrap your code to prevent the access of other functions to the private (original) method. Note: The previous code would do the final trick.

Does console log work in production?

Now you are rest assured your console. log(…) will work properly on your local or staging server but will not output anything on your production server. Comments, suggestions or corrections are welcome.


2 Answers

Put this at the top of the file:

var console = {}; console.log = function(){}; 

For some browsers and minifiers, you may need to apply this onto the window object.

window.console = console; 
like image 134
Naftali Avatar answered Sep 19 '22 13:09

Naftali


Or if you just want to redefine the behavior of the console (in order to add logs for example) You can do something like that:

// define a new console var console=(function(oldCons){     return {         log: function(text){             oldCons.log(text);             // Your code         },         info: function (text) {             oldCons.info(text);             // Your code         },         warn: function (text) {             oldCons.warn(text);             // Your code         },         error: function (text) {             oldCons.error(text);             // Your code         }     }; }(window.console));  //Then redefine the old console window.console = console; 
like image 25
Ludovic Feltz Avatar answered Sep 17 '22 13:09

Ludovic Feltz