在Debian上實現Node.js日志自動化管理,可采用以下方案:
sudo npm install pm2 -gpm2 start app.js --name my-app,默認將日志保存到~/.pm2/logs。ecosystem.config.js配置out_file、error_file及log_rotation參數(如按天輪轉、保留7天)。pm2 logs查看實時日志,pm2 flush清理舊日志。sudo apt-get install logrotate/etc/logrotate.d/下創建配置文件(如nodejs),指定日志路徑、輪轉周期(daily)、保留天數(rotate 7)、壓縮選項等。/path/to/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root adm
}
rsyslog,在Node.js中通過syslog模塊發送日志到系統日志。/etc/rsyslog.conf接收自定義日志并存儲到指定文件。systemd-cat命令將日志直接寫入系統日志,適合與systemd服務集成。winston及winston-daily-rotate-file,配置按日期或大小輪轉日志,支持多傳輸(文件、控制臺等)。const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const logger = winston.createLogger({
transports: [
new DailyRotateFile({
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
})
]
});