温馨提示×

nginx日志太多怎么分析

小樊
42
2026-10-02 16:19:03
栏目: 编程语言

Nginx 日志量大时,不要直接 cat 或 vim 硬看,而是按“定位问题 → 聚合统计 → 深入排查”的思路来分析。下面给你一套实用方法,从简单到进阶。


一、先看日志格式(很重要)

先确认你用的是哪种日志格式(默认是 combined):

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

常见字段含义:

  • $remote_addr:客户端 IP
  • $request:请求方法和 URL
  • $status:HTTP 状态码
  • $body_bytes_sent:响应大小
  • $http_user_agent:客户端类型

二、最常用:命令行快速分析(不用工具)

1️⃣ 统计访问最多的 IP

awk '{print $1}' access.log | sort | uniq -c | sort -nr | head

2️⃣ 统计最频繁的请求 URL

awk '{print $7}' access.log | sort | uniq -c | sort -nr | head

3️⃣ 统计 HTTP 状态码分布

awk '{print $9}' access.log | sort | uniq -c | sort -nr

常见异常:

  • 大量 404 → 爬虫 / 路径错误
  • 大量 500 → 后端程序问题
  • 大量 499 → 客户端主动断开(常见于超时)

三、按时间分析(找高峰)

按小时统计请求量

awk '{print $4}' access.log | cut -d: -f1-2 | sort | uniq -c

输出示例:

 1200 [10/Oct/2024:10
 3400 [10/Oct/2024:11

四、定位问题请求(实战场景)

1️⃣ 查看 500 错误请求

awk '$9 == 500 {print}' access.log

2️⃣ 查看某个 IP 的所有请求

grep '1.2.3.4' access.log

3️⃣ 查看慢请求(需要 $request_time)

如果你日志里有:

$request_time

统计最慢的 10 个请求:

awk '{print $NF, $0}' access.log | sort -nr | head

五、日志太多?先“瘦身”

1️⃣ 按日期切割日志(非常关键)

用 logrotate:

/etc/logrotate.d/nginx

示例:

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

六、进阶方案(日志量超大时)

✅ 方案 1:ELK / EFK

  • Filebeat 收集
  • Elasticsearch 存储
  • Kibana 可视化

适合:

  • 日请求量 > 千万
  • 多台 Nginx
  • 需要图表和告警

✅ 方案 2:GoAccess(轻量级实时分析)

goaccess access.log -o report.html --log-format=COMBINED

特点:

  • 实时
  • 网页报表
  • 不需要数据库

✅ 方案 3:只记录关键日志

减少日志量:

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

map $status $loggable {
    default 1;
    404     0;
}

或只记录错误:

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

七、实用排查套路(推荐)

  1. 先按状态码统计
  2. 再按 IP 排名
  3. 定位异常时间窗口
  4. 抽几条原始日志看细节
  5. 必要时上可视化工具

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

  • 日志大概多大(GB / 天)
  • 是排查 攻击 / 性能 / 报错 哪一类
  • 是否多台服务器

我可以直接给你定制化分析命令或架构建议。

0 踩