在Ubuntu上为Node.js应用程序设置日志备份策略可以通过多种方式实现,包括选择合适的日志库、配置日志级别、使用日志轮换工具以及定期清理和归档日志文件。以下是详细的步骤和建议:
合理配置日志级别,以避免记录不必要的信息,影响性能。例如,在生产环境中,通常只记录 error 或 warn 级别的日志,而将 info 或 debug 级别的日志关闭。
使用 cron 或其他定时任务工具定期清理和归档日志文件,以节省磁盘空间并保持日志文件的大小可控。
npm install winston winston-daily-rotate-file
const winston = require('winston');
const dailyRotateFile = require('winston-daily-rotate-file');
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new dailyRotateFile({
      filename: './logs/node.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxsize: '10m',
      daily: true,
    }),
    new winston.transports.File({ filename: './logs/node-error.log', level: 'error' }),
    new winston.transports.File({ filename: './logs/node-combined.log' }),
  ],
});
logger.info('Hello World!');
编辑 /etc/logrotate.d/winston 文件:
/path/to/your/node_modules/winston-daily-rotate-file/winston.conf {
  daily
  rotate 7
  missingok
  notifempty
  compress
  delaycompress
  sharedscripts
  postrotate
    /usr/lib/node_modules/node-rotate /path/to/your/node_modules/winston-daily-rotate-file/winston.conf
  endscript
}
sudo systemctl restart rsyslog
通过上述步骤,你可以在Ubuntu上为Node.js应用程序设置有效的日志备份策略,确保日志文件的有效管理和分析。