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?
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);
}
}
}
@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:
finish
event of res
object, because when req
emit end
event, res
header is not set yet.getHeader
to get
.btw, my reputation is 0, so I can't post comment to the @abeja's answer :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With