在 Debian 上 Node.js 日志太多,一般可以从 日志来源、日志级别、存储方式、轮转策略 四个方面来解决。下面按常见场景给你一套实用方案。
console.log / console.errorsystemd(journalctl)pm2docker/var/log/nginx/du -sh /var/log/*
journalctl --disk-usage
journalctl --vacuum-size=100M
或按时间:
journalctl --vacuum-time=7d
生产环境不要 debug / info 全开
const logLevel = process.env.NODE_ENV === 'production'
? 'warn'
: 'debug';
const winston = require('winston');
const logger = winston.createLogger({
level: 'warn', // 只记录 warn 以上
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
✅ 避免 console.log 满天飞
winston-daily-rotate-filenpm install winston-daily-rotate-file
const DailyRotateFile = require('winston-daily-rotate-file');
new DailyRotateFile({
dirname: '/var/log/myapp',
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d'
})
✅ 自动删除 14 天前的日志
sudo nano /etc/logrotate.d/nodeapp
/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
copytruncate
}
测试:
logrotate -d /etc/logrotate.d/nodeapp
pm2 logs # 查看
pm2 flush # 清空
限制日志大小:
pm2 start app.js --max-memory-restart 500M --log /var/log/myapp/pm2.log
或:
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
StandardOutput=append:/var/log/myapp/out.log
StandardError=append:/var/log/myapp/err.log
配合 logrotate 使用。
process.on('uncaughtException', err => {
logger.error(err);
});
process.on('unhandledRejection', err => {
logger.error(err);
});
否则 Node.js 会疯狂打错误日志。
✅ Node.js + Winston + 日志轮转 + 只记录 warn/error
- 不用 console.log
- 不记录 debug
- 日志按天切割
- 自动删除旧日志
你可以直接贴: