Capturing javascript console.log?

Javascript

Javascript Problem Overview


> Possible Duplicate:
> Intercept calls to console.log in Chrome
> Can I extend the console object (for rerouting the logging) in javascript?

When my JS app writes to the console.log, I want to capture that log message so that I can AJAX that log output to the server. How do I do that?

The code that writes to the log is from external services, which is why I can't just ajax it directly.

Javascript Solutions


Solution 1 - Javascript

You can hijack JavaScript functions in the following manner:

(function(){
    var oldLog = console.log;
    console.log = function (message) {
        // DO MESSAGE HERE.
        oldLog.apply(console, arguments);
    };
})();
  1. Line 1 wraps your function in a closure so no other functions have direct access to oldLog (for maintainability reasons).
  2. Line 2 captures the original method.
  3. Line 3 creates a new function.
  4. Line 4 is where you send message to your server.
  5. Line 5 is invokes the original method as it would have been handled originally.

apply is used so we can invoke it on console using the original arguments. Simply calling oldLog(message) would fail because log depends on its association with console.


Update Per zzzzBov's comment below, in IE9 console.log isn't actually a function so oldLog.apply would fail. See https://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9 for more details.

Solution 2 - Javascript

Simple:

function yourCustomLog(msg) {
  //send msg via AJAX
}

window.console.log = yourCustomLog;

You might want to override the whole console object to capture console.info, console.warn and such:

window.console = {
  log : function(msg) {...},
  info : function(msg) {...},
  warn : function(msg) {...},
  //...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbevanbView Question on Stackoverflow
Solution 1 - JavascriptBrian NickelView Answer on Stackoverflow
Solution 2 - JavascriptTomasz NurkiewiczView Answer on Stackoverflow