温馨提示×

debian nodejs日志怎样轮转

小樊
38
2026-09-01 06:30:13
栏目: 编程语言

在 Debian 上,Node.js 本身不自带日志轮转功能,通常需要借助系统工具来实现日志轮转。常见做法有以下几种:


一、使用 logrotate(最推荐,Debian 自带)

1. 安装(一般已默认安装)

sudo apt update
sudo apt install logrotate

2. 示例:为 Node.js 日志配置 logrotate

假设你的 Node.js 日志在:

/var/log/nodejs/app.log

创建配置文件:

sudo nano /etc/logrotate.d/nodejs

内容示例:

/var/log/nodejs/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    copytruncate
    su root root
}

参数说明

  • daily:每天轮转
  • rotate 14:保留 14 个历史文件
  • compress:压缩旧日志
  • copytruncate不重启 Node.js 直接截断日志(常用)
  • notifempty:空文件不轮转

copytruncate 对 Node.js 非常友好,因为 Node 默认不会重新打开日志文件


二、Node.js 应用层日志轮转(不依赖系统)

1. 使用 winston + winston-daily-rotate-file

npm install winston winston-daily-rotate-file

示例:

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

const transport = new winston.transports.DailyRotateFile({
  filename: '/var/log/nodejs/app-%DATE%.log',
  datePattern: 'YYYY-MM-DD',
  maxFiles: '14d',
  zippedArchive: true
});

const logger = winston.createLogger({
  transports: [transport]
});

✅ 适合容器 / PaaS 环境


2. 使用 pm2 日志管理(如果你用 pm2)

pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 14

三、Systemd 日志(如果你用 systemd 启动)

如果是 systemd 服务:

# /etc/systemd/system/nodeapp.service
StandardOutput=append:/var/log/nodejs/app.log
StandardError=append:/var/log/nodejs/error.log

日志仍由 logrotate 管理即可。


四、推荐方案总结

场景 推荐方式
服务器部署 logrotate + copytruncate
Docker 应用内轮转(winston)
pm2 pm2-logrotate
微服务 集中日志(ELK / Loki)

如果你愿意,我可以:

  • 根据你的 启动方式(systemd / pm2 / docker) 给具体配置
  • 帮你写一个完整的 logrotate 配置
  • 帮你选 Node.js 日志库

你现在的 Node.js 是怎么运行的?

0