温馨提示×

CentOS Nginx日志分析有哪些技巧

小樊
34
2025-12-17 15:55:04
栏目: 智能运维

CentOS 上 Nginx 日志分析实用技巧

一 基础与定位

  • 默认日志路径为:/var/log/nginx/access.log(访问日志)与 /var/log/nginx/error.log(错误日志)。快速查看可用:tail -f、grep、awk 等组合。若路径被自定义,可用 nginx -t 找到配置文件,或用 lsof -p $(pidof nginx | head -n 1) | grep log 反查正在写入的日志文件。Docker 场景直接 docker logs -f <容器名> 更高效。

二 命令行高频分析命令

  • 统计 Top IP:awk ‘{print $1}’ access.log | sort | uniq -c | sort -nr | head
  • Top URL:awk ‘{print $7}’ access.log | sort | uniq -c | sort -nr | head
  • 按小时看流量趋势:以默认 combined 格式为例,提取时间字段第4列并统计
    • awk ‘{print substr($4, 2, 14)}’ access.log | cut -d: -f1-2 | sort | uniq -c | sort -nr
  • 统计状态码分布:awk ‘{print $9}’ access.log | sort | uniq -c | sort -nr
  • 定位 499:统计 499 的 IP 与耗时
    • awk ‘$9 == 499 {print $1}’ access.log | sort | uniq -c | sort -nr
    • awk ‘$9 == 499 {print $1, $7, $request_time, $upstream_response_time}’ access.log
  • 实时观察错误与访问:tail -f error.log;tail -f access.log | grep --color=auto " 499 "
  • 说明:默认 combined 格式下,常用字段位置为:$1=IP$4=时间$7=URL$9=状态码;若启用了耗时字段(如 $request_time$upstream_response_time),可直接用于慢请求定位。

三 关键问题定位方法

  • 499 客户端提前关闭:表示客户端在响应返回前断开,常与前端超时、用户取消、爬虫中断、后端慢有关。排查要点:
    • 用上面的 499 命令找出高频 IP、慢 URL、request_time/upstream_response_time 分布;
    • 结合错误日志:grep -i “499” error.log,若出现 “upstream timed out …” 说明上游慢或不可达;
    • 必要时抓包:tcpdump -i eth0 port 80 -w nginx_traffic.pcap,用 Wireshark 检查是否异常 RST/断开。
  • 504 网关超时:与 499 的差别在于触发方不同,504 由网关/代理侧触发(上游未在超时内返回)。优先检查上游健康、网络与超时配置。
  • 优化建议(按需调整):
    • 合理设置超时:client_header_timeout、client_body_timeout、proxy_connect_timeout、proxy_read_timeout、proxy_send_timeout;
    • 优化后端(SQL/缓存/异步);前端适当延长超时;对异常来源做限流或封禁。

四 日志格式与可观测性增强

  • 使用 JSON 格式便于机器解析与检索:在 http 块中定义
    • log_format json_analytics escape=json ‘{ “msec”:“$msec”,“remote_addr”:“$remote_addr”,“request”:“$request”,“status”:“$status”,“request_time”:“$request_time”,“upstream_response_time”:“$upstream_response_time”,“http_user_agent”:“$http_user_agent”,“http_x_forwarded_for”:“$http_x_forwarded_for” }’;
    • access_log /var/log/nginx/access.log json_analytics;
  • 错误日志级别与用途:error_log 可在 http/server/location 指定,常用级别 warn/error/crit;排查时临时提升到 debug 可获得更细信息(性能影响大,勿长期开启)。
  • 可视化与检索:
    • 使用 GoAccess 实时分析并生成 HTML 报表:goaccess access.log -o report.html --log-format=COMBINED;
    • 将日志接入 ELK/Loki 等平台,做仪表盘、告警与长期留存;
    • 在云日志服务中,可直接做 PV/UV、QPS、状态码分布、响应时间 等分析,例如:
      • 每 5 分钟 PV/UV:SELECT DATE_FORMAT(time - time % 300000, ‘Y-M-d HH:mm’) AS time, APPROX_DISTINCT(remote_addr) AS UV, COUNT(1) AS PV GROUP BY time ORDER BY time
      • QPS(按分钟):SELECT time-time%60000 AS time, COUNT(*)/60 AS qps GROUP BY time ORDER BY time。

五 排错流程与运维建议

  • 三步走:先确认日志路径与生效配置(nginx -t / lsof),再实时复现(tail -f error.log),最后精准过滤(grep/awk 定位 IP、URL、状态码、耗时)。
  • 日志轮转:使用 logrotate 定期切割与压缩,避免单文件过大影响分析效率与磁盘空间。
  • 安全与治理:对高频异常来源做 限流封禁,并优化慢接口与数据库查询,降低 499/5xx 发生率。

0