Javascript 覆盖 console.log(); 用于生产

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7042611/
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 00:24:35  来源:igfitidea点击:

Override console.log(); for production

javascriptdebugging

提问by Chase Florell

I'm fairly new to Javascript development so this might be a real newbie question.

我对 Javascript 开发还很陌生,所以这可能是一个真正的新手问题。

I've got a sencha-touchapplication riddled with console.log();for debugging purposes.

我有一个sencha-touch应用程序,console.log();用于调试目的。

I've got chirpydoing all of my build time combining. It outputs a app.debug.jsfor debugging as well as a app.min.jsfor production

我有快活做了我所有的编译时间相结合。它输出一个app.debug.js用于调试以及app.min.js用于生产

Now I could go through all of my code files looking for console.log();and delete it manually when I'm ready to go to production, but I'm wondering if there's a way to override the method.

现在console.log();,当我准备投入生产时,我可以查看我的所有代码文件并手动删除它,但我想知道是否有一种方法可以覆盖该方法。

Basically, whenever the console.log();method is called, DO NOTHING.

基本上,无论何时console.log();调用该方法,什么都不做。

That way, I can put the override code file in my production config, and NOT in my debug config.

这样,我可以将覆盖代码文件放在我的生产配置中,而不是我的调试配置中。

Is this possible?

这可能吗?

回答by Naftali aka Neal

Put this at the top of the file:

把它放在文件的顶部:

var console = {};
console.log = function(){};

For some browsers and minifiers, you may need to apply this onto the window object.

对于某些浏览器和缩小器,您可能需要将其应用到 window 对象上。

window.console = console;

回答by Ludovic Feltz

Or if you just want to redefine the behavior of the console (in order to add logs for example) You can do something like that:

或者,如果您只想重新定义控制台的行为(例如为了添加日志),您可以执行以下操作:

// define a new console
var console=(function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            // Your code
        },
        info: function (text) {
            oldCons.info(text);
            // Your code
        },
        warn: function (text) {
            oldCons.warn(text);
            // Your code
        },
        error: function (text) {
            oldCons.error(text);
            // Your code
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;

回答by posit labs

It would be super useful to be able to toggle logging in the production build. The code below turns the logger off by default.

能够在生产版本中切换日志记录将非常有用。下面的代码默认关闭记录器。

When I need to see logs, I just type debug(true)into the console.

当我需要查看日志时,我只需debug(true)在控制台中输入即可。

var consoleHolder = console;
function debug(bool){
    if(!bool){
        consoleHolder = console;
        console = {};
        Object.keys(consoleHolder).forEach(function(key){
            console[key] = function(){};
        })
    }else{
        console = consoleHolder;
    }
}
debug(false);

To be thorough, this overrides ALL of the console methods, not just console.log.

彻底地说,这会覆盖所有控制台方法,而不仅仅是console.log.

回答by Zirak

console.log = function(){};

Override it like any other thing.

像其他任何事情一样覆盖它。

回答by Ryan

I use something similar to what posit labs does. Save the console in a closure and you have it all in one portable function.

我使用的东西类似于 posit labs 所做的。将控制台保存在一个闭包中,您就可以在一个便携式功能中拥有它。

var GlobalDebug = (function () {
    var savedConsole = console;
    return function(debugOn,suppressAll){
        var suppress = suppressAll || false;
        if (debugOn === false) {
            console = {};
            console.log = function () { };
            if(suppress) {
                console.info = function () { };
                console.warn = function () { };
                console.error = function () { };
            } else {
                console.info = savedConsole.info;
                console.warn = savedConsole.warn;
                console.error = savedConsole.error;              
            }
        } else {
            console = savedConsole;
        }
    }
})();

Just do globalDebug(false) to toggle log messages off or globalDebug(false,true) to remove all console messages.

只需执行 globalDebug(false) 以关闭日志消息或执行 globalDebug(false,true) 以删除所有控制台消息。

回答by Sunny R Gupta

I would recommend using: https://github.com/sunnykgupta/jsLogger

我建议使用:https: //github.com/sunnykgupta/jsLogger

Features:

特征:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.
  1. 它安全地覆盖了 console.log。
  2. 如果控制台不可用,请注意(哦,是的,您也需要考虑这一点。)
  3. 存储所有日志(即使它们被抑制)以供以后检索。
  4. 处理主要的控制台功能,如logwarnerrorinfo

Is open for modifications and will be updated whenever new suggestions come up.

可以修改,并且会在出现新建议时更新。

Disclaimer:I am the author of the plugin.

免责声明:我是插件的作者。

回答by Pappa

You could also use regex to delete all the console.log() calls in your code if they're no longer required. Any decent IDE will allow you to search and replace these across an entire project, and allow you to preview the matches before committing the change.

如果不再需要,您还可以使用正则表达式删除代码中的所有 console.log() 调用。任何体面的 IDE 都允许您在整个项目中搜索和替换这些,并允许您在提交更改之前预览匹配项。

\s*console\.log\([^)]+\);

回答by Kayem

Just remember that with this method each console.log call will still do a call to a (empty) function causing overhead, if there are 100 console.log commands, you are still doing 100 calls to a blank function.

请记住,使用此方法,每个 console.log 调用仍会调用(空)函数,从而导致开销,如果有 100 个 console.log 命令,您仍然会调用 100 次空函数。

Not sure how much overhead this would cause, but there will be some, it would be preferable to have a flag to turn debug on then use something along the lines of:

不确定这会导致多少开销,但会有一些开销,最好有一个标志来打开调试,然后使用以下内容:

var debug=true; if (debug) console.log('blah')

回答by neiker

Theres no a reason to let all that console.log all over your project in prod enviroment... If you want to do it on the proper way, add UglifyJS2to your deployment process using "drop_console" option.

没有理由让所有 console.log 在生产环境中遍布您的项目...如果您想以正确的方式进行操作,请使用“drop_console”选项将UglifyJS2添加到您的部署过程中。

回答by Rodolpho Brock

After read a lot of posts, I made my own solution as follow:

在阅读了很多帖子后,我提出了自己的解决方案如下:

SCRIPT:

脚本:

function extendConsole() {
    "use strict";
    try {
        var disabledConsoles = {};

        console.enable = function (level, enabled) {
            // Prevent errors in browsers without console[level]
            if (window.console === 'undefined' || !window.console || window.console === null) {
                window.console = {};
            }
            if (window.console[level] === 'undefined' || !window.console[level] || window.console[level] == null) {
                window.console[level] = function() {};
            }

            if (enabled) {
                if (disabledConsoles[level]) {
                    window.console[level] = disabledConsoles[level];
                }
                console.info("console." + level + "() was enabled.");
            } else {
                disabledConsoles[level] = window.console[level];
                window.console[level] = function () { };
                console.info("console." + level + "() was disabled.");
            }
        };
    } catch (exception) {
        console.error("extendConsole() threw an exception.");
        console.debug(exception);
    }
}

USAGE:

用法:

extendConsole();
console.enable("debug", window.debugMode);

EXAMPLE:

例子:

http://jsfiddle.net/rodolphobrock/2rzxb5bo/10/

http://jsfiddle.net/rodolphobrock/2rzxb5bo/10/