Reputation: 2388
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
?
Upvotes: 3
Views: 1440
Reputation: 131
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");
Upvotes: 2
Reputation: 3541
Alexey Kozyatinskiy's approach is cool. However, if not-pretty code like this.myInfo(1,2,3)()
is a more serious problem than ugly console output, you could use the wrapper you posted in your question and print needed filename and line number manually having it extracted from new Error().stack
. I'd personnaly use Alexey's method unless there was a team working on this project.
Upvotes: 1