在Express中避免重复记录日志的一种解决方法是使用中间件来处理日志记录,以确保只有一次记录。
以下是一个示例代码:
const express = require('express');
const morgan = require('morgan');
const app = express();
// 创建一个只记录一次日志的标志
let isLoggingEnabled = true;
// 自定义中间件,用来记录日志
const customLogger = (req, res, next) => {
if (isLoggingEnabled) {
// 执行日志记录操作
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
// 将标志设置为false,以避免重复记录
isLoggingEnabled = false;
}
next();
}
// 使用Morgan中间件来记录其他日志
app.use(morgan('combined'));
// 使用自定义中间件来记录日志
app.use(customLogger);
// 路由处理程序
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
在上面的示例中,我们使用了morgan
库来记录其他的日志,例如请求方法、URL、响应状态码等。然而,我们希望只有自定义的中间件在每个请求中记录一次日志。
我们创建了一个名为customLogger
的自定义中间件,它在每个请求中只记录一次日志。它利用了一个标志isLoggingEnabled
,初始值为true
,以确保第一次请求时记录日志。然后,它将标志设置为false
,以避免后续请求再次记录日志。
最后,我们将customLogger
中间件放在所有其他中间件之前,以确保它是第一个执行的中间件,从而实现只记录一次日志的效果。