当前位置: 首页 > linux, 系统 > 正文

nginx 日志中记录http响应头

背景:一个很简单的静态下载站点,每个文件都比较大,一般为30M+,现在想通过日志统计每个文件的下载完整情况。初步计划是在nginx日志中除了将下载的字节数之外,还要将原始文件的大小记录下来。不过如有range的请求情况下,这个值也不是很准确,但是有另外一个规律可寻,详见后面的测试结果。

google了大半天,发现nginx的log_format没有现成的变量将Content-Length记录下来,唯一的几篇抄来抄去的文章说是用$content_length,试过了这个变量是取不到header里面的Content-Length头的,
各种不靠谱,各种坑爹。

后来搜到了淘宝github上的一个文档

sent_http	ngx_http_variable_unknown_header_out

凭空感觉如果nginx内置变量记录到日志中的情况下,变量可以试试添加前缀sent_http,尝试了一下果然可以。

下面是测试情况:

原始文件大小为:43912736

# curl -I http://localhost/sudops.com.testfile.zip
HTTP/1.1 200 OK
Server: Nginx
Date: Wed, 27 Aug 2014 08:39:08 GMT
Content-Type: application/octet-stream
Content-Length: 43912736
Last-Modified: Tue, 19 Aug 2014 02:49:32 GMT
Connection: keep-alive
Xdebug: mytestnginx
Accept-Ranges: bytes

nginx.conf日志格式

    log_format  sudops_logs  '$remote_addr - $remote_user [$time_local] "$request" "$request_body" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for "$content_length" "$http_content_length" "$sent_http_content_length"';

从测试情况来看起作用的是”$sent_http_content_length,
$content_length” “$http_content_length”这两个均取不到值,网上的一些说法都有些误导。

一次性完整下载测试的日志:

10.233.11.107 - - [27/Aug/2014:16:37:56 +0800] "GET /sudops.com.testfile HTTP/1.0" "-" 200 43912736 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "43912736" 

断点续传测试的日志:

10.233.11.107 - - [27/Aug/2014:16:36:25 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 200 2420430 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "43912736"
10.233.11.107 - - [27/Aug/2014:16:36:27 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 206 7203351 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "41531726"
10.233.11.107 - - [27/Aug/2014:16:36:29 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 206 4873191 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "34405755"
10.233.11.107 - - [27/Aug/2014:16:36:31 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 206 9285310 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "29582204"
10.233.11.107 - - [27/Aug/2014:16:36:33 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 206 2345930 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "20364054"
10.233.11.107 - - [27/Aug/2014:16:36:40 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 206 9590450 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "18088204"
10.233.11.107 - - [27/Aug/2014:16:36:42 +0800] "GET /sudops.com.testfile.zip HTTP/1.0" "-" 206 8551774 "-" "Wget/1.11.4 Red Hat modified" - "-" "-" "8551774"

这个结果看上去很有规律,在断点续传情况下,range的作用会导致请求字节数有些叠加,总体来讲206+200的下载字节数之和基本等于初始文件大小。

本文固定链接: https://sudops.com/nginx-log-format-http-header-content-length.html | 运维速度

该日志由 u2 于2014年08月27日发表在 linux, 系统 分类下,
原创文章转载请注明: nginx 日志中记录http响应头 | 运维速度
关键字:

nginx 日志中记录http响应头:目前有2 条留言