bruh
bruh

Reputation: 93

Is there a function that allows you to listen for console logs in javascript?

I've tried searching it up with multiple different wordings and on multiple websites with no answer, is it possible, is it not, and if so, how? I need to be able to get code to run when anythign is logged to the console and get what that thing was.

Upvotes: 2

Views: 958

Answers (2)

  1. Save the original console

    var log = console.log;

  2. Monkey patch it i.e. modify it when run and all at runtime //use the log instance and 'apply()' method to apply to inherit it //we pass in a date for each call of console.log() when using the original ( log() )

    log.apply(console, [(new Date().toString())].concat([].slice.call(arguments)) ); };

  3. Now everytime we call - log() - we are calling the original //to test it do this

    log('test','this is the original console.log());

  4. This is the patched version

    console.log("This is the Monkey Patched console.log()!", "More text...");

Upvotes: 0

Spectric
Spectric

Reputation: 31992

You can override console.log's default behavior:

var log = console.log;

var logs = []
console.log = function(e) {
  log.apply(console, [].slice.call(arguments));
  logs.push(e) //custom code
};

console.log("Hello World!")

console.log('Printed logs:', logs)

Upvotes: 3

Related Questions