简体   繁体   中英

How to overwrite / intercept console.log and output original log to console

I'm trying to intercept console.log and write it to an array to access the log programatically. This should be cross browser compliant.

window["log"]=[];
var logger = console.log;
console.log = function() {
  window["log"].push({arguments});
  // neither seems to output as original
  logger( arguments );
  logger.call ( arguments );
  logger.call ( console, arguments );
  logger.apply ( arguments );
}

My problem is that logger( arguments) always writes an array to console and not the original message. How can I make console output the original message with original line numbers and file?

You're looking for:

logger.apply(console, arguments);

...which calls the original function with this set to console and with arguments spread out as discrete arguments.


Side note: If you want to be broadly-compatible, you'll need to replace the ES2015+ code here:

window["log"].push({arguments});

with ES5-compatible code:

window["log"].push({arguments: arguments});

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