在 Node.js 中,日志按天切割(日志轮转)常见有几种成熟方案,推荐优先使用现成库,而不是自己手动写文件重命名逻辑。
winston + winston-daily-rotate-file(最常用)npm install winston winston-daily-rotate-file
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
dirname: 'logs',
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m', // 单个文件最大
maxFiles: '14d', // 保留 14 天
zippedArchive: true // 是否压缩旧日志
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
transport,
new winston.transports.Console()
]
});
logger.info('hello world');
logs/
├── app-2026-01-20.log
├── app-2026-01-21.log
✅ 优点
pino + pino-roll(高性能)适合高并发、IO 敏感场景。
npm install pino pino-roll
const pino = require('pino');
const roll = require('pino-roll');
const stream = roll({
file: 'logs/app.log',
frequency: 'daily',
size: '10m',
mkdir: true
});
const logger = pino({
level: 'info'
}, stream);
logger.info('hello pino');
✅ 优点
如果你用 PM2 管理 Node 进程:
pm2 install pm2-logrotate
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
✅ 优点
pm2 logs// 不推荐
fs.renameSync('app.log', `app-${today}.log`);
❌ 问题:
| 场景 | 推荐方案 |
|---|---|
| 通用 Node 项目 | winston + daily-rotate-file |
| 高性能 / 微服务 | pino + pino-roll |
| 服务器部署 | PM2 + pm2-logrotate |
| 简单脚本 | pino |
如果你告诉我:
我可以帮你直接给出最合适的配置方案。