温馨提示×

nginx日志过大怎么处理

小樊
49
2026-09-02 14:07:08
栏目: 编程语言

Nginx 日志过大是生产环境中很常见的问题,通常可以从 日志切割、日志级别控制、访问日志优化、磁盘与监控、必要时关闭或转发 这几个方面来处理。


一、日志切割(最常用、必须做)

1. 使用 logrotate(推荐)

Nginx 官方和大多数系统都依赖 logrotate

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

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

说明:

  • daily:每天切割
  • rotate 14:保留 14 天
  • compress:压缩旧日志
  • kill -USR1:让 Nginx 重新打开日志文件

测试:

logrotate -d /etc/logrotate.d/nginx   # 调试
logrotate -f /etc/logrotate.d/nginx   # 强制执行

2. 手动切割(不推荐长期使用)

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

二、降低日志量(从根本上减少)

1. 调整日志级别

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

级别从低到高:

debug < info < notice < warn < error < crit

2. 精简 access_log 格式

默认格式可能记录过多字段:

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

3. 关闭不必要日志

静态资源可不记录:

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

4. 条件记录日志

只记录非正常请求:

map $status $loggable {
    ~^[23]  0;
    default 1;
}

access_log /var/log/nginx/access.log combined if=$loggable;

三、日志存储与清理策略

  • 单独挂载日志盘
  • 设置磁盘告警(>80%)
  • 定期清理历史日志
  • 使用 find 清理:
find /var/log/nginx -name "*.log.*" -mtime +14 -delete

四、日志集中化(进阶)

适合多台服务器:

  • ELK / EFK
  • Loki + Promtail
  • rsyslog / fluentd

好处:

  • 不占用本地磁盘
  • 方便检索和分析

五、极端情况

临时关闭访问日志

access_log off;

⚠️ 仅限排查或特殊场景


六、推荐方案组合(实际生产)

✅ logrotate 每天切割 + 压缩
✅ error_log 设为 warn
✅ 静态资源不记录 access_log
✅ 监控磁盘使用率


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

  • 日志路径和大小
  • Nginx 版本
  • 是否容器 / K8s
  • 是 access 还是 error 日志过大

我可以给你一套 可以直接用的配置。

0 踩