Nginx日志参数
nginx日志主要有两种:访问日志和错误日志。访问日志主要记录客户端访问nginx的每一个请求,格式可以自定义;错误日志主要记录客户端访问nginx出错时的日志,格式不支持自定义。两种日志都可以选择性关闭。
通过访问日志,你可以得到用户地域来源、跳转来源、使用终端、某个URL访问量等相关信息;通过错误日志,你可以得到系统某个服务或server的性能瓶颈等。因此,将日志好好利用,你可以得到很多有价值的信息。
访问日志[Access.log]
log_format main '$remote_addr $remote_user [$time_local] “$request” $http_host ' '$status $upstream_status $body_bytes_sent “$http_referer”' '”$http_user_agent” $ssl_protocol $ssl_cipher $upstream_addr' '$request_time $upstream_response_time';
access_log logs/access.log main; #一定要加上这行,不然不生效
变量名称 | 变量描述 | 举例说明 |
$remote_addr | 客户端地址 | 113.140.15.90 |
$remote_user | 客户端用户名称 | – |
$time_local | 访问时间和时区 | 18/Jul/2012:17:00:01 +0800 |
$request | 请求的URI和HTTP协议 | “GET /pa/img/home/logo-alipay-t.png HTTP/1.1″ |
$http_host | 请求地址,即浏览器中你输入的地址(IP或域名) | img.alipay.com10.253.70.103 |
$status | HTTP请求状态 | 200 |
$upstream_status | upstream状态 | 200 |
$body_bytes_sent | 发送给客户端文件内容大小 | 547 |
$http_referer | 跳转来源 | “https://cashier.alipay.com…/” |
$http_user_agent | 用户终端代理 | “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C; |
$ssl_protocol | SSL协议版本 | TLSv1 |
$ssl_cipher | 交换数据中的算法 | RC4-SHA |
$upstream_addr | 后台upstream的地址,即真正提供服务的主机地址 | 10.228.35.247:80 |
$request_time | 整个请求的总时间 | 0.205 |
$upstream_response_time | 请求过程中,upstream响应时间 | 0.002 |
nginx优化之request_time 和upstream_response_time差别
下面介绍下2者的差别:
1、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 。
指的就是从接受用户请求的第一个字节到发送完响应数据的时间,即包括接收请求数据时间、程序响应时间、输出响应数据时间。
2、upstream_response_time
官网描述:keeps times of responses obtained from upstream servers; times are kept in seconds with a milliseconds resolution. Several response times are separated by commas and colons like addresses in the $upstream_addr
variable
是指从Nginx向后端(php-cgi)建立连接开始到接受完数据然后关闭连接为止的时间。
从上面的描述可以看出,$request_time肯定比$upstream_response_time值大,特别是使用POST方式传递参数时,因为Nginx会把request body缓存住,接受完毕后才会把数据一起发给后端。所以如果用户网络较差,或者传递数据较大时,$request_time会比$upstream_response_time大很多。
所以如果使用nginx的accesslog查看php程序中哪些接口比较慢的话,记得在log_format中加入$upstream_response_time。
##########【注意】
新版本中的time
除了上述的request_time和upstream_response_time比较常用,在新的Nginx版本中对整个请求各个处理阶段的耗时做了近一步的细分:
$upstream_connect_time(1.9.1):
keeps time spent on establishing a connection with the upstream server (1.9.1); the time is kept in seconds with millisecond resolution. In case of SSL, includes time spent on handshake. Times of several connections are separated by commas and colons like addresses in the $upstream_addr variable.
跟后端server建立连接的时间,如果是到后端使用了加密的协议,该时间将包括握手的时间。
$upstream_header_time(1.7.10):
keeps time spent on receiving the response header from the upstream server (1.7.10); the time is kept in seconds with millisecond resolution. Times of several responses are separated by commas and colons like addresses in the $upstream_addr variable.
接收后端server响应头的时间。