Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping `console.log` and retaining call stack

In my logging helper class, I have the following:

this.myInfo = console.info.bind(console);

When I call my myInfo function from elsewhere, the calling object and line number are correctly retained and logged in the Chrome devtools.

When I run myInfo though, I also want to run another local function in addition to the console.info. Hence, I figured I could just wrap the above and it would work. I've come up with the following:

var obj = this;
this.myInfo = (function() {
    console.info.apply(this, arguments);
    myOtherFunc.apply(obj, arguments);
}).bind(console);

The problem is that unlike my first example, I lose the calling context for console.info, and the wrong line number and file are logged in the devTools.

How can I wrap the first example and retain the proper context for the console.info?

like image 461
LJW Avatar asked Oct 21 '25 06:10

LJW


1 Answers

You can use getter. In getter you call your other function and then return console.info.bind(console) to caller.

Object.defineProperty(this, "myInfo", { get: function () { 
  myOtherFunc();
  return console.info.bind(console); 
}});

In case of passing arguments. You can define following function:

this.myInfo = function()
{
  myOtherFunc.apply(null, arguments);
  return console.bind.apply(console, arguments);
}
// example of call
this.myInfo(1,2,3)();

I've new solution. You can implement your console.log wrapper in separate JS file or evaluate it with sourceURL then go to Chrome DevTools settings and add "console-wrapper.js" url to blackbox pattern or blackbox this script by link when first message is arrived to console. When script become blackboxed then all messages will have correct location in source code. It works in last Google Chrome Canary build and will be available in stable in around two months.

eval("\
function myAwesomeConsoleLogWrapper() {\
  console.log.call(console, arguments);\
  makeAnotherWork();\
}\
//# sourceURL=console-wrapper.js");
like image 194
Alexey Kozyatinskiy Avatar answered Oct 23 '25 19:10

Alexey Kozyatinskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!