0

您好,这是我的问题,最近,我在 2021/10/01 部署了一个服务器,用于保存访问日志。我正在使用morgan库来执行此操作,并使用旋转文件流进行文件轮换。然而,经过几天的活动,我意识到旋转没有正确完成。

这是我的代码:

const morgan = require('morgan');
const rfs = require('rotating-file-stream');
const path = require('path');
const { format } = require('date-fns');

function logFilename() {
  return `${format(new Date(), 'yyyy-MM-dd')}-access.log`;
}

const accessLogStream = rfs.createStream(logFilename, {
  interval: '1d', // rotate daily
  path: path.resolve(__dirname, '..', 'log'),
});

morgan.token('ip', (req) => req.headers['x-forwarded-for'] || req.connection.remoteAddress);

morgan.token('user', (req) => {
  if (req.user) return req.user;
  return '-';
});

module.exports = morgan(':ip ":user" [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"', { stream: accessLogStream });

以下是我可以在我的日志文件中找到的示例(它是您必须查看的日期级别)。

2021-10-03-access.log

:ip ":user" [01/Oct/2021:07:30:52 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
...
...
:ip ":user" [02/Oct/2021:23:56:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"

2021-10-04-access.log

:ip ":user" [03/Oct/2021:00:01:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
...
...
:ip ":user" [03/Oct/2021:23:56:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"

2021-10-05-access.log

:ip ":user" [04/Oct/2021:00:01:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
...
...
:ip ":user" [05/Oct/2021:06:03:02 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"

我在旋转文件流文档中看到如果我们将“1d”放在间隔参数中,那将在每个午夜旋转,但也许我忘记了一些东西。

提前感谢您的关注和未来的答案。

4

1 回答 1

0

我忘记了文件名生成器的一个条件和一个参数

function logFilename(time) {
  if (!time) return 'access.log';
  return `${format(time, 'yyyy-MM-dd')}-access.log`;
}
于 2021-11-16T12:15:15.540 回答