2

console.log在我的 JS 文件中使用来跟踪应用程序。

问题:日志在生产环境中。
如何console.log从代码中删除行?

PS请不要建议文本解决方案,如find + xargs + grep -v

4

4 回答 4

4

对于我的重要项目,我有自己的内部使用的日志记录函数console.log(),但我的代码中没有console.log()调用,除了这个函数中的一个地方。然后我可以通过更改一个变量来启用或禁用日志记录。

我的函数实际上比这更多地涉及将输出放置到控制台以外的位置的选项,但从概念上讲,它看起来像这样:

// change this variable to false to globally turn off all logging
var myLoggingEnabled = true;   

function myLog() {
    if (myLoggingEnabled) {
        if (window.console && console.log) {
            console.log.apply(this, arguments);
        }
    }
}

然后,您可以使用这样的代码来记录:

myLog(foo);

仅供参考,对于部署的代码紧凑性和性能优化,我还有一个最小化步骤,可以myLog()从我的代码中删除所有调用。这是我选择利用的优化。也许您可以分享为什么您也不会考虑这种类型的优化。

于 2012-08-25T20:52:00.270 回答
3

好吧,您可以使用以下命令禁用它们

console.log=function(){}

但是除非您手动删除它们,否则这些行将在那里。

于 2012-08-25T20:47:01.817 回答
2

如果你使用 Grunt,你可以添加一个任务来删除/注释 console.log 语句。因此不再调用 console.log。

https://www.npmjs.org/package/grunt-remove-logging-calls

于 2014-10-13T22:29:56.823 回答
0

是的,我也遇到过类似的情况,我在这里发过。http://bhavinsurela.com/naive-way-of-overriding-console-log/ 这是代码的要点。

var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.

var logger = {
    force:false,
    original:null,
    log:function(obj)
    {
        var hostName = window.location.hostname;
        if(domainNames.indexOf(hostName) > -1)
        {
            if(window.myLogger.force === true)
            {
                window.myLogger.original.apply(this,arguments);
            }
        }else {
            window.myLogger.original.apply(this,arguments);
        }
    },
    forceLogging:function(force){
        window.myLogger.force = force;
    },
    original:function(){
        return window.myLogger.original;
    },
    init:function(){
        window.myLogger.original = console.log;
        console.log = window.myLogger.log;
    }
}

window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");
于 2016-06-02T06:14:37.873 回答