linux

Node.js日志轮转配置方法

小樊
38
2025-04-30 14:23:14
栏目: 编程语言

在Node.js应用程序中,日志轮转是一种常见的做法,可以帮助管理日志文件的大小和数量,避免日志文件过大或过多导致磁盘空间不足。以下是几种常见的日志轮转配置方法:

1. 使用 winstonwinston-daily-rotate-file

winston 是一个流行的日志库,结合 winston-daily-rotate-file 可以实现日志的每日轮转。

首先,安装所需的包:

npm install winston winston-daily-rotate-file

然后,配置 winston

const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');

const transport = new DailyRotateFile({
  filename: 'application-%DATE%.log',
  datePattern: 'YYYY-MM-DD-HH',
  zippedArchive: true,
  maxSize: '20m',
  maxFiles: '14d'
});

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    transport
  ]
});

logger.info('Hello, world!');

2. 使用 morganmorgan-body

morgan 是一个HTTP请求日志中间件,结合 morgan-body 可以实现请求日志的轮转。

首先,安装所需的包:

npm install morgan morgan-body

然后,配置 morgan

const express = require('express');
const morgan = require('morgan');
const morganBody = require('morgan-body');
const fs = require('fs');
const path = require('path');

const app = express();

const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });
const errorLogStream = fs.createWriteStream(path.join(__dirname, 'error.log'), { flags: 'a' });

app.use(morgan('combined', { stream: accessLogStream }));
app.use(morganBody());

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

3. 使用 pinopino-rotate

pino 是一个高性能的日志库,结合 pino-rotate 可以实现日志的轮转。

首先,安装所需的包:

npm install pino pino-rotate

然后,配置 pino

const pino = require('pino');
const rotate = require('pino-rotate');

const logger = pino({
  level: 'info',
  transport: {
    target: 'pino-rotate',
    options: {
      period: '1d',
      path: 'application.log',
      maxsize: '10m',
      maxfiles: '7'
    }
  }
});

logger.info('Hello, world!');

4. 使用 logrotate 工具

如果你在Linux系统上运行Node.js应用程序,可以使用 logrotate 工具来管理日志文件。

首先,创建一个 logrotate 配置文件:

sudo nano /etc/logrotate.d/myapp

然后,添加以下内容:

/path/to/your/application.log {
    daily
    missingok
    rotate 14
    compress
    notifempty
    create 640 root adm
}

最后,确保 logrotate 定期运行:

sudo systemctl enable logrotate
sudo systemctl start logrotate

通过以上几种方法,你可以根据具体需求选择合适的日志轮转配置方式。

0
看了该问题的人还看了