centos

CentOS中nginx日志切割的最佳实践

小樊
39
2025-12-07 18:14:20
栏目: 智能运维

CentOS 中 Nginx 日志切割最佳实践

一 推荐方案与标准配置

/var/log/nginx/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0640 nginx nginx
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}

二 验证与运行

sudo logrotate -d /etc/logrotate.d/nginx   # 调试模式,不真正执行
sudo logrotate -vf /etc/logrotate.d/nginx  # 强制执行一次并输出详情
# 每天 23:59 执行自定义配置
sudo crontab -e
59 23 * * * /usr/sbin/logrotate -f /etc/logrotate_mytime/nginx >>/var/log/logrotate-nginx.log 2>&1

三 进阶场景与配置要点

/var/log/nginx/*.log {
    daily
    size 100M
    rotate 30
    compress
    delaycompress
    missingok
    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
    dateext
    dateyesterday
    dateformat -%Y-%m-%d
    compress
    delaycompress
    missingok
    notifempty
    create 0640 nginx nginx
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}

四 常见问题与排查清单

sudo semanage fcontext -a -t var_log_t "/usr/local/nginx/logs(/.*)?"
sudo restorecon -Rv /usr/local/nginx/logs

0
看了该问题的人还看了