我如何在node.js中记录每个方法调用而不到处添加调试行
how can I log every method call in node.js without adding debug lines everywhere?
我想记录发出请求的人的user_id和为javascript类调用的每个方法的方法名称。例如:
35 - log_in
35 - list_of_other_users
78 - log_in
35 - send_message_to_user
35 - connect_to_redis
78 - list_of_other_users
因为一切都是异步的,用户35和78可能同时在做一些事情。所以我想确保每个日志行以他们的user_id开始,这样我就可以grep它,一次只看到一个用户的活动。
是否有一个超级聪明的方法来做到这一点,而不添加记录器语句到每个方法?
答案基本上是正确的,但这里是如何避免无限递归
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.call arguments, 1
res = this.apply self, args
Function::call = newCall
res
Function::call = newCall
这是另一种选择,虽然不完全确定它有多可靠,但感觉有点不对:
(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;
})();
可以看到,它覆盖了call
函数—当您尝试调用console.log()
时,这会产生一个小问题,因此您需要将函数交换回来。但它似乎有效!
编辑
因为这是标记CoffeeScript:
do ->
oldCall = Function::call
newCall = (self) ->
Function::call = oldCall
console.log "Function called: #{this.name}"
args = Array.prototype.slice.call arguments, 1
Function::call = newCall
this.apply self, args
Function::call = newCall
我猜这是一个web应用程序,在这种情况下,如果你使用连接,你可以使用日志记录器中间件记录用户和URL路径,这可能是足够的。否则,您将不得不进行一些元编程,将每个函数包装在包装器函数中以进行日志记录。
function logCall(realFunc, instance) {
return function() {
log.debug('User: ' + instance.user_id + ' method ' + realFunc.name);
return realFunc.apply(instance, arguments);
};
}
要使它工作,你的类方法必须命名为函数,而不是匿名的。
function sendMessage() {
//code to send message
//can use `this` to access instance properties
}
function MyClass(userId) {
this.userId = userId; //or whatever
this.sendMessage = logCall(sendMessage, this);
//repeat above line for each instance method you want instrumented for logging
}
相关文章:
- 注意:wp_enqueue_script调用不正确.在 Wordpress 调试模式下
- 显示错误的Ajax调用无法调试
- 如何调试JS调用
- Chrome在调试AJAX时只显示调用堆栈中的库行
- 从 JS 调用 IE Js 调试器
- AngularJs 2: 如何调试服务调用?(ES6 语法)
- 如何调试从Java调用的JavaScript代码(通过JSR-223)
- 使用调试器从内部函数调用外部函数中定义的变量
- 如何在 D3 中调试 data() 调用
- jQuery .val(#) 在 AJAX 调用后不会更改选择 - 如果调试/暂停,则有效
- 对函数调用和调试的排序感到困惑
- 如何调试ajax REST调用(一般)
- 为什么简单的MVC教程没有调用我的javascript函数?为什么可以't我也调试
- 随叫随到(图表),如何调试“;无法调用方法'getPropertyValue'“为空”;
- jQueryAJAX调用在FF/Chrome中调试时有效
- Javascript调用跟踪使用调试工具,如firedbug
- 在Aptana中调试通过Javascript调用的PHP
- Chrome JS调试帮助.函数在哪里被调用
- chrome调试器调用堆栈异步选项意味着什么
- 调试谷歌可视化图表——回调被多次调用