CentOS 上 Nginx 日志切割实用技巧
一 推荐做法 Logrotate 系统级方案
/var/log/nginx/*.log {
daily
missingok
rotate 7
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
}
二 备选方案 Shell 脚本 + Cron
#!/bin/bash
LOGS_PATH="$1"
DAYS="$2"
DATE=$(date -d "yesterday" +%Y%m%d)
cd "$LOGS_PATH" || exit 1
[ -f access.log ] && mv access.log access_${DATE}.log
[ -f error.log ] && mv error.log error_${DATE}.log
# 通知 Nginx 重新打开日志
if [ -f /var/run/nginx.pid ]; then
kill -USR1 $(cat /var/run/nginx.pid)
fi
# 清理 N 天前日志(按需调整)
find . -mtime +${DAYS} -name "*.log" -delete
三 Docker 与容器场景
map $time_iso8601 $logdate {
default 'date-not-found';
'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
}
access_log /var/log/nginx/access-$logdate.log main;
- 注意:需确保日志目录对 **nginx** 用户可写,并另行清理历史日志。
四 高级策略与实用参数
/var/log/nginx/*.log {
size 100M
rotate 10
compress
missingok
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
/usr/local/nginx/logs/*.log {
monthly
rotate 24
compress
missingok
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid)
endscript
}
/var/log/nginx/*.log {
hourly
rotate 168 # 保留 7 天
compress
missingok
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
五 验证 排错与运维建议