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

前端 未结 3 761
栀梦
栀梦 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:23

    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
    }
    

提交回复
热议问题