Javascript 不调试时如何禁用 console.log?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7500811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:31:36  来源:igfitidea点击:

How do I disable console.log when I am not debugging?

javascriptdebugginglogging

提问by vsync

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

我的代码中有很多console.log或任何其他控制台调用),我只想在我的应用程序处于某种“调试模式”时使用它们。

I can't seem to use some kind of logger function and internally use console.logbecause 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.

我似乎无法使用某种记录器功能并在内部使用,console.log因为那样我就不知道是哪条线触发了它。也许只有 try/catch,但我的日志非常一般,我不想在我的代码中使用 try/catch。

What would you recommend?

你会推荐什么?

采纳答案by vsync

Since 2014, I simply use GULP(and recommend everyone to, it's an amazing tool), and I have a package installed which is called stripDebugwhich does that for you.

自 2014 年以来,我只使用GULP(并推荐大家使用,这是一个了不起的工具),并且我安装了一个名为stripDebug的包,它可以为您执行此操作。

(I also use uglifyand closureCompilerin production)

(我也在生产中使用uglifyclosureCompiler



Update (June 20, 2019)

更新(2019 年 6 月 20 日)

There's a Babel Macrothat automatically removes all consolestatements:

有一个Babel 宏可以自动删除所有console语句:

https://www.npmjs.com/package/dev-console.macro

https://www.npmjs.com/package/dev-console.macro

回答by Frédéric Hamidi

I would probably abuse the short-circuitingnature of JavaScript's logical AND operatorand replace instances of:

我可能会滥用JavaScript 的逻辑 AND 运算符的短路特性并替换以下实例:

console.log("Foo.");

With:

和:

DEBUG && console.log("Foo.");

Assuming DEBUGis a global variable that evaluates to trueif debugging is enabled.

假设DEBUG是一个全局变量,用于评估true是否启用了调试。

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

此策略避免绝育console.log(),因此如果确实需要,您仍然可以在发布模式下调用它(例如,跟踪在调试模式下不会发生的问题)。

回答by bjornd

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

只需将 console.log 替换为用于生产的空函数。

if (!DEBUG_MODE_ON) {
    console = console || {};
    console.log = function(){};
}

回答by namuol

Clobbering global functions is generally a bad idea.

破坏全局函数通常是一个坏主意。

Instead, you could replace all instances of console.login your code with LOG, and at the beginning of your code:

相反,您可以console.log在代码LOG的开头用,替换代码中的所有实例:

var LOG = debug ? console.log.bind(console) : function () {};

This will still show correct line numbers and also preserve the expected console.logfunction for third party stuff if needed.

这仍将显示正确的行号,并console.log在需要时保留第三方内容的预期功能。

回答by vinesh

One more way to disable console.log in production and keep it in development.

在生产中禁用 console.log 并将其保留在开发中的另一种方法。

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

您可以更改您的开发设置,例如 localhost 和端口。

回答by vsync

This Tiny wrapper override will wrap the original console.logmethod 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.

这个 Tiny 包装器覆盖将console.log用一个内部有检查的函数包装原始方法,你可以从外部控制,如果你想查看控制台日志而不是深入。

I chose window.allowConsolejust as an example flag but in real-life use it would probably be something else. depending on your framework.

window.allowConsole只选择了一个示例标志,但在现实生活中,它可能是其他东西。取决于你的框架。

(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 consolemethods such as warn, time, dirand so on.

此覆盖应在代码层次结构中尽可能“高”地实现,以便在发生之前“捕获”所有日志。这可以扩展到所有其他的console方法,如warntimedir等等。

回答by Raynos

Simple.

简单的。

Add a little bash script that finds all references to console.logand deletes them.

添加一个小 bash 脚本来查找所有引用console.log并删除它们。

Make sure that this batch script runs as part of your deployment to production.

确保此批处理脚本作为部署到生产的一部分运行。

Don't shim out console.logas an empty function, that's a waste of computation and space.

不要console.log作为一个空函数来填充,那会浪费计算和空间。

回答by Attakinsky Blanco

This code works for me:

这段代码对我有用:

if(console=='undefined' || !console || console==null) {
  var console = {
    log : function (string) {
        // nothing to do here!!
    }
  }
}

回答by Iman Mohamadi

enter image description here

enter image description here

The newest versions of chrome show which line of code in which file fired console.log. If you are looking for a log management system, you can try out logeekit allows you to control which groups of logs you want to see.

最新版本的 chrome 显示了哪个文件中的哪一行代码触发了 console.log。如果您正在寻找日志管理系统,您可以尝试logeek,它允许您控制要查看的日志组。

回答by deepakssn

// In Development:
var debugMode = true

// In Prod:
var debugMode = false

// This function logs console messages when debugMode is true .
function debugLog(logMessage) {
    if (debugMode) {
        console.log(logMessage);
    }
}

// Use the function instead of console.log
debugLog("This is a debug message");