javascriptnode.jsexpressmiddlewaremorgan

Creating logger middleware using morgan


I would like to create a middleware using morgan, i tryed to export the middleware function, then require in app.js. I don't kown why this is not working

Middleware:

    const morgan = require('morgan');
    const rfs = require("rotating-file-stream");

    const rfsStream = rfs.createStream("logs/log.txt", {
        size: '10M', // rotate every 10 MegaBytes written
        interval: '1d', // rotate daily
        compress: 'gzip' // compress rotated files
    })

    function logger(req, res, next){
        morgan('tiny', {
        stream: rfsStream
        })
        next();
    }

    module.exports.logger = logger;

App:

    const express = require('express');
    const app = express();
    const PORT = 4000;
    const { logger } = require('./middlewares/logger');

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

    app.listen(PORT, () => {
        console.log(`app running on port: ${PORT}`);
    });

Solution

  • Morgan itself is a middleware. That means that you should pass it req, res and next.

    HTTP request logger middleware for node.js

    So, try to change your Middleware file like this:

    const morgan = require('morgan');
    const rfs = require("rotating-file-stream");
    
    const rfsStream = rfs.createStream("logs/log.txt", {
        size: '10M', // rotate every 10 MegaBytes written
        interval: '1d', // rotate daily
        compress: 'gzip' // compress rotated files
    })
    
    const logger = morgan('tiny', {
      stream: rfsStream
    })
    
    module.exports.logger = logger;