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?
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]'));
After going through morgan documentation for about an hour I found a good solution to the problem.
Instead of using morgan-body, logging can can be done using the morgan library itself at the time of request. Even the length of the POST body can be logged quite easily.
Here is how it can be done:
app.use(morgan({format: 'POST body length in bytes :req[Content-Length]', immediate: true}))
Here the 'format' option defines the format of log and the 'immediate' option writes the log at the time request is received
You can use morgan-body ,this captures all the request types whether be post or get
import morganBody from 'morgan-body';
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
// must parse body before morganBody as body will be logged
app.use(bodyParser.json());
// hook morganBody to express app
morganBody(app);
You can write your own middleware
app.use((req, res, next) => {
console.log(req.body);
next();
});
You can also check if the request is either POST or PUT etc..
if (req.method === "POST") {
// log the budy
}