res
inherits from http.ServerResponse
in the standard library. This means that it is an EventEmitter
with a finish
event. So in your middleware, register for the finish
event and do the logging when that fires:
app.use(function (req, res, next) {
res.on('finish', function() {
logger.info('API request.', {
module: 'core'
data : {
req: {
method: req.method,
url : req.url,
ip : req.ip
},
res: {
status_code: res.statusCode
}
}
});
});
next();
});
You could, of course, register with res.once
, but the finish
event is guaranteed to fire only once, so that shouldn't be necessary unless there's a bug in the standard library.
This won't necessarily occur "after res.send
but before the response leaves the server" as you request - the docs on the finish
event only claim that
[T]his event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network.
So, some of the response may have already left the server. However, I believe it is the closest you'll get without monkey-patching express
, which I would advise against.