Logging requests and responses in express middleware
<p>I'm trying to implement a logger in an <a href="http://expressjs.com" rel="noreferrer">Express</a> application. I need it to be able to log requests and the response (status code and body) sent back for each request. I started writing a middleware that looks like this:</p>

<pre><code>function (req, res, next) {
    ...
    res.on('finish', function () {
       Logger.debug('For request', req);
       Logger.debug('Response sent');
    });
    ...
}
</code></pre>

<p>I need to access the data passed to the <code>res</code> object method used to send the response. For example, if in one controller I had:</p>

<pre><code>res.json({ foo: 'bar' })
</code></pre>

<p>I need a way to get that <code>{ foo: 'bar' }</code> object, something like this maybe:</p>

<pre><code>function (req, res, next) {
    ...
    res.on('finish', function () {
       Logger.debug('For request', req);
       var data = res.data; // or res.body, or whatever
       Logger.debug('Response: ' + res.statusCode, data);
    });
    ...
}
</code></pre>

<p>Is there any property or method in the Express <code>res</code> object that I could use for that? Or, is there a better strategy for logging requests and the responses for them?</p>