CentOS Nginx日志轮转策略有哪些
导读:CentOS 下 Nginx 日志轮转策略 一 核心策略与常用参数 周期控制:按时间触发使用 daily/weekly/monthly;按大小触发使用 size 或 minsize(如 minsize 1M 表示达到 1MB 才轮转,常与...
CentOS 下 Nginx 日志轮转策略
一 核心策略与常用参数
- 周期控制:按时间触发使用 daily/weekly/monthly;按大小触发使用 size 或 minsize(如 minsize 1M 表示达到 1MB 才轮转,常与 daily 组合使用)。
- 保留与压缩:用 rotate N 保留最近 N 个归档;用 compress 压缩旧日志,delaycompress 常用于保留最新一份未压缩以便排查。
- 空文件与容错:notifempty 空文件不轮转;missingok 日志缺失不报错。
- 文件创建与权限:用 create mode owner group 在轮转后重建日志文件(如 create 0640 nginx nginx)。
- 触发与通知:用 postrotate … endscript 发送 USR1 信号让 Nginx 重新打开日志文件;sharedscripts 在匹配多个日志时只执行一次脚本。
- 命名风格:dateext 以日期为后缀(如 access.log-20250405),便于按天检索与归档。
以上参数均为 logrotate 的标准指令,适用于 CentOS 上的 Nginx 日志管理。
二 典型策略模板
- 按天轮转并保留 7 天(通用稳定)
/var/log/nginx/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] &
&
kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
- 按天轮转并保留 30 天(更长期留存)
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] &
&
kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
- 按大小触发并保留 7 个归档(避免小文件频繁切割)
/var/log/nginx/*.log {
daily
minsize 1M
rotate 7
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] &
&
kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
- 按日期后缀命名(便于检索与归档)
/var/log/nginx/*.log {
daily
rotate 30
compress
delaycompress
notifempty
create 0640 nginx nginx
dateext
dateformat -%Y%m%d
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] &
&
kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
以上模板覆盖按天、按大小、按保留天数、按日期命名等常见需求,可直接放入 /etc/logrotate.d/nginx 使用。
三 生效机制与验证
- 生效机制:系统通过 /etc/cron.daily/logrotate 每日调用 logrotate,读取 /etc/logrotate.conf 及其包含的 /etc/logrotate.d/ 配置,无需额外定时任务。
- 配置校验:使用 logrotate -d /etc/logrotate.d/nginx 进行干跑校验(不真正切割)。
- 强制执行:使用 logrotate -f /etc/logrotate.d/nginx 立即执行一次轮转,便于验证。
- 状态查看:查看 /var/lib/logrotate/status 了解各日志最近一次轮转时间与状态。
以上步骤可确保策略正确加载、按预期执行并便于问题排查。
四 注意事项与最佳实践
- 权限与属主:确保日志目录与文件对 nginx 用户可写,常见设置为 create 0640 nginx nginx;必要时执行 chown -R nginx:nginx /var/log/nginx。
- 信号通知:轮转后必须让 Nginx 重新打开日志文件,使用 kill -USR1 指向 /var/run/nginx.pid;若 PID 路径不同,请按实际环境调整。
- 压缩策略:生产环境建议启用 compress 与 delaycompress,既节省空间又便于最近一份日志快速排查。
- 命名与归档:启用 dateext 可避免数字后缀回卷,配合 rotate N 实现清晰的保留策略。
- 大流量优化:在 access_log 中使用 buffer=32k flush=5m 降低磁盘 IO(需按业务权衡)。
- 监控与清理:结合 GoAccess 做实时分析;如策略调整或异常,可脚本清理超期压缩日志并写入审计日志。
以上实践有助于提升稳定性、可维护性与可观测性。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: CentOS Nginx日志轮转策略有哪些
本文地址: https://pptw.com/jishu/783401.html
