Comprehensive Guide to Morgan Body Middleware for Node.js

Introduction to Morgan Body Middleware

morgan-body is a popular middleware package for Node.js that enhances the logging capabilities of the Express.js framework. It builds upon the morgan package by adding support for logging request and response bodies. This is particularly useful for debugging and monitoring API requests and responses in detail.

Installing Morgan Body

  npm install morgan-body

Basic Usage

To use morgan-body, you first need to set up an Express app and then integrate the middleware.

  
    const express = require('express');
    const morganBody = require('morgan-body');

    const app = express();

    // Middleware to parse JSON bodies
    app.use(express.json());

    // Integrate morgan-body
    morganBody(app);

    // Sample endpoint
    app.post('/user', (req, res) => {
      res.send('User endpoint');
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  

Advanced Configuration

You can customize the logging behavior of morgan-body with various options:

  
    morganBody(app, {
      logReqBody: true, // Log request body
      logResBody: true, // Log response body
      maxBodyLength: 1000, // Maximum length of the body to log
      logIP: true // Log client IP address
    });
  

Logging to a File

You can also direct the logs to a file instead of the console:

  
    const fs = require('fs');
    const path = require('path');
    const rfs = require('rotating-file-stream');

    const logDirectory = path.join(__dirname, 'log');

    // Ensure log directory exists
    fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

    // Create a rotating write stream
    const accessLogStream = rfs.createStream('access.log', {
      interval: '1d', // Rotate daily
      path: logDirectory
    });

    morganBody(app, {
      stream: accessLogStream
    });
  

Example Application

Below is an example application that demonstrates the use of morgan-body for improved logging:

  
    const express = require('express');
    const morganBody = require('morgan-body');
    const fs = require('fs');
    const path = require('path');
    const rfs = require('rotating-file-stream');

    const app = express();
    app.use(express.json());

    const logDirectory = path.join(__dirname, 'log');

    fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

    const accessLogStream = rfs.createStream('access.log', {
      interval: '1d',
      path: logDirectory
    });

    morganBody(app, {
      stream: accessLogStream,
      logReqBody: true,
      logResBody: true,
      maxBodyLength: 1000,
      logIP: true
    });

    app.get('/', (req, res) => {
      res.send('Hello, World!');
    });

    app.post('/echo', (req, res) => {
      res.json(req.body);
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  

By following this guide, you can efficiently log and monitor HTTP requests and responses in your Node.js applications using morgan-body.

Hash: 7986f0d4ba69b3bccb0f47ce6eac9e66924d200f0b7a312cf5a1398bcfb9a22f

Leave a Reply

Your email address will not be published. Required fields are marked *