在Nginx日志中查看响应时间是常见的性能分析需求,以下是详细解析和操作方法:
Nginx默认的main
日志格式通常不包含响应时间,需要自定义日志格式添加$request_time
或$upstream_response_time
变量:
关键变量说明:
$request_time
:客户端请求到Nginx返回响应的总时间(包括接收客户端数据、后端处理、返回响应)$upstream_response_time
:Nginx向后端服务器请求的响应时间(仅适用于反向代理场景)修改nginx.conf:
http {
log_format custom_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log custom_log;
}
配置生效后,日志中会新增时间字段(单位:秒),可通过以下方式分析:
tail -f /var/log/nginx/access.log
示例输出:
192.168.1.1 - - [10/Oct/2023:14:30:00 +0800] "GET /api/data HTTP/1.1" 200 1234 "-" "Mozilla/5.0" 0.056 0.032
$request_time
和$upstream_response_time
# 统计平均响应时间(按请求时间排序)
awk '{sum+=$(NF-1);count++} END {print "Avg:",sum/count,"s"}' access.log
# 找出最慢的10个请求
awk '{print $(NF-1),$7}' access.log | sort -rn | head -10
# 按URL路径统计响应时间
awk '{url[$7]++;time[$7]+=$(NF-1)} END {for(u in url) print u,time[u]/url[u],"s"}' access.log | sort -k2 -rn
bash
goaccess /var/log/nginx/access.log --log-format=CUSTOM --time-format='%H:%M:%S' --date-format='%d/%b/%Y'
时间单位转换:
# 将秒转换为毫秒
awk '{printf "%.2fms\n", $(NF-1)*1000}' access.log
过滤特定请求:
# 只分析API请求
grep "/api/" access.log | awk '{print $(NF-1)}' | sort -n
时间范围分析:
# 分析14:00-15:00的请求
sed -n '/10\/Oct\/2023:14:00:/,/10\/Oct\/2023:15:00:/p' access.log | awk '{sum+=$(NF-1)} END {print sum/NR}'
若发现响应时间异常(如>1s),可检查: 1. 后端应用处理瓶颈(数据库查询、代码逻辑) 2. 网络延迟(特别是跨机房请求) 3. Nginx配置问题(缓冲区设置、keepalive等) 4. 服务器资源(CPU/内存/磁盘IO)
通过持续监控日志中的响应时间,可以快速定位性能问题并优化用户体验。