温馨提示×

怎样从日志看nginx性能

小樊
40
2026-09-29 19:21:59
栏目: 编程语言

从日志看 Nginx 性能,核心思路是先明确要看哪些日志字段,再结合指标和工具做分析。下面按“日志类型 → 关键指标 → 实操方法”给你一个完整思路。


一、Nginx 有哪些日志可看性能

1. 访问日志(access log)

最常用,记录每一次请求的情况。

默认路径:

/var/log/nginx/access.log

2. 错误日志(error log)

看异常、超时、连接问题。

/var/log/nginx/error.log

3. 状态模块(stub_status)

实时看连接和请求数(不是日志,但非常关键)。


二、access.log 里看性能的 6 个核心指标

1️⃣ 响应时间(最关键)

默认日志没有响应时间,需要自定义 log_format:

log_format main '$remote_addr - $request_time - $upstream_response_time';
  • $request_time:Nginx 处理整个请求的时间
  • $upstream_response_time:后端(PHP/Java)响应时间

怎么看:

  • request_time > 1s:慢
  • upstream_response_time 很大:后端慢
  • request_time 大但 upstream 小:Nginx 或网络问题

2️⃣ 请求量(QPS)

统计单位时间请求数:

wc -l access.log

或按分钟统计:

awk '{print $4}' access.log | cut -c 2-18 | uniq -c

3️⃣ 状态码分布

看异常比例:

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

重点关注:

  • 5xx:后端或 Nginx 错误
  • 499:客户端提前断开(常因太慢)
  • 404:资源问题

4️⃣ 慢请求 Top N

awk '{print $request_time, $7}' access.log | sort -rn | head

或只看成对后端慢的:

awk '$upstream_response_time > 1 {print}' access.log

5️⃣ 大文件 / 大请求

awk '{print $10, $7}' access.log | sort -rn | head

$10 是响应字节数。


6️⃣ 并发来源 IP

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

用于发现:

  • 爬虫
  • 攻击
  • 单点热点

三、error.log 看性能问题

重点看:

  • timeout
  • too many open files
  • worker_connections
  • upstream timed out

示例:

upstream timed out (110: Connection timed out)

说明:后端响应慢或连接池不够。


四、用 stub_status 实时看性能(强烈推荐)

开启

location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

看什么

Active connections: 200
server accepts handled requests
10000 10000 50000
Reading: 10 Writing: 20 Waiting: 170

指标含义:

  • Active:当前连接数
  • Waiting:keep-alive 空闲连接
  • Requests:总请求数(算 QPS)

五、进阶:用工具分析日志

GoAccess(实时可视化)

goaccess access.log -o report.html

ELK / Grafana + Loki

适合生产环境长期分析。


六、一句话总结

Nginx 性能看日志 = 响应时间 + 状态码 + QPS + 错误日志 + 实时连接数

如果你愿意,我可以:

  • 帮你写一套 Nginx 性能日志格式
  • 或根据你的 access.log 样本直接帮你分析慢点在哪里

0 踩