2

I want to get all the request and response details, and I'm considering save them to ngx.log.

I use such code to save them, I want to get a length of 5000 chars from the response body, but in the error.log file, it only saved a part of the response data for each response, which is much shorter than 5000.

body_filter_by_lua_block
    {
    local resp_body = string.sub(ngx.arg[1], 1, 5000)
        ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
        if ngx.arg[2] then
            ngx.var.resp_body = ngx.ctx.buffered
        end
    }
log_by_lua_block{
        local data = {response={}, request={}}

        local req = ngx.req.get_headers()
        req.accessTime = os.date("%Y-%m-%d %H:%M:%S")
        data.request = req

        local resp = data.response
        resp.headers = ngx.resp.get_headers()
        resp.status = ngx.status
        resp.duration = ngx.var.upstream_response_time
        resp.body = ngx.var.resp_body

        ngx.log(ngx.NOTICE,"from log pharse:", json.encode(data));    
    }

Please help me to explain it, and How to change any configurations to save the whole response data. Or any other suggestions which are more proper to save the request and response details. Thanks!

Rick
  • 141
  • 2
  • 15

2 Answers2

5

that is because ngx.arg[1] is only a chunk of data, you have to compare the string length with the buffer, something like this:

ngx.ctx.buffered = (ngx.ctx.buffered or "") .. ngx.arg[1]
if ngx.arg[2] then
    ngx.var.resp_body = string.sub(ngx.ctx.buffered, 1, 5000)
end
lucsbelt
  • 453
  • 2
  • 9
0
#client_body_buffer_size 5000;
  body_filter_by_lua_block{
        local resp_body = string.sub(ngx.arg[1], 1, 5000)
        ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
        if ngx.arg[2] then
            ngx.log(ngx.INFO, ngx.ctx.buffered)
        end
  }

i have changed some, i use above to log the response in the nginx(openresty) log

user3073309
  • 184
  • 2
  • 5