在 Linux 下对 JS(Node.js)项目产生的日志 进行备份,常见做法有几种,下面按实用程度给你总结。
如果你的 JS 日志是写文件的(如 app.log),直接用系统自带工具。
which logrotate
sudo vim /etc/logrotate.d/node-app
示例(每天备份、保留 7 天):
/var/log/node-app/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
copytruncate
}
✅ 关键点:
copytruncate:不重启 Node 也能切日志compress:节省空间sudo logrotate -f /etc/logrotate.d/node-app
如果你用 Winston:
const { createLogger, transports } = require('winston');
require('winston-daily-rotate-file');
const transport = new (require('winston-daily-rotate-file'))({
filename: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxFiles: '7d',
zippedArchive: true
});
const logger = createLogger({ transports: [transport] });
✅ 自动:
适合整体拷贝日志
crontab -e
每天凌晨 2 点:
0 2 * * * cp /app/logs/app.log /backup/logs/app-$(date +\%F).log
-v /data/logs:/app/logs
docker logs container_name > log_$(date +%F).txt
rsync -az /var/log/node-app/ user@backup:/backup/node/
或上传 OSS / S3。
| 场景 | 推荐 |
|---|---|
| 服务器长期运行 | ✅ logrotate |
| Node 项目 | ✅ winston-daily-rotate-file |
| 简单脚本 | crontab |
| Docker | 挂载卷 |
如果你愿意,可以把:
发我,我可以给你直接可用的配置。