Logging POST body size using morgan when request is received

Shaurya Mittal picture Shaurya Mittal · Jul 18, 2018 · Viewed 11.9k times · Source

I am using 'morgan' library to log my request, time it takes and the size of response.

But, for a POST request is there a way I can log the POST request and its body size when it is received?

Answer

Abhishek Maheshwari picture Abhishek Maheshwari · Apr 25, 2019
  1. Use custom token formats from Morgan module.
  2. Create a token for body and then just add it to your format.

Here is the working sample code snippet you need to add to your app.js:

morgan.token('body', (req, res) => JSON.stringify(req.body));
app.use(morgan(':method :url :status :response-time ms - :res[content-length] :body - :req[content-length]'));