How Can I Log Every Method Call In Node.js Without Adding Debug Lines Everywhere?
Solution 1:
The answer is essentially correct, but here's how to avoid infinite recursion
Javascript
(function () {
var oldCall = Function.prototype.call;
var newCall = function(self) {
Function.prototype.call = oldCall;
console.log('Function called:', this.name);
var args = Array.prototype.slice.call(arguments, 1);
var res = this.apply(self, args);
Function.prototype.call = newCall;
return res
}
Function.prototype.call = newCall;
})();
Coffeescript
do ->
oldCall = Function::call
newCall = (self) ->
Function::call = oldCall
console.log"Function called: #{this.name}"
args = Array.prototype.slice.callarguments, 1
res = this.apply self, args
Function::call = newCall
res
Function::call = newCall
Solution 2:
This is one alternative, not entirely sure how reliable it is though, it feels a bit wrong:
(function () {
var oldCall = Function.prototype.call;
var newCall = function(self) {
Function.prototype.call = oldCall;
console.log('Function called:', this.name);
var args = Array.prototype.slice.call(arguments, 1);
Function.prototype.call = newCall;
this.apply(self, args);
}
Function.prototype.call = newCall;
})();
As you can see, it overwrites the call
function - this creates a slight problem when you try to call console.log()
so you need to swap the function back. But it seems to work!
EDIT
Since this is tagged CoffeeScript:
do ->
oldCall = Function::call
newCall = (self) ->
Function::call = oldCall
console.log"Function called: #{this.name}"
args = Array.prototype.slice.callarguments, 1Function::call = newCall
this.apply self, args
Function::call = newCall
Solution 3:
I'm guessing this is a web app, in which case if you are using connect you can use a logger middleware that logs the user and the URL path, which is probably sufficient. Otherwise, you are going to have to do some metaprogramming along the lines of wrapping each function in a wrapper function to do the logging.
functionlogCall(realFunc, instance) {
returnfunction() {
log.debug('User: ' + instance.user_id + ' method ' + realFunc.name);
return realFunc.apply(instance, arguments);
};
}
For this to work, your class method's must be named functions, not anonymous.
functionsendMessage() {
//code to send message//can use `this` to access instance properties
}
functionMyClass(userId) {
this.userId = userId; //or whateverthis.sendMessage = logCall(sendMessage, this);
//repeat above line for each instance method you want instrumented for logging
}
Post a Comment for "How Can I Log Every Method Call In Node.js Without Adding Debug Lines Everywhere?"