2016-06-17 4 views
8

あなたはインスペクタを開く場合(あなたが不運なら)だから、あなたはこれを取得:コンソール統合:エラー/警告の数を取得しますか?

enter image description here

私はデバッグ情報を表示する小さなJSコンポーネントを構築しています - 読むためにどのような方法がありますこれまでに発生したエラーと警告の数

console.(error|log|warn)の機能を自分のものに置き換えることで、ちょっとしたトリッキーなことが起こる可能性がありますが、自分のコードの外など、すべての場合に機能するかどうかはまだ検証していません。

これを行うより良い方法はありますか?

+0

コードの周りに何らかの種類のラッパーが必要で、キャッチされない例外をキャッチするか、コンソールAPIに何らかの形で結びつける必要があります。 – ssube

+0

クロム拡張機能を使用して[devtools](https://developer.chrome.com/extensions/devtools)を使用できます。 – mash

+1

多分window.onerror = function(msg、url、lineNo、columnNo、error) –

答えて

1

答えがthisに記載されているように、ネイティブオブジェクト/メソッドの動作を変更することはお勧めできません。

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

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

 
// 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気軽にただし、次のコードは、あなたがかなり無害な方法で必要なものを取得する必要があります古いブラウザで使用するためにコンパイルされています。

+0

これはdevtoolのカウンタのような404と例外をカウントしますか? – dandavis

+0

残念ながら、@ dandavis、私はそれが開発者が利用するコンソールメソッドを集計するためにのみ動作すると思います。 'fetch( 'http://invalidajaxcall.com/').catch(showConsoleTallies)'(例えば)は、フードの下でconsole.errorを使用するようには見えません。 – jmealy

関連する問題