if you don't have environment variable then you can jsut simply do. console. log = function () {}; I am using this on my live app to hides the console.
Use the short cut Ctrl + L to clear the console. Use the clear log button on the top left corner of the chrome dev tools console to clear the console.
I would probably abuse the short-circuiting nature of JavaScript's logical AND operator and replace instances of:
console.log("Foo.");
With:
DEBUG && console.log("Foo.");
Assuming DEBUG
is a global variable that evaluates to true
if debugging is enabled.
This strategy avoids neutering console.log()
, so you can still call it in release mode if you really have to (e.g. to trace an issue that doesn't occur in debug mode).
Just replace the console.log with an empty function for production.
if (!DEBUG_MODE_ON) {
console = console || {};
console.log = function(){};
}
Clobbering global functions is generally a bad idea.
Instead, you could replace all instances of console.log
in your code with LOG
, and at the beginning of your code:
var LOG = debug ? console.log.bind(console) : function () {};
This will still show correct line numbers and also preserve the expected console.log
function for third party stuff if needed.
Since 2014, I simply use GULP (and recommend everyone to, it's an amazing tool), and I have a package installed which is called stripDebug which does that for you.
(I also use uglify
and closureCompiler
in production)
There's a Babel Macro that automatically removes all console
statements:
https://www.npmjs.com/package/dev-console.macro
One more way to disable console.log in production and keep it in development.
// overriding console.log in production
if(window.location.host.indexOf('localhost:9000') < 0) {
console.log = function(){};
}
You can change your development settings like localhost and port.
This Tiny wrapper override will wrap the original console.log
method with a function that has a check inside it, which you can control from the outside, deepening if you want to see console logs and not.
I chose window.allowConsole
just as an example flag but in real-life use it would probably be something else. depending on your framework.
(function(cl){
console.log = function(){
if( window.allowConsole )
cl(...arguments);
}
})(console.log)
// in development (allow logging)
window.allowConsole = true;
console.log(1,[1,2,3],{a:1});
// in production (disallow logging)
window.allowConsole = false;
console.log(1,[1,2,3],{a:1});
This override should be implement as "high" as possible in the code hierarchy so it would "catch" all logs before then happen. This could be expanded to all the other console
methods such as warn
, time
, dir
and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With