Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a custom log format in express.js using Morgan-body?

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.

like image 431
Victor Ian Avatar asked Dec 17 '22 22:12

Victor Ian


1 Answers

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!

like image 100
Shaurya Mittal Avatar answered Dec 20 '22 16:12

Shaurya Mittal