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?
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.
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.
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.
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]
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]'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With