温馨提示×

如何定位nginx慢请求日志

小樊
41
2026-09-11 13:22:55
栏目: 编程语言

定位 Nginx 慢请求(响应慢、耗时长的请求)通常从日志配置 + 分析手段两方面入手。下面按实战步骤说明。


一、开启 Nginx 慢请求相关日志

1. 使用 $request_time 记录请求耗时

nginx.confhttpserver 中定义日志格式:

log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status '
                'upstream=$upstream_addr '
                'request_time=$request_time '
                'upstream_time=$upstream_response_time';

关键点:

  • request_time客户端整个请求耗时(含连接、处理、传输)
  • upstream_response_time后端处理耗时(反代场景非常重要)

serverlocation 中使用:

access_log /var/log/nginx/access.log main;

2. 单独记录慢请求日志(推荐)

通过 if + map 实现“只记录慢请求”

map $request_time $is_slow {
    default 0;
    ~^([5-9]\.|[0-9]{2,}) 1;  # 超过 5 秒
}

server {
    access_log /var/log/nginx/slow.log main if=$is_slow;
}

这样只会把慢请求写入 slow.log,便于分析。


二、如何分析慢请求日志

1. 按耗时排序(最常见)

awk '{print $NF}' /var/log/nginx/access.log | sort -nr | head

更实用(假设 request_time 在最后):

awk '{print $request_time, $request}' access.log | sort -nr | head

2. 查看超过 3 秒的请求

awk '$request_time > 3 {print}' access.log

3. 对比请求耗时和后端耗时

如果:

  • request_time 很大
  • upstream_response_time 很小

说明问题在 Nginx 到客户端网络 / 连接 / 带宽

如果反过来:

  • upstream_response_time 很大

说明问题在 后端服务(PHP / Java / Python / DB)


三、常见慢请求原因定位

1. 后端慢

  • 数据库慢查询
  • 接口阻塞
  • 锁等待

✅ 解决:优化后端 / 加缓存 / 限流


2. Nginx 本身慢

  • 大文件下载
  • keepalive 配置不合理
  • worker 数量不足

3. 网络问题

  • 客户端带宽低
  • 跨地域访问
  • TLS 握手慢

四、进阶工具(可选)

  • ngxtop:实时分析 Nginx 日志
ngxtop -l /var/log/nginx/access.log
  • GoAccess:可视化日志
goaccess access.log -o report.html
  • ELK / Grafana Loki:生产环境大规模分析

五、一句话总结

开启 request_time + upstream_response_time 日志 → 拆分慢请求日志 → 对比前后端耗时 → 定位是后端、Nginx 还是网络问题

如果你愿意,我可以帮你写一份完整可直接用的 Nginx 慢请求配置示例

0