1

我正在使用 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 },
));
4

1 回答 1

2

查看morgan 的代码,您会看到它skipstream受支持的。

问题是如何将选项提供给工厂功能:

app.use(requestLogger('combined',
  {
    stream: requestLogStream,
    flags: 'a',
    skip: skipLog
  })
)

它必须是单个对象

于 2020-05-13T07:14:53.980 回答