Record request body and response body in ubuntu 18.04 nginx log

Record request body and response body in ubuntu 18.04 nginx log

Install lua module

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

Set a global format

# /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"'
  '}';

Add configuration in specific domain name configuration file

# /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
    ';

Check the effect

implement

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

When accessing at this time, you will see a log effect similar to this

{"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}",}

Notice

The above adb.comis an example, please switch to a real domain name.

Guess you like

Origin blog.csdn.net/kangear/article/details/117879323