如何解决为什么Morgan Logger服务器中间件不能在单独的文件中工作?
我正在nextjs
应用中跟踪this tutorial,以添加新的中间件进行日志记录,因此我的 server.js 中包含以下代码>:
// create a write stream (in append mode)
const accessLogStream = fs.createWriteStream(path.join(__dirname,'access.log'),{ flags: 'a' })
// setup the logger
server.use(morgan('combined',{ stream: accessLogStream }))
而且工作正常。
但是但是我想将逻辑包含在中间件目录的单独文件中,所以我有:
中间件/logger/index.js
import morgan from "morgan";
import fs from 'fs';
import path from 'path';
export default (req,res,next) => {
var accessLogStream = fs.createWriteStream(path.join(__dirname,{ flags: 'a' })
return morgan('combined',{ stream: accessLogStream });
};
在我的 server.js 中,我将拥有:(在导入和初始化内容之后)
server.use(logger);
server.use(othermiddlewareone);
server.use(othermiddlewaretwo);
其他中间件工作正常,但是这个中断了。你知道为什么吗?
解决方法
我这样更改了中间件,现在可以正常使用了:)
import type { Request,Response,Next } from './types';
import morgan from "morgan";
import fs from 'fs';
import path from 'path';
const accessLogStream = fs.createWriteStream(path.join(__dirname,'server.log'),{ flags: 'a' })
const logger = morgan('combined',{ stream: accessLogStream })
export default async (req: Request,res: Response,next: Next) => {
logger(req,res,function (err) {
return next();
})
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。