Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging POST body size using morgan when request is received

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?

like image 510
Shaurya Mittal Avatar asked Jul 18 '18 19:07

Shaurya Mittal


People also ask

What does Morgan (' Tiny ') do?

The preset tiny provides the minimal output when logging HTTP requests. Including the preset tiny as an argument to morgan() will use its built-in method, identify the URL, declare a status, and the request's response time in milliseconds.

What is Morgan logger used for?

Morgan is a middleware for node. js that logs HTTP requests and is commonly used in Express projects. Express is a node. js routing and middleware web framework that is quick, unprejudiced, and simple.

How do I create a log file with Morgan?

write logs to a file var express = require('express') var fs = require('fs') var morgan = require('morgan') var path = require('path') var app = express() // create a write stream (in append mode) var accessLogStream = fs. createWriteStream(path. join(__dirname, 'access. log'), { flags: 'a' }) // setup the logger app.

What is logger Express?

It provides the ability to log incoming requests by specifying the formatting of log instance based on different request related information. For example: :method :url :status :response-time ms - :res[content-length]


1 Answers

  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]'));
like image 177
Abhishek Maheshwari Avatar answered Oct 06 '22 07:10

Abhishek Maheshwari