我正在使用 NodeJS 和 morgan 进行日志记录和旋转文件流来创建日志文件。我想设置应用程序以创建 apache 组合格式的旋转日志文件。代码正在运行,日志在所需目录中创建。但是,跳过功能不起作用。发送到的请求/api/healthcheck
仍然出现在日志中。我已确认“跳过”网址是正确的,并且在发送对该网址的请求时与 originalUrl 匹配,并且我已确认该函数实际上在调用运行状况检查路由时返回 true。
const logger = require('morgan');
/* Logger */
// Logger skip url
const loggerSkipUrl = '/api/healthcheck';
// Create a rotating write stream
let accessLogStream = rfs.createStream('server.log', {
interval: '1d', // Rotate daily
maxFiles: 30, // Maximum number of rotated files to keep in storage
compress: 'gzip', // Compress rotated files
path: path.join(__dirname, 'logs'),
})
// Log requests in the Apache combined format to one log file per day
app.use(logger('combined',
{ stream: accessLogStream }, // Works but doesn't skip
{ skip: (req, res) => req.originalUrl === loggerSkipUrl }, // Does not skip
{ flags: 'a' },
));
更新:我仍然有这个问题。它似乎与使用流选项有关。例如,不使用 stream 选项进行日志记录,它会正确跳过 healthcheck 路由,但是当使用 stream 选项时,它不会跳过。这是 Morgan 记录器模块中的配置问题还是错误?
function skipLog(req, res) {
const answer = req.originalUrl.indexOf('healthcheck') > -1;
console.log(`skipLog ${answer}`);
return answer;
}
/* SKIP WORKS WITHOUT STREAM OPTION */
// Log API requests to console
app.use(requestLogger('dev', { skip: skipLog }));
/* SKIP DOES NOT WORK WITH STREAM OPTION */
requestLogStream = rfs.createStream('request.log', {
interval: '1d', // Rotate daily
maxFiles: 30, // Maximum number of rotated files to keep in storage
path: path.join(__dirname, `logs/${hostname}`)
});
// Log API requests in the Apache combined format to one log file per day
app.use(requestLogger('combined',
{ stream: requestLogStream },
{ flags: 'a' },
{ skip: skipLog },
));