Actual interceptor for console.log in javascript

The usual sentence ( Capture javascript console.log? ) For js console.log interceptor does not match two values, both are serious:

(i) all calls in the real browser console now appear from the same line where the new function is defined, and not where the call is made.

(ii) the intercepted arguments have not yet been formatted as they do console.log(i.e. substitution substitutions %, %o):

(function() {
  function send_stuff(){ /* Deal with console arguments. */ }
  
  var oldLog=console.log;
  console.log=function(msg) {
    oldLog.apply(this,arguments);
    send_stuff(Array.prototype.slice.call(arguments).join());
  }
}())

console.log("test");
console.log("Hello %s", "Bob");
console.log("Here is an object %o", { stuff: "thing" });
Run codeHide result
 

Maybe something is better (for example, something capable of capturing the actual buffer contents of console.log).

Edit:   : /, console.log - a-la-printf - % . % o, () . , ( , , )

,

+4
1

, console.log , , oldLog.apply(this,arguments); . , , console.error , , , , .

, ,

(function () {

  function origin() {
    try {
      throw Error('');
    } catch (err) {
      return err.stack.split('\n').slice(-1)[0];
    }
  }

  function send_stuff() { /* Deal with console arguments. */ }

  var oldLog = console.log;
  console.log = function (msg) {
    oldLog.call(this, ...arguments, origin());
    send_stuff(Array.prototype.slice.call(arguments).join());
  };

})();

console.log("test");
console.log("Hello %s", "Bob");
console.log("Here is an object %o", {
  stuff: "thing"
});
-1

Source: https://habr.com/ru/post/1612234/


All Articles