ubuntu 18.04 nginx日志中记录请求体和响应体

ubuntu 18.04 nginx日志中记录请求体和响应体

安装lua模块

sudo apt-get install nginx-plus-module-lua

设置一个全局格式

# /etc/nginx/nginx.conf
log_format json_combined escape=json
  '{'
    '"t":"$time_local",'
    '"remote_addr":"$remote_addr",'
   # '"remote_user":"$remote_user",'
   '"request":"$request",'
   # '"status": "$status",'
   # '"body_bytes_sent":"$body_bytes_sent",'
    '"req_body":"$request_body",'
    '"req_time":"$request_time",'
    '"resp_body":"$resp_body",'
   # '"http_user_agent":"$http_user_agent"'
  '}';

在具体的域名配置文件中添加配置

# /etc/nginx/sites-enabled/xxx.abc.com 
   access_log  /var/log/nginx/xxx.abc.com.log json_combined;
   lua_need_request_body on;
    set $resp_body "";
    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
    ';

查看效果

执行

nginx -s reload
tail -f /var/log/nginx/xxx.abc.com.log

这时进行访问会看到类似这样的日志效果

{"t":"17/Apr/2020:14:10:01 +0800","remote_addr":"xxxxxx","request":"POST /v1/xxx HTTP/1.1","req_body":"","req_time":"0.000","resp_body":"{\"code\": 0}",}

注意

上述adb.com为例子,请切换成真实域名。

猜你喜欢

转载自blog.csdn.net/kangear/article/details/117879323