生产环境中的某些api出现故障,但是问题无法重现,但是又很想解决掉问题以及我们新项目上线,需要跟踪请求与响应的信息,可以预先找到一些bug,减少大面积的损失。
响应日志需要lua的支持,
备注:安装过程中,发现nginx-1.9.0版本与ngx_lua不兼容,所以我换成nginx-1.4.2
nginx日志配置
# vim /usr/local/nginx-1.4.2/conf/nginx.conf
....省略一些配置....
log_format main '$remote_addr | $remote_user | [$time_local] | "$request" | '
'$status | $body_bytes_sent | "$http_referer" | '
'"$http_user_agent" | "$http_x_forwarded_for" | "$request_body" | "$resp_body"';
....省略一些配置....
1
2
3
4
5
6
# vim /usr/local/nginx-1.4.2/conf/nginx.conf
....省略一些配置....
log_format main '$remote_addr | $remote_user | [$time_local] | "$request" | '
'$status | $body_bytes_sent | "$http_referer" | '
'"$http_user_agent" | "$http_x_forwarded_for" | "$request_body" | "$resp_body"';
....省略一些配置....
$request_body变量由nginx自身提供,用于记录POST请求日志
$resp_body变量由我们后面再server中定义,由ngx_lua获取
nginx虚拟主机配置
server {
listen 80;
server_name www.ttlsa.com;
access_log /data/logs/nginx/www.ttlsa.com.access.log main;
index index.html index.php index.html;
root /data/site/www.ttlsa.com/;
set $resp_body ""; // 这个必须放到最外层,否则日志取不到默认值
location /ttlsa/api
{
// 以下配置可以放到server里面,如此一来,整个server的请求都会记录到log中
lua_need_request_body on;
body_filter_by_lua '
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or"") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
';
//省略一些配置
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server{
listen 80;
server_name www.ttlsa.com;
access_log /data/logs/nginx/www.ttlsa.com.access.log main;
indexindex.htmlindex.phpindex.html;
root/data/site/www.ttlsa.com/;
set$resp_body"";// 这个必须放到最外层,否则日志取不到默认值
location/ttlsa/api
{
// 以下配置可以放到server里面,如此一来,整个server的请求都会记录到log中
lua_need_request_bodyon;
body_filter_by_lua'
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or"") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
';
//省略一些配置
}
配置完毕之后,所有/ttlsa/api下的请求都会记录到log中,包含request和response日志
日志结果展示
10.11.11.11 | - | [23/May/2015:11:51:11 +0800] | "POST /ttlsa/api HTTP/1.1" | 200 ~ 519 | "-" | "Apache-HttpClient/4.3.2 (java 1.5)" | "-" | "100022217891232110001WhQD62S7mW06uGZb09JHZx78VN6Z9VO7\xE5\xBE\xAE\xE4\xBF\xA1\xE6\x9D\xA1\xE7\xA0\x81\xE6\x94\xAF\xE4\xBB\x982015052310975548550110874620910192.168.1.1031301450509212754998F7C57A99DBA452EFEF685CBE14BE599" | "100022211000178912321"
以上是某个微信支付项目中的日志,通过根据此日志,可以及早发现问题并且修复。有些人可能有疑问,POST里面的一些内容都是\xE9\x93\xB6\xE8,无法理解。怎么办呢?看后续文章。