控制台集成:抛出错误/警告的数量?

时间:2016-06-17 15:06:11

标签: javascript google-chrome webkit frontend

所以,如果你打开检查员,你会得到这个(如果你不走运):

enter image description here

我正在构建一个显示调试信息的小型JS组件 - 到目前为止有没有办法读取遇到的错误和警告的数量?

我能提出的一个hacky解决方案涉及用我自己的console.(error|log|warn)函数替换一些技巧,但我还没有测试它是否适用于所有情况(例如我拥有的代码之外)

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

this回答所述,更改本机对象/方法的行为通常不是一个好主意。但是,以下代码应该以相当无害的方式为您提供所需的内容:

// Add this IIFE to your codebase:
(() => {
	// Get all of the property names of the console:
	const methodsToTrack = Object.keys(window.console);
	// Create an object to collect total usage tallies in:
	const usageRegistry = {};
	for (let i = 0, j = methodsToTrack.length; i < j; i++) {
		let methodName = methodsToTrack[i];
		// If the property is not a method, don't touch it:
		if(typeof window.console[methodName] !== 'function') {
			continue;
		}
		// Cache the original console method here:
		let consoleMethod = window.console[methodName];
		// Overwrite console's method to increment the counter:
		window.console[methodName] = function () {
			// Defining registry properties here, so the registry only contains values for methods that were accessed:
			usageRegistry[methodName] = usageRegistry[methodName] || 0;
			// Execute the original method's behavior, capturing the returned value (if any) in a var, to return it at the end:
			const returnedValue = consoleMethod(...arguments);
			// Increment the usage registry for the executed method:
			usageRegistry[methodName]++;
			// Return the value the console's method would have returned, so the new method has the same signature as the old.
			return returnedValue;
		};

	}
	// Define a funciton to output the totals to a console log, then clean up after itself:
	window.showConsoleTallies = function () {
		window.console.log(usageRegistry);
		usageRegistry['log']--;
	}
})();

// Examples:
showConsoleTallies();
console.log('log 1');
console.error('error 1');
console.log('log 2');
console.warn('warn 1');
console.error('error 2');
console.log('log 3');
showConsoleTallies();

PS:这是ECMA6版本,但如果您希望将其编译为在旧浏览器中使用,请随意run it through Babel