javascript - Logging requests and responses in express middleware -


i'm trying implement logger in express application. need able log requests , response (status code , body) sent each request. started writing middleware looks this:

function (req, res, next) {     ...     res.on('finish', function () {        logger.debug('for request', req);        logger.debug('response sent');     });     ... } 

i need access data passed res object method used send response. example, if in 1 controller had:

res.json({ foo: 'bar' }) 

i need way { foo: 'bar' } object, maybe:

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);     });     ... } 

is there property or method in express res object use that? or, there better strategy logging requests , responses them?

you need event listener triggered when response.end (or send) methods called. express doesn't have such listener node.js raw api have.

there a finish event in node.js http server instances makes able things after sent response client.

you can integrate existing express server:

response.on('finish', () => {   // logging here. }); 

i recommend save logs in javascript object during request , send them inside of finish event's callback when response has sent.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)