Press "Enter" to skip to content

NGINX作为反向代理时,记录后端接口响应耗时

编辑 /etc/nginx/nginx.conf,在 http 那块配置里面,加上如下代码:

log_format timed_combined '$remote_addr - $remote_user [$time_local]  '
                          '"$request" $status $body_bytes_sent '
                          '"$http_referer" "$http_user_agent"  request_time: $request_time  upstream_response_time: $upstream_response_time';

然后,在具体的 nginx server 配置里的 access_log 后面,加上一句 timed_combined 即可:

access_log /path/to/access.log timed_combined;

|$request_time|
    request processing time in seconds with a milliseconds resolution;
    time elapsed between the first bytes were read from the client and
    the log write after the last bytes were sent to the client

|$request_time指的就是从接受用户请求数据到发送完回复数据的时间。|

http://nginx.org/en/docs/http/ngx_http_upstream_module.html#variables

|$upstream_response_time|
    keeps servers response times in seconds with a milliseconds
    resolution. Several responses are also separated by commas and colons.

|$upstream_response_time说的有点模糊,它指的是从Nginx向后端建立连接开始 
到接受完数据然后关闭连接为 止的时间。||因为会有重试,||它可能有多个时间 
段。一般来说,||$upstream_response_time 会比||$request_time时间短。|

对于HTTP POST的请求,两者相差特别大。因为Nginx会把HTTP request body缓存 
住,接受完毕后才会把数据一起发给后端。

参考资料:

https://nginx.org/en/docs/http/ngx_http_log_module.html#log_format

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注