Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing javascript console.log? [duplicate]

Tags:

javascript

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.

like image 775
bevanb Avatar asked Jul 09 '12 21:07

bevanb


People also ask

How do I copy the output console in JavaScript?

Right click on the object in console and click Store as a global variable. the output will be something like temp1. type in console copy(temp1) paste to your favorite text editor.

What does .log do in JavaScript?

The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console.

Does console log equal print?

The only notable difference between the two is that, when printing an object, console. log gives special treatment to HTML elements, while console. dir displays everything as plain objects.


2 Answers

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 console.log.apply not working in IE9 for more details.

like image 117
Brian Nickel Avatar answered Sep 18 '22 20:09

Brian Nickel


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) {...},   //... } 
like image 44
Tomasz Nurkiewicz Avatar answered Sep 18 '22 20:09

Tomasz Nurkiewicz