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


当前回答

你可以使用javascript AOP(例如jquery-aop)来拦截所有对console.debug/log的调用,如果某个全局变量被设置为false,就不进行实际的调用。

您甚至可以(不时地)执行ajax调用,这样就可以更改服务器上启用/禁用日志的行为,当在登台环境或类似环境中遇到问题时启用调试,这可能非常有趣。

其他回答

当使用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上编写测试代码

你可以使用logeek,它可以让你控制你的日志消息的可见性。你可以这样做:

<script src="bower_components/dist/logeek.js"></script>

logeek.show('security');

logeek('some message').at('copy');       //this won't be logged
logeek('other message').at('secturity'); //this would be logged

你也可以使用logeek.show('nothing')来完全禁用每条日志消息。

这是来自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');
});

如果你正在使用gulp,那么你可以使用这个插件:

使用下面的命令安装这个插件: NPM安装gulp-remove-logging 接下来,将这一行添加到gulpfile中: Var gulp_remove_logging = require("gulp-remove-logging"); 最后,将配置设置(见下文)添加到gulpfile中。 任务配置 饮而尽。任务("remove_logging",函数(){ 返回gulp.src (" src / javascript / * * / * . js”) .pipe ( gulp_remove_logging () ) .pipe ( gulp.dest ( “构建/ javascript /” ) ); });

我这样写道:

//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)来启用它