使用 morgan 创建记录器中间件

Creating logger middleware using morgan

我想使用 morgan 创建一个中间件,我尝试导出中间件功能,然后在 app.js 中要求。我不知道为什么这不起作用

中间件:

    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;

应用程序:

    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}`);
    });

Morgan本身就是一个中间件。这意味着您应该传递 reqresnext.

HTTP request logger middleware for node.js

所以,尝试像这样更改您的 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
})

const logger = morgan('tiny', {
  stream: rfsStream
})

module.exports.logger = logger;