我如何在node.js中记录每个方法调用而不到处添加调试行

how can I log every method call in node.js without adding debug lines everywhere?

本文关键字:调用 调试 添加 方法 node js 记录      更新时间:2023-09-26

我想记录发出请求的人的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
}