前言
开头讨论了事物一般是如何工作的。如果您只关心代码,请跳过简介并滚动到解决方案标题。
介绍
问题:
Web 应用程序中有很多控制台噪音。很大一部分噪音来自我们无法访问的第三方代码。一些日志噪音也可能来自我们的代码。
要求:
通过停止日志来减少噪音。仍然应该保留一些日志,并且关于这些的决定应该与正在执行日志记录的代码分离。所需的粒度是“每个文件”。我们应该能够选择哪些文件添加或不添加日志消息。最后,这不会在生产代码中使用。
假设:这将在开发人员控制的浏览器中运行。在这种情况下,我不会关注向后兼容性。
前期工作:
首先可以使用此全局启用/禁用日志记录
(function (original) {
console.enableLogging = function () {
console.log = original;
};
console.disableLogging = function () {
console.log = function () {};
};
})(console.log);
(代码发布在问题中,但也在这里供参考)
- 但是,这不允许任何粒度。
- 这可以修改为仅适用于特定模块,但不能用于第三方代码。
- 一种混合方法是全局禁用日志记录,但在我们的每个模块中启用它。问题是我们必须修改我们的每个文件,我们不会得到一些可能有用的外部消息。
可以使用日志框架,但它可能是一种矫枉过正。虽然,老实说,我认为这就是我想要的,但它可能需要一些集成到产品中。
所以,我们需要一些轻量级的东西,它有一些配置并且不需要漂亮。
提议:
登录者(标题可能会发生变化)
让我们从基础开始——我们已经知道我们可以覆盖全局日志功能。我们会接受它并与之合作。但首先,让我们认识到该console
对象支持的不仅仅是.log
. 可以使用各种日志记录功能。So-oo,让我们禁用所有这些。
沉默一切
//shorthand for further code.
function noop() {}
const savedFunctions = Object.keys(console)
.reduce((memo, key) => {
if(typeof console[key] == "function") {
//keep a copy just in case we need it
memo[key] = console[key];
//de-fang any functions
console[key] = noop;
}
return memo;
},
{});
console.log("Hello?");
console.info("Hello-o-o-o?");
console.warn("Can anybody hear me?");
console.error("I guess there is nobody there...");
savedFunctions.log("MUAHAHAHA!")
这显然可以改进,但它展示了如何停止任何和所有日志记录。实际上,console.error
可能应该留下并且console.warn
可能也有用。但这不是万能的解决方案。
接下来,既然我们可以覆盖控制台功能......为什么不提供我们自己的呢?
自定义日志记录
const originalLog = console.log;
console.log = function selectiveHearing() {
if (arguments[0].indexOf("die") !== -1) {
arguments[0] = "Have a nice day!";
}
return originalLog.apply(console, arguments)
}
console.log("Hello.");
console.log("My name is Inigo Montoya.");
console.log("You killed my father.");
console.log("Prepare to die.");
这就是我们推出自己的迷你日志框架所需的所有工具。
如何进行选择性日志记录
唯一缺少的是确定来自哪个文件。我们只需要一个堆栈跟踪。
// The magic
console.log(new Error().stack);
/* SAMPLE:
Error
at Object.module.exports.request (/home/vagrant/src/kumascript/lib/kumascript/caching.js:366:17)
at attempt (/home/vagrant/src/kumascript/lib/kumascript/loaders.js:180:24)
at ks_utils.Class.get (/home/vagrant/src/kumascript/lib/kumascript/loaders.js:194:9)
at /home/vagrant/src/kumascript/lib/kumascript/macros.js:282:24
at /home/vagrant/src/kumascript/node_modules/async/lib/async.js:118:13
at Array.forEach (native)
at _each (/home/vagrant/src/kumascript/node_modules/async/lib/async.js:39:24)
at Object.async.each (/home/vagrant/src/kumascript/node_modules/async/lib/async.js:117:9)
at ks_utils.Class.reloadTemplates (/home/vagrant/src/kumascript/lib/kumascript/macros.js:281:19)
at ks_utils.Class.process (/home/vagrant/src/kumascript/lib/kumascript/macros.js:217:15)
*/
(相关位复制在这里。)
诚然,有一些更好的方法可以做到这一点,但不是很多。它要么需要一个框架,要么是特定于浏览器的——错误堆栈不受官方支持,但它们可以在 Chrome、Edge 和 Firefox 中使用。另外,来吧 - 它实际上是一条线 - 我们想要简单并且不介意肮脏,所以我很高兴权衡。
解决方案
把它们放在一起。警告:不要在生产中使用它
(function(whitelist = [], functionsToPreserve = ["error"]) {
function noop() {}
//ensure we KNOW that there is a log function here, just in case
const savedFunctions = { log: console.log }
//proceed with nuking the rest of the chattiness away
Object.keys(console)
.reduce((memo, key) => {
if(typeof console[key] == "function" && functionsToPreserve.indexOf(key) != -1 ) {
memo[key] = console[key];
console[key] = noop;
}
return memo;
},
savedFunctions); //<- it's a const so we can't re-assign it. Besides, we don't need to, if we use it as a seed for reduce()
console.log = function customLog() {
//index 0 - the error message
//index 1 - this function
//index 2 - the calling function, i.e., the actual one that did console.log()
const callingFile = new Error().stack.split("\n")[2];
if (whitelist.some(entry => callingFile.includes(entry))) {
savedFunctions.log.apply(console, arguments)
}
}
})(["myFile.js"]) //hey, it's SOMEWHAT configurable
或者黑名单
(function(blacklist = [], functionsToPreserve = ["error"]) {
function noop() {}
//ensure we KNOW that there is a log function here, just in case
const savedFunctions = {
log: console.log
}
//proceed with nuking the rest of the chattiness away
Object.keys(console)
.reduce((memo, key) => {
if (typeof console[key] == "function" && functionsToPreserve.indexOf(key) != -1) {
memo[key] = console[key];
console[key] = noop;
}
return memo;
},
savedFunctions); //<- it's a const so we can't re-assign it. Besides, we don't need to, if we use it as a seed for reduce()
console.log = function customLog() {
//index 0 - the error message
//index 1 - this function
//index 2 - the calling function, i.e., the actual one that did console.log()
const callingFile = new Error().stack.split("\n")[2];
if (blacklist.some(entry => callingFile.includes(entry))) {
return;
} else {
savedFunctions.log.apply(console, arguments);
}
}
})(["myFile.js"])
所以,这是一个自定义记录器。当然,它并不完美,但它会完成这项工作。而且,嘿,由于白名单有点松散,它可以变成一个优势:
- 将一堆共享子字符串的文件列入白名单,例如,所有文件都
myApp
可以包括myApp1.js
,myApp2.js
和myApp3.js
.
- 虽然如果你想要特定的文件,你可以只传递全名,包括扩展名。我怀疑会有一堆重复的文件名。
- 最后,堆栈跟踪将包含调用函数的名称(如果有),因此您实际上可以只传递它,并且它将基于每个函数列入白名单。但是,它依赖于具有名称的函数,并且函数名称更有可能发生冲突,因此请谨慎使用
除此之外,当然可以进行改进,但这是它的基础。例如,info
/warn
方法也可以被覆盖。
所以,这个,如果使用,应该只在开发版本中。有很多方法可以使它不投入生产,所以我不会讨论它们,但我可以提一件事:如果你将它保存为书签,你也可以在任何地方使用它
javascript:!function(){function c(){}var a=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],b=arguments.length<=1||void 0===arguments[1]?["error"]:arguments[1],d={log:console.log};Object.keys(console).reduce(function(a,d){return"function"==typeof console[d]&&b.indexOf(d)!=-1&&(a[d]=console[d],console[d]=c),a},d),console.log=function(){var c=(new Error).stack.split("\n")[2];a.some(function(a){return c.includes(a)})&&d.log.apply(console,arguments)}}(["myFile.js"]);
这是缩小的(尽管我首先通过 Babel 传递它,以使用 ES5 缩小)并且在一定程度上仍然是可配置的,因为您可以更改可以传递白名单的那一端。但除此之外,它的工作原理相同,并且与代码库完全解耦。它不会在页面加载时运行,但如果需要,您可以将其用作用户脚本(仍然解耦)或将其包含在 dev/debug 构建中的其他 JS 文件之前。
请注意 - 这适用于 Chrome、Edge 和 Firefox。这些都是最新的浏览器,所以我假设开发人员至少会使用其中一个。该问题被标记为 Chrome,但我决定扩大支持范围。仅 Chrome 的解决方案可能会稍微好一些,但实际上并没有太大的功能损失。