温馨提示×

怎样切割debian nginx日志

小樊
45
2026-09-28 11:35:57
栏目: 智能运维

在 Debian 上“切割” Nginx 日志,通常有三种常见做法:


一、使用系统自带 logrotate(推荐)

Debian 默认已安装 logrotate,并且 Nginx 包一般已经带了配置文件。

1. 查看已有配置

cat /etc/logrotate.d/nginx

典型内容类似:

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

2. 手动测试切割

logrotate -d /etc/logrotate.d/nginx   # 调试模式(不真正执行)
logrotate -f /etc/logrotate.d/nginx  # 强制执行

3. 常用参数说明

  • daily / weekly / monthly:切割周期
  • rotate N:保留 N 个旧日志
  • compress:压缩旧日志
  • notifempty:空日志不切
  • postrotate:重新打开日志(nginx 必须)

二、使用 Nginx 自带日志轮转(手动)

Nginx 不支持自动切割,但可以通过信号重新打开日志:

mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +%Y%m%d)
kill -USR1 $(cat /var/run/nginx.pid)

可写入 crontab:

0 0 * * * mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +\%Y\%m\%d) && kill -USR1 $(cat /var/run/nginx.pid)

三、按虚拟主机分别切割(多站点)

在 logrotate.d/nginx 中可使用通配:

/var/log/nginx/*/*.log {
    daily
    rotate 30
    compress
    missingok
    notifempty
    sharedscripts
    postrotate
        kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

四、常见注意事项

  1. 必须重新打开日志
    • 不发送 USR1 信号,Nginx 仍写旧文件
  2. 权限问题
    • 日志属主通常是 www-data:adm
  3. systemd 环境
    • 也可用:
      systemctl kill -s USR1 nginx
      

推荐方案总结

✅ 生产环境:logrotate(默认、稳定、自动)
⚠️ 特殊需求:脚本 + cron
❌ 不推荐:手动 rm 日志

如果你愿意,我可以帮你:

  • 写一份 自定义 logrotate 配置
  • 按 日期 + 大小 切割
  • 配置 远程日志 / 清理策略

0 踩