在我当前具有大量依赖项的项目中,我需要一种方法来禁用特定库的控制台访问,以便这些文件不能使用任何控制台功能.
我当然可以通过简单地在库包中找到并替换它来禁用控制台功能,但是因为这个项目有很多依赖性,这会使更新库变得非常麻烦.
我知道我可以通过用空功能块覆盖它来禁用控制台功能:
console.log = function(){};
Run Code Online (Sandbox Code Playgroud)
但是这会禁用整个项目的控制台功能.所以我正在寻找一个实现,或一行代码,我可以用它来禁用特定文件或代码块的控制台功能.
console.log// Preserve the old console.log
const log = console.log;
// Used a dictionary because it's faster than lists for lookups
const whiteListedFunctions = {"hello": true};
// Whitelisting "middleware". We used the function's name "funcName"
// as a criteria, but it's adaptable
const isWhitelisted = callerData => callerData.funcName in whiteListedFunctions;
// Replacing the default "console.log"
console.log = arg => {
const stack = new Error().stack.split("at")[2].trim().split(' ');
const fileParts = stack[1].substr(1, stack[1].length - 2).split(':');
const callerData = {
funcName: stack[0],
file: fileParts.slice(0, fileParts.length - 2).join(':'),
lineColNumber: fileParts.slice(fileParts.length - 2).join(':')
};
if (isWhitelisted(callerData)) { // Filtering happens here
log(arg);
}
};
// Define the calling functions
function hello() { console.log("hello"); }
function world() { console.log("world"); }
hello(); // => Prints hello
world(); // => Doesn't print anythingRun Code Online (Sandbox Code Playgroud)
console.logconsole.log通过用新的 logger覆盖来替换。该记录器将把要记录的消息作为参数(可能是多个参数?)。在此函数中,您还需要查找与调用者函数(想要调用)相关的数据console.log。这部分有点“hacky”(但在本例中它完成了工作)。我们基本上创建一个Error并检查它的stack属性,如下所示new Error().stack。这会给我们这个痕迹
console.log.arg [as log] ( https://stacksnippets.net/js:25:7 )的错误在 hello ( https://stacksnippets.net/js:41:11 ) 在https://stacksnippets 。净/js:48:1
处理(分割、映射等)跟踪后,我们得到调用函数数据。例如这里我们有
这一点的灵感来自于VLAZ在如何根据特定 javascript 源(方法、文件)或消息内容的条件禁用 console.log 消息中的答案,因此请务必检查一下。非常好的和彻底的帖子。
为了理解跟踪,我们可以知道new Error().stack.split("at")[INDEX].trim().split(' ')您想要在堆栈跟踪中定位的函数调用INDEX的位置。因此,如果您想获得与本示例中使用的不同的“级别” ,请尝试更改INDEX