Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading