Reputation: 7563
I use console.log
in my JS files to trace the application.
The problem: logs are in production environment.
How can I remove lines like console.log
from code?
P.S. Please do not advice text solutions like find + xargs + grep -v
.
Upvotes: 2
Views: 1429
Reputation: 427
Yeah, I had a similar situation, I posted about it here. http://bhavinsurela.com/naive-way-of-overriding-console-log/ This is the gist of the code.
var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.
var logger = {
force:false,
original:null,
log:function(obj)
{
var hostName = window.location.hostname;
if(domainNames.indexOf(hostName) > -1)
{
if(window.myLogger.force === true)
{
window.myLogger.original.apply(this,arguments);
}
}else {
window.myLogger.original.apply(this,arguments);
}
},
forceLogging:function(force){
window.myLogger.force = force;
},
original:function(){
return window.myLogger.original;
},
init:function(){
window.myLogger.original = console.log;
console.log = window.myLogger.log;
}
}
window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");
Upvotes: 0
Reputation: 51
If you use Grunt you can add a task so as to remove/comment the console.log statements. Therefore the console.log are no longer called.
https://www.npmjs.org/package/grunt-remove-logging-calls
Upvotes: 2
Reputation: 707148
For my significant projects, I have my own logging function that internally uses console.log()
, but there are no console.log()
calls in my code except for the one place in this function. I can then enable or disable logging by changing one variable.
My function is actually a little more involved than this with options to put the output into places other than just the console, but conceptually, it looks like this:
// change this variable to false to globally turn off all logging
var myLoggingEnabled = true;
function myLog() {
if (myLoggingEnabled) {
if (window.console && console.log) {
console.log.apply(this, arguments);
}
}
}
You can then use code like this to log:
myLog(foo);
FYI, for deployed code compactness and performance optimization, I also have a minimization step that removes all calls to myLog()
from my code. This is an optimization that I've chosen to take advantage of. Perhaps you could share why you wouldn't also consider this type of optimization.
Upvotes: 4
Reputation: 287940
Well, you can disable them with
console.log=function(){}
But the lines will be there unsless you delete them manually.
Upvotes: 3