简体   繁体   中英

Is there a way in JavaScript to listen console events?

I'm trying to write handler for uncaught exceptions and browser warnings in Javascript. All errors and warnings should be sent to server for later review.

Handled exceptions can be caught and easily logged with

console.error("Error: ...");

or

console.warn("Warning: ...");

So they are not problem if they are called from javascript code, even more, unhandled exceptions could be caught with this peace of code:

window.onerror = function(){
    // add to errors Stack trace etc.
   });
}

so exceptions are pretty covered but I've stuck with warnings which browser sends to console. For instance security or html validation warnings. Example below is taken from Google Chrome console

The page at https://domainname.com/ ran insecure content from http://domainname.com/javascripts/codex/MANIFEST.js .

It would be great if there is some event like window.onerror but for warnings. Any thoughts?

You could just wrap the console methods yourself. For example, to record each call in an array:

var logOfConsole = [];

var _log = console.log,
    _warn = console.warn,
    _error = console.error;

console.log = function() {
    logOfConsole.push({method: 'log', arguments: arguments});
    return _log.apply(console, arguments);
};

console.warn = function() {
    logOfConsole.push({method: 'warn', arguments: arguments});
    return _warn.apply(console, arguments);
};

console.error = function() {
    logOfConsole.push({method: 'error', arguments: arguments});
    return _error.apply(console, arguments);
};

More Succint Way:

 // this method will proxy your custom method with the original one function proxy(context, method, message) { return function() { method.apply(context, [message].concat(Array.prototype.slice.apply(arguments))) } } // let's do the actual proxying over originals console.log = proxy(console, console.log, 'Log:') console.error = proxy(console, console.error, 'Error:') console.warn = proxy(console, console.warn, 'Warning:') // let's test console.log('im from console.log', 1, 2, 3); console.error('im from console.error', 1, 2, 3); console.warn('im from console.warn', 1, 2, 3); 

I know it's an old post but it can be useful anyway as others solution are not compatible with older browsers.

You can redefine the behavior of each function of the console (and for all browsers ) like this:

// define a new console
var console = (function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            // Your code
        },
        info: function (text) {
            oldCons.info(text);
            // Your code
        },
        warn: function (text) {
            oldCons.warn(text);
            // Your code
        },
        error: function (text) {
            oldCons.error(text);
            // Your code
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;

I needed to debug console output on mobile devices so I built this drop-in library to capture console output and category and dump it to the page. Check the source code, it's quite straightforward.

https://github.com/samsonradu/Consolify

在用于执行console.log()的相同功能中,只需将相同的消息发布到您正在记录日志的Web服务上。

You're going about this backwards. Instead of intercepting when an error is logged, trigger an event as part of the error handling mechanism and log it as one of the event listeners:

try
{
  //might throw an exception
  foo();
}
catch (e)
{
  $(document).trigger('customerror', e);
}

function customErrorHandler(event, ex)
{
  console.error(ex)
}
function customErrorHandler2(event, ex)
{
  $.post(url, ex);
}

this code uses jQuery and is oversimplified strictly for use as an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM