Is there a way in JavaScript to listen console events?

30,507

Solution 1

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);
};

Solution 2

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;

Solution 3

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);

Solution 4

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

Share:
30,507

Related videos on Youtube

Milan Jaric
Author by

Milan Jaric

Updated on May 06, 2020

Comments

  • Milan Jaric
    Milan Jaric almost 4 years

    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?

    • SimplGy
      SimplGy about 11 years
      I was wondering the same thing. Logging negative resource request outcomes would be great, too. :)
  • Milan Jaric
    Milan Jaric over 12 years
    I was thinking on this but it wont work for some of my expectations, for instance, while everything loads into secured page i will get plenty of warnings when some unsecured content is loaded, and that comes from browser, not javascript code. Also I want to cover stupid IE (which is why this came to my mind) and console is undefined there. Anyway you got vote from me :)
  • Milan Jaric
    Milan Jaric over 12 years
    jQuery is not option, what if it fails to load :)
  • Milan Jaric
    Milan Jaric over 12 years
    Not option, it is to expensive, what if page have a 100 errers and warnings, should I make for each ajax request, I don't think so
  • Joe White
    Joe White over 12 years
    @MilanJaric, your objection makes no sense. If you're capturing the console output, you'd still be making 100 AJAX calls.
  • Joe White
    Joe White over 12 years
    @MilanJaric, then what if your error-handling code fails to load? What if your AJAX-log-to-database call fails?
  • Milan Jaric
    Milan Jaric over 12 years
    no I'm keeping it in one variable (object) and when user is about to leave page it will post data to back end.
  • Milan Jaric
    Milan Jaric over 12 years
    it will not if it is in with page inside <script> my handler goes here </script>
  • zzzzBov
    zzzzBov over 12 years
    @MilanJaric, you can trigger custom events without using jQuery. I'm using jQuery only because it's a simple way of showing an example. The code to trigger custom events without jQuery is much more complex and would take longer to write than the minute i spent answering your question.
  • Milan Jaric
    Milan Jaric over 12 years
    Don't be mad at me, but you example is really not something I'm trying to find, even if we put aside jquery, but be sure I REALLY appreciate you time to make this answer. Actually anyone. That is the reason why I never degrade answers from anyone! Thanks allot.
  • Joshua
    Joshua over 12 years
    Milan - If you want to cut down on number of AJAX requests, you could push console messages to an array and just send the array. However generally when the user leaves the page, JS functions will stop, so it won't post the data.
  • Bangkokian
    Bangkokian over 8 years
    But not all errors can be trapped. ERR_BLOCKED_BY_CLIENT is one example. Try trapping that.
  • Kyle Chadha
    Kyle Chadha over 8 years
    For IE use var message = Array.prototype.slice.apply(arguments).join(' '); return _error(message); etc.
  • Pablo Pazos
    Pablo Pazos almost 6 years
    it is better to store the old logs on local variables rather on global ones, this answer shows that way stackoverflow.com/questions/6455631/listening-console-log
  • Inanc Gumus
    Inanc Gumus over 5 years
    @AiShiguang what do you mean?
  • AiShiguang
    AiShiguang over 5 years
    there was a line number shown at the end of the line of the logged content. it can't be pointed to the right position where the console log is called
  • Inanc Gumus
    Inanc Gumus over 5 years
    The question is about listening for console events and that's the correct answer. If what you're looking for is the line numbers, check out this: stackoverflow.com/questions/13815640/…
  • AiShiguang
    AiShiguang over 5 years
    no problem. i did't vote down, bro. as for listening for the console events, this solution still breaks the former feature a little bit
  • Johan Hoeksma
    Johan Hoeksma almost 5 years
    Great way, I use ...message to get all the message items in
  • Inanc Gumus
    Inanc Gumus almost 5 years
    @JohanHoeksma Thx, feel free to edit the answer if you can.
  • Johan Hoeksma
    Johan Hoeksma almost 5 years
    Yes, but I think I made a mistake. Your code is working now :D. I can do it without ...message Thank you :D
  • Inanc Gumus
    Inanc Gumus almost 5 years
    @JohanHoeksma Np :)