2013-05-28 2 views
0

Я добавляю форму отчета об ошибке в свой проект. Когда пользователь нажимает кнопку отправки в форме (после того, как они объясняют, что такое ошибка), я получаю информацию о своем браузере автоматически. В настоящее время я могу получить их пользовательский агент и исходный код этой страницы, но я думаю, что было бы очень полезно, если бы я мог также получить любые ошибки, отправленные на консоль браузера.Как получить диагностику браузера

Я googled для таких вещей, как «javascript get console.log content», но на самом деле не нашел ничего полезного.

Я читал о создании «обертки» для window.log, и нашел этот код:

window.log = function(){ 
    log.history = log.history || []; // store logs to an array for reference 
    log.history.push(arguments); 
    if(this.console){ 
    console.log(Array.prototype.slice.call(arguments)); 
    } 
}; 

Но это, кажется, не будут получать ошибки, браузер (хром) посылает на консоль .журнал.

Кто-нибудь знает, как я могу получить ВСЕ ошибки в console.log?

+0

Консоль является частью браузера. Это означает, что вы не можете напрямую передавать сообщения. Вам нужно использовать функцию, которая сохраняет сообщение, а затем 'console.log'. Или вам нужно добавить браузер. –

+0

У меня уже есть функция для замены с помощью console.log, но я хотел иметь возможность получать любые ошибки, которые отправляет браузер. Вероятно, это невозможно, но это была бы очень полезная информация. –

ответ

2

Это казалось интересной идеей. Я придумал, по сути, небольшой класс JavaScript, который переопределяет функции консоли (но позволяет поведение по умолчанию - вы все равно можете видеть информацию в Инспекторе Google Chrome, например).

Это довольно простой в использовании. Сохранить как «consolelogger.js»:

/** 
* ConsoleLogger 
* 
* Tracks the history of the console. 
* @author Johnathon Koster 
* @version 1.0.0 
*/ 
var ConsoleLogger = function() { 

    // Holds an instance of the current object. 
    var _instance = this; 

    this._logOverwrite = function(o) { 

     var _log = o.log; 

     // Overwrites the console.log function. 
     o.log = function(e) { 
      _instance.pushLog(e); 
      // Calls the console.log function (normal browser behavior) 
      _log.call(o, e); 
     } 

     // Overwrites the console.info function. 
     o.info = function(e) { 
      _instance.pushInfoLog(e); 
      // Calls the console.info function (normal browser behavior) 
      _log.call(o, e); 
     } 

     // Overwrites the console.warn function. 
     o.warn = function(e) { 
      _instance.pushWarnLog(e); 
      // Calls the console.warn function (normal browser behavior) 
      _log.call(o, e); 
     } 

     // Overwrites the console.error function. 
     o.error = function(e) { 
      _instance.pushErrorLog(e); 
      // Calls the console.error function (normal browser behavior) 
      _log.call(o, e); 
     } 

    }(console); 

    // Holds the history of the console calls made by other scripts. 
    this._logHistory = []; 
    this._infoHistory = []; 
    this._warnHistory = []; 
    this._errorHistory = []; 

    this._windowErrors = []; 

    /** 
    * This allows users to get the history of items not explicitly added. 
    */ 
    window.onerror = function(msg, url, line) { 
     _instance._windowErrors.push('Message: ' + msg + ' URL: ' + url + ' Line: ' + line); 
    } 

    /** 
    * Adds an item to the log history. 
    * 
    * @param {log} object to log 
    */ 
    this.pushLog = function(log) { 
     this._logHistory.push(log); 
    } 


    /** 
    * Adds an item to the information log history. 
    * 
    * @param {log} object to log 
    */ 
    this.pushInfoLog = function(log) { 
     this._infoHistory.push(log); 
    } 

    /** 
    * Adds an item to the warning log history. 
    * 
    * @param {log} object to log 
    */ 
    this.pushWarnLog = function(log) { 
     this._warnHistory.push(log); 
    } 

    /** 
    * Adds an item to the error log history. 
    * 
    * @param {log} object to log 
    */ 
    this.pushErrorLog = function(log) { 
     this._errorHistory.push(log); 
    } 

    /** 
    * Returns the log history. 
    * @this {ConsoleLogger} 
    * @return {array} the log history. 
    */ 
    this.getLog = function() { 
     return this._logHistory; 
    } 

    /** 
    * Returns the information log history. 
    * @this {ConsoleLogger} 
    * @return {array} the information log history. 
    */ 
    this.getInfoLog = function() { 
     return this._infoHistory; 
    } 

    /** 
    * Returns the warning log history. 
    * @this {ConsoleLogger} 
    * @return {array} the warning log history. 
    */ 
    this.getWarnLog = function() { 
     return this._warnHistory; 
    } 

    /** 
    * Returns the error log history. 
    * @this {ConsoleLogger} 
    * @return {array} the error log history. 
    */ 
    this.getErrorLog = function() { 
     return this._errorHistory; 
    } 

    /** 
    * Returns the window log history. 
    * @this {ConsoleLogger} 
    * @return {array} the window log history. 
    */ 
    this.getWindowLog = function() { 
     return this._windowErrors; 
    } 

    /** 
    * Returns all log histories. 
    * @this {ConsoleLogger} 
    * @return {array} the error log(s) history. 
    */ 
    this.getLogHistory = function() { 
     var _return = []; 
     _return = this._logHistory 
     _return = _return.concat(this._infoHistory); 
     _return = _return.concat(this._warnHistory); 
     _return = _return.concat(this._errorHistory); 
     _return = _return.concat(this._windowErrors); 
     return _return; 
    } 

} 

и добавить его на страницу, как это:

<script src="consolelogger.js"></script> 
<script> 
// Create a new instance of ConsoleLogger 
var logger = new ConsoleLogger; 
</script> 

Теперь вам не нужно делать ничего особенного в ловушку «console.log» , 'console.warn', 'console.info' или 'console.error'. ConsoleLogger сделает это за вас и позволит вам получить историю того, что было добавлено.

Чтобы получить историю вызова эти функции (все они возвращают массив JavaScript):

var logHistory = logger.getLog(); // Get the console.log history 
var infoHistory = logger.getInfoLog(); // Get the console.info history 
var warningHistory = logger.getWarnLog(); // Get the console.warn history 
var errorHistory = logger.getErrorLog(); // Get the console.error history 
var windowLog = logger.getWindowLog(); // Get the window error history 

var allLogs = logger.getLogHistory(); // Returns all log histories as one array. 

Я извиняюсь за столь длительный пост, но это, кажется, сделать трюк! Я также создал GitHub repo; если я буду больше работать над этим, там будут происходить изменения.

+0

это поймает ошибки, отображаемые браузером в консоли? Не только то, что я бы отправил на console.log, но ошибки, возникшие из-за ошибок кодирования? –

+0

Привет, Чарльз! Теперь вы поймете сообщения, которые явно не добавлены с помощью консоли. * Функции. Обратите внимание, что для того, чтобы сообщение было захвачено этим скриптом, оно должно быть уловлено событием window.onerror. – John

+1

Итак, похоже, что все, что мне нужно от вашего скрипта, это «window.onerror = function ...» snippet, так как у меня уже есть система ведения журнала. –

Смежные вопросы