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

前端 未结 3 693
栀梦
栀梦 2021-02-08 03:00

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 -          


        
3条回答
  •  无人及你
    2021-02-08 03:22

    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.call arguments, 1
        Function::call = newCall
        this.apply self, args
      Function::call = newCall
    

提交回复
热议问题