Node.js 在 Ubuntu 上的日志优化实践
一 核心优化策略
二 日志轮转与保留
三 系统日志集成与查看
四 集中式日志与可视化
五 落地配置示例
npm i winston winston-daily-rotate-file
const winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: '/var/log/myapp/application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
});
const logger = winston.createLogger({
level: process.env.NODE_ENV === 'production' ? 'error' : 'debug',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: '/var/log/myapp/error.log', level: 'error' }),
transport,
...(process.env.NODE_ENV !== 'production'
? [new winston.transports.Console({ format: winston.format.simple() })]
: []),
],
});
logger.info('应用启动', { service: 'myapp', pid: process.pid });
/var/log/myapp/*.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 0640 myapp myapp
sharedscripts
postrotate
systemctl reload myapp.service >/dev/null 2>&1 || true
endscript
}
sudo logrotate -vf /etc/logrotate.d/myapp
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
pm2 set pm2-logrotate:compress true
pm2 set pm2-logrotate:rotateInterval "0 0 * * *"
pm2 restart all
npm i winston @winston/syslog
const { Syslog } = require('@winston/syslog');
logger.add(new Syslog({ host: 'localhost', facility: 'local0', tag: 'myapp' }));
logger.error('通过 syslog 记录的错误', { meta: 'data' });