压缩 Node.js 的历史日志,通常取决于日志的存储方式、大小和后续需求。下面从常见场景 → 具体做法 → 自动化建议给你一个完整方案。
例如:
logs/
├── app-2024-01-01.log
├── app-2024-01-02.log
├── app-2024-01-03.log
pino-roll / gzipgzip(最通用)gzip logs/app-2024-01-01.log
结果:
app-2024-01-01.log.gz
✅ 优点:
.gzfind logs/ -name "*.log" -mtime +7 -exec gzip {} \;
解释:
-mtime +7:7 天前的日志zlib(Node 内置)const fs = require('fs');
const zlib = require('zlib');
fs.createReadStream('logs/app.log')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('logs/app.log.gz'));
✅ 适合:
import pino from 'pino';
import { createGzip } from 'zlib';
const logger = pino(
{},
createGzip({ level: 9 })
);
或者使用 pino-roll:
import pino from 'pino';
import pinoRoll from 'pino-roll';
const stream = pinoRoll({
file: 'logs/app.log',
frequency: 'daily',
compress: 'gzip'
});
const logger = pino({}, stream);
✅ 自动:
Winston 本身不压缩,需要配合:
npm install winston-daily-rotate-file
import { createLogger, transports } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
const transport = new DailyRotateFile({
filename: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d',
zippedArchive: true // ✅ 自动 gzip
});
const logger = createLogger({
transports: [transport]
});
✅ 最省心方案之一
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "5"
}
}
cd /var/lib/docker/containers
gzip *.log
⚠️ 需要停止容器或确认日志已轮转
cron + find0 2 * * * find /app/logs -name "*.log" -mtime +7 -exec gzip {} \;
logrotate(强烈推荐)/var/log/node/app.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
}
✅ 最专业、最稳定
| 方式 | 压缩率 | 性能 | 推荐度 |
|---|---|---|---|
| gzip | ⭐⭐⭐ | ⭐⭐⭐ | ✅✅✅ |
| zstd | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ✅✅ |
| 不压缩 | - | ⭐⭐⭐⭐⭐ | ❌ |
✅ 新项目
pino-roll + gzip✅ 已有 Winston
winston-daily-rotate-file + zippedArchive✅ 纯文件日志
find + gzip 或 logrotate✅ Docker
如果你愿意,可以告诉我:
我可以给你一个完全定制的压缩方案。