跳到主要内容

Nginx日志轮转配置指南

· 阅读需 3 分钟

Nginx日志轮转配置指南

注:本文档基于nginx日志目录为 /etc/nginx/logs/ 的环境配置。 如果您的nginx日志在其他目录(如默认的/var/log/nginx/),请相应调整路径。

1. 检查系统环境

首先确认系统已安装logrotate:

# 检查是否安装logrotate
which logrotate

# 如果未安装,使用以下命令安装
# CentOS/RHEL系统
sudo yum install logrotate

# Ubuntu/Debian系统
sudo apt-get install logrotate

2. 创建Nginx日志轮转配置

创建nginx专用的logrotate配置文件:

sudo vim /etc/logrotate.d/nginx

配置文件内容:

/etc/nginx/logs/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}

3. 配置参数说明

  • daily: 每天轮转一次
  • missingok: 如果日志文件丢失,不报错
  • rotate 52: 保留52个轮转文件(约1年)
  • compress: 压缩旧的日志文件
  • delaycompress: 延迟压缩,保留最近的一个文件不压缩
  • notifempty: 如果日志文件为空,不进行轮转
  • create 0640 nginx nginx: 创建新日志文件的权限和所有者
  • sharedscripts: 所有日志文件轮转后只执行一次脚本
  • postrotate: 轮转后执行的脚本,发送USR1信号给nginx重新打开日志文件

4. 测试配置

# 测试配置文件语法
sudo logrotate -d /etc/logrotate.d/nginx

# 强制执行轮转(用于测试)
sudo logrotate -f /etc/logrotate.d/nginx

5. 验证轮转效果

# 查看日志文件
ls -la /etc/nginx/logs/

# 查看轮转后的文件
ls -la /etc/nginx/logs/*.gz

6. 高级配置示例

按大小轮转

/etc/nginx/logs/*.log {
size 100M
missingok
rotate 10
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}

按小时轮转

/etc/nginx/logs/*.log {
hourly
missingok
rotate 168
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}

7. 排查问题

检查logrotate服务状态

# 检查logrotate服务状态
sudo systemctl status logrotate

# 查看logrotate日志
sudo journalctl -u logrotate

检查权限问题

# 确保nginx用户有正确的权限
sudo chown -R nginx:nginx /etc/nginx/logs/
sudo chmod 755 /etc/nginx/logs/

手动测试

# 手动执行logrotate
sudo /usr/sbin/logrotate -v /etc/logrotate.d/nginx

8. 监控脚本

创建一个监控脚本来检查日志轮转状态:

#!/bin/bash
# /usr/local/bin/check_log_rotation.sh

LOG_DIR="/etc/nginx/logs"
MAX_SIZE=100M
ALERT_EMAIL="admin@example.com"

# 检查日志文件大小
for log_file in $LOG_DIR/*.log; do
if [ -f "$log_file" ]; then
size=$(du -h "$log_file" | cut -f1)
if [[ $size > $MAX_SIZE ]]; then
echo "Warning: $log_file size is $size" | mail -s "Log Size Alert" $ALERT_EMAIL
fi
fi
done

# 检查是否有过期的日志文件
find $LOG_DIR -name "*.gz" -mtime +30 -exec rm {} \;

9. 性能优化建议

  1. 合理设置轮转频率:根据日志量调整轮转频率
  2. 使用压缩:节省磁盘空间
  3. 定期清理:删除过期的日志文件
  4. 监控磁盘空间:避免日志文件占满磁盘

10. 注意事项

  • 确保nginx用户有足够权限访问日志目录
  • 在生产环境测试前,先在测试环境验证配置
  • 定期检查轮转是否正常工作
  • 考虑使用日志管理工具如ELK Stack进行集中管理