在 Ubuntu 上,Node.js 的日志压缩通常不是 Node.js 自身完成的,而是由系统日志管理工具或定时任务来处理。下面按常见场景给你几种实用方案。
logrotate(最推荐,Ubuntu 自带)which logrotate
如果没有:
sudo apt update
sudo apt install logrotate
假设日志目录:
/var/log/nodejs/app.log
新建配置文件:
sudo nano /etc/logrotate.d/nodejs
示例内容:
/var/log/nodejs/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
copytruncate
}
daily:每天轮转rotate 14:保留 14 天compress:使用 gzip 压缩copytruncate:不重启 Node.js 直接截断日志(非常重要)sudo logrotate -d /etc/logrotate.d/nodejs # 模拟
sudo logrotate -f /etc/logrotate.d/nodejs # 强制执行
winston + winston-daily-rotate-filenpm install winston winston-daily-rotate-file
示例:
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: '/var/log/nodejs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true, // 自动 gzip
maxFiles: '14d'
});
const logger = winston.createLogger({
transports: [transport]
});
✅ 优点:
.gz)如果你用 PM2 启动 Node.js:
~/.pm2/logs/
sudo nano /etc/logrotate.d/pm2
/home/*/.pm2/logs/*.log {
daily
rotate 7
compress
delaycompress
notifempty
copytruncate
}
gzip /var/log/nodejs/app.log
⚠️ 注意:
| 场景 | 推荐方式 |
|---|---|
| 生产环境 | ✅ logrotate |
| Node.js 项目 | ✅ winston-daily-rotate-file |
| PM2 | ✅ logrotate + PM2 |
| 临时处理 | gzip(不推荐) |
如果你愿意,可以告诉我:
我可以帮你写一份完全适配你环境的配置。