9

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?

Shaurya Mittal
  • 764
  • 1
  • 8
  • 19

4 Answers4

31
  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]'));
Allan Juan
  • 2,048
  • 1
  • 18
  • 42
8

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

Shaurya Mittal
  • 764
  • 1
  • 8
  • 19
3

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);
Vaibhav
  • 1,481
  • 13
  • 17
2

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
    }
Israel kusayev
  • 833
  • 8
  • 20