温馨提示×

nginx日志太大怎么处理

小樊
62
2026-09-17 19:18:08
栏目: 编程语言

Nginx 日志太大是常见问题,一般可以从切割、压缩、清理、控制内容、异步写盘几个方向处理。下面按实用程度给你一套方案。


一、最推荐:日志切割(必做)

1️⃣ 使用 logrotate(Linux 自带,最常用)

Nginx 官方推荐方式。

示例配置(/etc/logrotate.d/nginx):

/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
}

说明:

  • daily:每天切
  • rotate 30:保留 30 天
  • compress:压缩旧日志
  • kill -USR1:让 Nginx 重新打开日志(不重启)

测试:

logrotate -d /etc/logrotate.d/nginx   # 模拟
logrotate -f /etc/logrotate.d/nginx   # 强制执行

二、减少日志内容(立竿见影)

2️⃣ 精简 access_log 格式

默认日志太详细,可自定义:

log_format main '$remote_addr - $request_time $status $request';
access_log /var/log/nginx/access.log main;

常见可去掉:

  • $http_user_agent
  • $http_referer
  • $upstream_response_time(非必要)

3️⃣ 不记录静态资源(非常有效)

location ~* \.(jpg|png|css|js|gif|ico)$ {
    access_log off;
}

静态请求通常占日志 70%+


三、关闭不重要的日志

4️⃣ 关闭 health check / 内部请求日志

location /health {
    access_log off;
    return 200;
}

四、控制日志级别

5️⃣ error_log 不要开 debug

error_log /var/log/nginx/error.log warn;

级别(从少到多):

crit < error < warn < notice < info < debug

五、定期清理(兜底)

6️⃣ 定时清理旧日志

find /var/log/nginx -name "*.log.*" -mtime +30 -delete

加进 crontab:

0 3 * * * find /var/log/nginx -name "*.log.*" -mtime +30 -delete

六、高级方案(量大时)

7️⃣ 日志异步 / 远端

  • 用 syslog 输出日志
  • 接 ELK / Loki / SLS
  • 不在本地落盘
access_log syslog:server=127.0.0.1:514 main;

七、极端情况

如果是被刷流量 / 攻击:

  • 限流(limit_req)
  • 封 IP
  • 上 CDN / WAF

推荐组合(通用最佳实践)

✅ logrotate 每天切 + 压缩
✅ 静态资源不记日志
✅ access_log 精简格式
✅ error_log 用 warn


如果你愿意,可以告诉我:

  • 日志路径
  • 单日大小
  • 是否 Docker / K8s
  • Nginx 版本

我可以直接帮你写一份可用配置。

0 踩