7

Im looking at universal way to audit the express middleware that I have written for some APIs.

I have come up with several ways of doing but none seems that efficient to me. For now I'm only wanting to log to console or a log file but later on I will be looking at a datastore.

  • I can quite easily use a "logging" library such as bunyan in the API routing to do this. But this means Il have to call the logging function everywhere that I want to audit.
  • Use a central function such as given in the snippet to do the logging. This is nice way to log the request/response of the APIs but doesn't help when it comes to auditing the critical information such as auditing a user id from a user registration. Or auditing an email address when a user logs in.

    function auditUserAction(apiFunction) {
    
        function jsonWrapper(funcToWrap, userAction) {
            return function() {
                userAction.jsonResponse = arguments[0];
                return funcToWrap.apply(this, arguments);
            }
        }
    
        return function() {
            req = arguments[0];
            res = arguments[1];
    
            // Overriding json method so we can capture the json response
            res.json = jsonWrapper(res.json, userAction);
            userAction.url = req.url;
            userAction.userId =  req.headers.user_id;
            userAction.referer = req.headers.referer;
            userAction.browserAgent = req.headers['user-agent'];
            result = apiFunction.apply(this, arguments);
            userAction.responseStatusCode = res.statusCode;
            userAction.responseBody = res.body;
            logger.info("Action", userAction);
            return result;
        }
    }
    ..........
    router = require('express').Router();
    router.post('/users', auditUserAction(createUser));
    

Is there a better strategy than this ? Ive searched the web but couldn't find anyway of doing this elegantly.

nixgadget
  • 6,983
  • 16
  • 70
  • 103

0 Answers0