nginx log记录请求响应时间

2018.10.22 阿里云对默认nginx log的分析功能详细介绍

有时为了方便分析接口性能等,需要记录请求的时长,通过修改nginx的日志格式可以做到,如

添加一个新的log_format

log_format  timed_combined  '$remote_addr - $remote_user [$time_local] "$request" '

                      '$status $body_bytes_sent "$http_referer" '

                      '"$http_user_agent" "$http_x_forwarded_for" '

                        '$request_time $upstream_response_time';

 然后引用这个新的日志格式

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

几个时间变量的解释

  • $request_time – Full request time, starting when NGINX reads the first byte from the client and ending when NGINX sends the last byte of the response body
  • $upstream_connect_time – Time spent establishing a connection with an upstream server
  • $upstream_header_time – Time between establishing a connection to an upstream server and receiving the first byte of the response header
  • $upstream_response_time – – Time between establishing a connection to an upstream server and receiving the last byte of the response body

如果使用是阿里云,就可以使用他们的日志服务,方便的查询到各执行时间了,如下图:

后记:

2019.9.25 注意,并发请求时,时间有可能会累计,导致对单个请求的时长统计并不准确。

2019.9.26 这个时间跟请求的客户端网速有关系,不是纯的内部处理时长。如果请求客户端网速越慢,时长越大。而且如果你没有使用upstream配置,返回的也是整个请求的处理时长(亦跟客户端网速有关)。

Nginx还支持自定义时间参数的下钻功能,只要在http头上添加相关头字段,并在log_format配置上就可以提取得到了。如在php代码中输出响应头db_read_time,然后在Nginx.conf配置log_format记录此头的值,如

log_format main 'app_db_read_time=$upstream_http_db_read_time '

参考

https://www.nginx.com/blog/using-nginx-logging-for-application-performance-monitoring/#var_upstream_response_time

https://lincolnloop.com/blog/tracking-application-response-time-nginx/

https://www.nginx.com/blog/using-nginx-logging-for-application-performance-monitoring/

转载于:https://my.oschina.net/swingcoder/blog/2177682

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值