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

我对 Javascript 开发相当新,所以这可能是一个真正的新手问题。

我有一个 应用程序,它用 console.log();进行调试。

我已经让 完成了所有构建时间的组合。它输出一个用于调试的 app.debug.js和一个用于生产的 app.min.js

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

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

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

这可能吗?

149646 次浏览

把这个放在文件的顶部:

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

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

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

像其他事情一样重写它。

只要记住,使用这个方法,每个 console.log 调用仍然会调用一个(空)函数,这会导致开销,如果有100个 console.log 命令,那么仍然会调用100个空函数。

不确定这会导致多少开销,但是会有一些,最好是有一个标志来打开调试,然后使用大致如下的代码:

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

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

当我需要查看日志时,我只需在控制台中键入 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);

为了全面起见,这将覆盖所有控制台方法,而不仅仅是 console.log

你可以查看 UglifyJS: http://jstarrdewar.com/blog/2013/02/28/use-uglify-to-automatically-strip-debug-messages-from-your-javascript/,< a href = “ https://github.com/mishoo/UglifyjS”rel = “ nofollow”> https://github.com/mishoo/uglifyjs 我还没试过。

引用,

 if (typeof DEBUG === 'undefined') DEBUG = true; // will be removed


function doSomethingCool() {
DEBUG && console.log("something cool just happened"); // will be removed }

日志消息行将被 Uglify 的死代码删除器删除 (因为它会擦除任何总是计算为 那么第一个条件也是如此。但是当你测试为 未压缩的代码,DEBUG 将启动未定义的,第一 条件将设置为 true,并且您的所有 console.log ()消息 会成功的。

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

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

我用的东西和实验室的差不多。将控制台保存在一个闭包中,这样就可以在一个可移植函数中实现所有功能。

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;
}
}
})();

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

没有理由让所有的 console. log 都在 prod 环境中遍布您的项目... ... 如果您想以正确的方式来做这件事,那么使用“ drop _ sole”选项将 UglifyJS2添加到您的部署过程中。

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

特点:

  1. 它安全地覆盖 console.log。
  2. 注意控制台是否可用(哦,是的,您也需要考虑这个因素)
  3. 存储所有日志(即使它们被禁用) ,以备以后检索。
  4. 处理主要的控制台功能,如 logwarnerrorinfo

是开放的修改,并将更新每当新的建议出现。

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

在阅读了大量文章后,我自己制定了如下解决方案:

剧本:

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);
}
}

用法:

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

例子:

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

我是这么做的

    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");

也发布在这里。 http://bhavinsurela.com/naive-way-of-overriding-console-log/

当 url 不包含 localhost 时,这将覆盖 console.log 函数。您可以用自己的开发设置替换本地主机。

// overriding console.log in production
if(window.location.host.indexOf('localhost:9000') < 0) {
console.log = function(){};
}

或者,如果您只是想重新定义控制台的行为(例如,为了添加日志) 你可以这样做:

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