2

I'm trying to log every request made to my sails application, but I can't find a way to log the response associated with a request.

I added this custom middleware in the config/http.js file :

myRequestLogger: function (req, res, next) {
  req.on("end", function(){
    sails.log(res.statusCode);
  });
  return next();
}

But it doesn't work properly, I can get the 200 codes, buta res.forbidden or res.notFound response is not logged. Any idea about how I could handle that ?

Thank you

adc06
  • 793
  • 8
  • 23
  • I used your exact example and was able to log 403 and 404 errors. Please show your entire config/http.js file? – JohnGalt Sep 08 '15 at 18:05

2 Answers2

1

You can override that in api/responses itself. Here is simplified override:

// api/responses/forbidden.js
module.exports = function(err, viewOrRedirect) {
  // ... Sails logic
  this.req._sails.log.verbose();
}

But, if you expect that your middleware above can do this, you're wrong. Your middleware should looks similar to this:

myRequestLogger: function(req, res, next) {
  req._sails.log.verbose('YOUR LOG');
  return next();
}
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34
  • My problem is no to log something but to log the response object before it is send to the client... I although did a typo in my code above so I will edit it. Thanks! – adc06 Sep 08 '15 at 16:53
  • Then try to override responses in `api/responses` as I described above. – Eugene Obrezkov Sep 08 '15 at 18:17
1

Ok, I have found the answer by reading this stackoverflow post : https://stackoverflow.com/a/11841877/2700309

Apparently there is a 'finish' event emitted just before the response is send to the client. So the right code would be :

myRequestLogger: function (req, res, next) {
  res.on("finish", function(){
  sails.log(res.statusCode);
 });
 return next();
}

And this seems to work!

Community
  • 1
  • 1
adc06
  • 793
  • 8
  • 23