How do I disable console.log when I am not debuggi

2019-01-31 11:21发布

I have many console.log (or any other console calls) in my code and I would like to use them only when my app is in some kind of "debug mode".

I can't seem to use some kind of logger function and internally use console.log because then I wouldn't know what line fired it. Maybe only with a try/catch, but my logs are very general and I don't want try/catch in my code.

What would you recommend?

11条回答
老娘就宠你
2楼-- · 2019-01-31 12:04

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-31 12:06

This code works for me:

if(console=='undefined' || !console || console==null) {
  var console = {
    log : function (string) {
        // nothing to do here!!
    }
  }
}
查看更多
Viruses.
4楼-- · 2019-01-31 12:07

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)

Usage:

// 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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-31 12:08

Just replace the console.log with an empty function for production.

if (!DEBUG_MODE_ON) {
    console = console || {};
    console.log = function(){};
}
查看更多
够拽才男人
6楼-- · 2019-01-31 12:15

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).

查看更多
登录 后发表回答