Nginx日志参数

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
$statusHTTP请求状态200
$upstream_statusupstream状态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_protocolSSL协议版本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响应头的时间。