在 Ubuntu 上,Node.js 应用本身的日志通常不会自动分割,需要借助外部工具或代码层方案来实现。下面按常见程度给你几种实用方案。
例如使用 winston / pino / 原生 fs 写文件:
// 示例:只写文件,不自己切分
const fs = require('fs');
fs.appendFileSync('/var/log/myapp/app.log', logText);
sudo vim /etc/logrotate.d/myapp
/var/log/myapp/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
copytruncate
}
daily:每天切分rotate 14:保留 14 天compress:压缩旧日志copytruncate:不重启 Node 也能切分(关键)sudo logrotate -f /etc/logrotate.d/myapp
✅ 最稳定、最常用
npm install winston winston-daily-rotate-file
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
dirname: '/var/log/myapp',
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxFiles: '14d',
zippedArchive: true
});
const logger = winston.createLogger({
transports: [transport]
});
✅ 优点:
❌ 缺点:
pm2 install pm2-logrotate
配置示例:
pm2 set pm2-logrotate:rotateInterval '0 0 * * *'
pm2 set pm2-logrotate:retain 14
pm2 set pm2-logrotate:compress true
✅ 适合:
配合 StandardOutput=append:/var/log/myapp/app.log
再使用 logrotate(copytruncate)
| 方案 | 是否推荐 | 适合场景 |
|---|---|---|
| logrotate | ⭐⭐⭐⭐⭐ | 生产环境 |
| winston 分割 | ⭐⭐⭐ | 小项目 |
| PM2 logrotate | ⭐⭐⭐⭐ | PM2 用户 |
| 自己写脚本 | ❌ | 不推荐 |
❌ Node 写日志用 > 重定向
❌ logrotate 没用 copytruncate 导致 Node 继续写旧文件
❌ 多进程同时写日志文件
如果你愿意,可以告诉我:
我可以给你精准配置。