sirrodgepodge/morgan-body

Log response body (maybe optional, with a parameter)

Closed this issue · 7 comments

Log response body (maybe optional, with a parameter)

hmm good idea, I seem to remember looking into doing this and finding it difficult, the one way I can think of is wrapping express methods... which might not be the worst thing in the world, will take a look tonight

okay, so a bit late, but tried this snippet out and it will work, but it does mean overwriting an express method, which is dangerous... if we're okay with this should I include some sort of warning at startup time about using this in production you think? Maybe it's obvious, just want to make sure I don't wreck anyone's day:

app.use(function (req, res, next) {
  const originalSend = res.send;
  res.send = responseBeingSent => {
    if (responseBeingSent && !(responseBeingSent instanceof Buffer)) {
      if(typeof responseBeingSent === 'object') {
        let logResponse;
        try {
          logResponse = JSON.stringify(req.body, null, '\t').split('\n').forEach(line => console.log('\x1b[97m' + line + '\x1b[0m')); // needed for multi-line coloring
        } catch(e) {}
        if(logResponse) console.log(logResponse);
      } else if (typeof responseBeingSent === 'string') {
        console.log('\x1b[97m' + responseBeingSent + '\x1b[0m')
      }
    }
    originalSend.call(res, responseBeingSent);
  });
  next();
};

Maybe a safer way to do it would be to handle as part of the after hook.

server.on('after', morganLogger.log({responseBody: true/false, requestBody: true/false}) 

This removes our requirement to use the immediate mode i.e. {immediate: true}, because everyone can just hook it whereever they want in the middleware chain.

So an immediate mode will become

server.use(morganLogger.log({responseBody: false, requestBody: true/false}) 
//responseBody is irrelevant  because there is no response till now

I understand this would create certain change to the existing codebase. I'm happy to help if needed.
What do you think?

this looks great actually, didn't know this was possible, was trying to find documentation for the 'after' event, are you sure that this exists?

okay @mkhanal haha, went ahead and did this, perhaps not in the ideal way (decorating res.send) but it works quite well, see #2 and let me know what you think.

If you're too busy I'll probably just go ahead and merge it in a week or so, I actually really like the experience, thank you again for the suggestion
screen shot 2017-07-07 at 2 02 55 am

This seems to work for what we want. I'm very surprised that we have to go through all this in express. I would have expected express to expose an event for when a response is send.

Why don't you merge it and i'll try to add it to my app. See if the decoration of res.send works without any issues

k, did it and version bumped npm package to 0.10.5, working