在 Node.js 项目中,压缩旧日志通常是为了节省磁盘空间、方便归档和长期存储。下面按常见场景给你一套实用方案,从简单到规范。
gzip 手动或定时压缩gzip app-2025-01-01.log
生成:
app-2025-01-01.log.gz
✅ 适合临时处理
❌ 不适合自动化
logs/
├── app-2026-01-20.log
├── app-2026-01-19.log
├── app-2026-01-18.log
zlib(Node.js 内置)const fs = require('fs');
const zlib = require('zlib');
const path = require('path');
function compressFile(filePath) {
const gzipPath = filePath + '.gz';
const readStream = fs.createReadStream(filePath);
const writeStream = fs.createWriteStream(gzipPath);
const gzip = zlib.createGzip();
readStream
.pipe(gzip)
.pipe(writeStream)
.on('finish', () => {
fs.unlinkSync(filePath); // 删除原文件
console.log(`压缩完成: ${gzipPath}`);
});
}
示例调用:
compressFile('logs/app-2026-01-18.log');
✅ 无需第三方库
✅ 可控、稳定
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: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d', // 保留 14 天
zippedArchive: true // ✅ 自动 gzip 压缩
});
const logger = winston.createLogger({
transports: [transport]
});
logger.info('这是一条日志');
✅ 自动按天切割 ✅ 自动压缩旧日志 ✅ 生产环境首选
cron + find# 每天凌晨 2 点压缩 7 天前的日志
0 2 * * * find /app/logs -name "*.log" -mtime +7 -exec gzip {} \;
✅ 适合 Docker / 传统服务器
✅ 不依赖 Node.js
或:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
| 场景 | 建议 |
|---|---|
| 开发环境 | 手动 gzip |
| 生产环境 | winston + daily-rotate |
| 高并发 | 日志异步 + 压缩 |
| 长期归档 | 压缩后上传 OSS / S3 |
❌ 压缩正在写入的日志 → 日志损坏
✅ 先切割,再压缩
❌ 保留太多旧日志
✅ 设置 maxFiles 或 mtime
如果你愿意,可以告诉我:
我可以直接给你 可复制的完整配置 ✅