I am using morgan-body to log HTTP requests and responses in my node.js/express application. Log entries created by this middleware consist of the full request and response HTTP headers, which is too verbose for my needs.
This is my morgan-body snippet:
const express = require('express');
const app = express();
const parser = require('body-parser');
const morganBody = require('morgan-body');
// snipped configuration for other middleware
app.use(parser.json());
app.use(parser.urlencoded({ extended: false }));
morganBody(app, {
noColors: true,
maxBodyLength: 65535,
stream: this.responseStream
});
As the existing log entry is too verbose I need to create a custom format for them, i.e.,
timestamp: fruit-name: info: status: Pass message: no damage
The fields "status" and "message" are in the response.body.
I've googled for a solution to this but I'm stuck. Is there a way for morgan-body to compose a custom message? If there is an alternative middleware that can achieve what I needed it would be welcome.
Instead of using morgan-body, this can be easily achieved using morgan library.
You can do it by creating custom tokes.
Here is a possible solution:
const express = require('express');
const app = express();
const morgan = require('morgan');
morgan.token('status', function (req, res) { return res.body.status })
morgan.token('message', function (req, res) { return res.body.message })
morgan.token('fruit-name', function (req, res) { return res.body.fruit-name })
morgan.token('timestamp', function (req, res) { return res.body.timestamp })
app.use(morgan('Timestamp\: :timestamp fruit-name\: :fruit-name Status\: :status Message\: :message'))
This should create a custom string for you log!
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