在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'
})
]
});