问题描述
我想记录发出请求的人的 user_id 以及为 javascript 类调用的每个方法的方法名称.例如:
I would like to log the user_id of the person making a request and the method name of every method called for a javascript class. For example:
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 并且一次只能看到一个用户的活动.
Since everything is async user 35 and 78 might be doing stuff at the same time. So I want to make sure each log line starts with their user_id so I can grep for it and only see one user's activity at a time.
有没有一种超级聪明的方法可以在不向每个方法添加记录器语句的情况下做到这一点?
Is there a super clever way to do this without adding logger statements to every method?
推荐答案
我猜这是一个网络应用程序,在这种情况下,如果您使用连接,您可以使用记录用户和 URL 路径的记录器中间件,这可能就足够了.否则,您将不得不按照将每个函数包装在包装函数中的方式进行一些元编程以进行日志记录.
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.
function logCall(realFunc, instance) {
return function() {
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.
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
}
这篇关于如何在 node.js 中记录每个方法调用而不在任何地方添加调试行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!