nginx日志记录服务器响应数据,nginx记录响应与POST请求日志

生产环境中的某些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,无法理解。怎么办呢?看后续文章。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值