Console integration: get the number of errors / warnings?

So, if you open the inspector, you will get this (if you're out of luck):

enter image description here

I am creating a tiny JS component that displays debugging information - is there a way to read the number of errors and warnings detected so far?

The hacker solution that I could come up with is a bit of a hoax, replacing the console.(error|log|warn) functions with my own, but I have not yet verified whether it works in all cases (for example, outside my code).

Is there a better way to do this?

+8
javascript google-chrome webkit frontend
source share
1 answer

As noted in this answer, it is usually not recommended to change the behavior of your own objects / methods. However, the following code should get you what you need, harmless enough:

 // 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 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 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 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: This is a version of ECMA6, but feel free to run it through Babel if you want it to be compiled for use in older browsers.

+1
source share

All Articles