是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?


当前回答

当使用React时,你可以利用钩子来管理它,这样它就被限制在你的组件范围内

import { useEffect, useRef } from "react";

type LoggingReplacements = {
  debug?: typeof console["debug"];
  error?: typeof console["error"];
  info?: typeof console["info"];
  log?: typeof console["log"];
  warn?: typeof console["warn"];
};
/**
 * This replaces console.XXX loggers with custom implementations.  It will restore console log on unmount of the component.
 * @param replacements a map of replacement loggers.  They're all optional and only the functions defined will be replaced.
 */
export function useReplaceLogging({
  debug,
  error,
  info,
  log,
  warn,
}: LoggingReplacements): void {
  const originalConsoleDebug = useRef(console.debug);
  const originalConsoleError = useRef(console.error);
  const originalConsoleInfo = useRef(console.info);
  const originalConsoleLog = useRef(console.log);
  const originalConsoleWarn = useRef(console.warn);
  if (debug) {
    console.debug = debug;
  }
  if (error) {
    console.error = error;
  }
  if (info) {
    console.info = info;
  }
  if (log) {
    console.log = log;
  }
  if (warn) {
    console.warn = warn;
  }
  useEffect(() => {
    return function restoreConsoleLog() {
      console.debug = originalConsoleDebug.current;
      console.error = originalConsoleError.current;
      console.info = originalConsoleInfo.current;
      console.log = originalConsoleLog.current;
      console.warn = originalConsoleWarn.current;
    };
  }, []);
}

在https://github.com/trajano/react-hooks/tree/master/src/useReplaceLogging上编写测试代码

其他回答

只需更改标志DEBUG以覆盖console.log函数。这应该能奏效。

var DEBUG = false;
// ENABLE/DISABLE Console Logs
if(!DEBUG){
  console.log = function() {}
}

这是来自SolutionYogi和Chris s的答案的混合。它维护console.log行号和文件名。jsFiddle示例。

// Avoid global functions via a self calling anonymous one (uses jQuery)
(function(MYAPP, $, undefined) {
    // Prevent errors in browsers without console.log
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function(){};

    //Private var
    var console_log = console.log;  

    //Public methods
    MYAPP.enableLog = function enableLogger() { console.log = console_log; };   
    MYAPP.disableLog = function disableLogger() { console.log = function() {}; };

}(window.MYAPP = window.MYAPP || {}, jQuery));


// Example Usage:
$(function() {    
    MYAPP.disableLog();    
    console.log('this should not show');

    MYAPP.enableLog();
    console.log('This will show');
});

如果你使用Webpack,你可以使用Terser插件来完全排除console.log函数调用。

这样你就可以有一个干净的生产应用程序包,它不会暴露不必要的信息,但在调试版本中仍然有所有这些信息。

https://github.com/terser/terser#compress-options

drop_console(默认值:false)——传递true以丢弃对控制台的调用。*功能。如果你希望删除一个特定的函数调用,如console.info和/或在删除函数调用后保留函数参数的副作用,则使用pure_funcs代替。

minimizer: [
    new TerserPlugin({
        terserOptions: {
            compress: {
                pure_funcs: [ 'console.log' ]
            }
        }
    }),
]

或者你也可以使用drop_console: true来排除所有控制台调用。

我这样写道:

//Make a copy of the old console.
var oldConsole = Object.assign({}, console);

//This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)
function setEnabled(bool) {
    if (bool) {
        //Rewrites the disable function with the original one.
        console[this.name] = oldConsole[this.name];
        //Make sure the setEnable will be callable from original one.
        console[this.name].setEnabled = setEnabled;
    } else {
        //Rewrites the original.
        var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};
        //Defines the name, to remember.
        Object.defineProperty(fn, "name", {value: this.name});
        //replace the original with the empty one.
        console[this.name] = fn;
        //set the enable function
        console[this.name].setEnabled = setEnabled

    }
}

不幸的是,它在使用严格模式下不起作用。

使用console。fn。setEnabled = setEnabled然后是console。fn。setEnabled(false) fn可以是几乎任何控制台函数。 你的情况是:

console.log.setEnabled = setEnabled;
console.log.setEnabled(false);

我还写了这个:

var FLAGS = {};
    FLAGS.DEBUG = true;
    FLAGS.INFO = false;
    FLAGS.LOG = false;
    //Adding dir, table, or other would put the setEnabled on the respective console functions.

function makeThemSwitchable(opt) {
    var keysArr = Object.keys(opt);
    //its better use this type of for.
    for (var x = 0; x < keysArr.length; x++) {
        var key = keysArr[x];
        var lowerKey = key.toLowerCase();
        //Only if the key exists
        if (console[lowerKey]) {
            //define the function
            console[lowerKey].setEnabled = setEnabled;
            //Make it enabled/disabled by key.
            console[lowerKey].setEnabled(opt[key]);
        }
    }
}
//Put the set enabled function on the original console using the defined flags and set them.
makeThemSwitchable(FLAGS);

所以你只需要在FLAGS中加入默认值(在执行上面的代码之前),比如FLAGS. log = false,日志功能将在默认情况下被禁用,仍然可以调用console.log.setEnabled(true)来启用它

下面是更详细的:

var DEBUG = false;
if(!DEBUG){
    if(!window.console) window.console = {};
    var methods = ["log", "debug", "warn", "info"];
    for(var i=0;i<methods.length;i++){
        console[methods[i]] = function(){};
    }
}

这将把控制台中存在的通用方法归零,并且可以毫无错误地调用它们,而且几乎没有性能开销。在像IE6这样没有控制台的浏览器的情况下,将创建虚拟方法以防止错误。当然,Firebug中还有更多的函数,比如跟踪、配置文件、时间等。如果在代码中使用它们,则可以将它们添加到列表中。

你也可以检查调试器是否有这些特殊的方法(ie, ie),并将不支持的方法归零:

if(window.console && !console.dir){
var methods = ["dir", "dirxml", "trace", "profile"]; //etc etc
    for(var i=0;i<methods.length;i++){
        console[methods[i]] = function(){};
    }
}