Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure Sails.js requests/respond time

I would like to see in the console the time it takes for an HTTP request to be responded. Kind of like express.js does.

GET api/myurl/ 210ms 200

I run sails debug but this doesn't show much.
I have node-inspector running but it seems this lets me inspect the JavaScript objects at runtime but not this particular thing.
Is there a configuration in Sails I can enable or a NPM module I can install to find out this time between request and response?

like image 807
Juan Solano Avatar asked Sep 15 '14 23:09

Juan Solano


2 Answers

If you want to measure total response time (including view generation and pushing data to socket) you can use req._startTime defined in startRequestTimer middleware or use response-time middleware which gives much more accurate results.

This middleware adds a X-Response-Time header to all HTTP responses so you can check it both on client and server side.

module.exports.http = {
  middleware: {
    order: [
      'responseTimeLogger',
      // ...
    ],

    // Using built-in variable defined by Sails
    responseTimeLogger: function (req, res, next) {
      req.on("end", function() {
        sails.log.info('response time: ' + new Date() - req._startTime + 'ms');
      });
      next();
    },

    // Using response-time middleware
    responseTimeLogger: function (req, res, next) {
      req.on("end", function() {
        sails.log.info('response time: ' + res.getHeader('X-Response-Time'));
      });
      require('response-time')()(req, res, next);
    }
  }
}
like image 169
abeja Avatar answered Nov 13 '22 08:11

abeja


@abeja's answer is great, but a little out of date. In case of anyone still seek the answer, I put the latest version below:

// Using response-time middleware
responseTimeLogger: function(req, res, next) {
  res.on("finish", function() {
    sails.log.info("Requested :: ", req.method, req.url, res.get('X-Response-Time'));
  });
  require('response-time')()(req, res, next);
}

A little explanation:

  1. Listen to finish event of res object, because when req emit end event, res header is not set yet.
  2. Recent Node.js change the API getHeader to get.

btw, my reputation is 0, so I can't post comment to the @abeja's answer :)

like image 44
Chang Li Avatar answered Nov 13 '22 07:11

Chang Li