如何将整个响应数据保存到 nginx error.log?

Ric*_*ick 2 lua nginx openresty

我想获得所有请求和响应的详细信息,我正在考虑将它们保存到 ngx.log。

我用这样的代码来保存它们,我想从响应体中获取5000个字符的长度,但是在error.log文件中,它只保存了每个响应的一部分响应数据,比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));    
    }
Run Code Online (Sandbox Code Playgroud)

请帮我解释一下,以及如何更改任何配置以保存整个响应数据。或者任何其他更适合保存请求和响应详细信息的建议。 谢谢!

小智 5

那是因为 ngx.arg[1] 只是一个数据块,您必须将字符串长度与缓冲区进行比较,如下所示:

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
Run Code Online (Sandbox Code Playgroud)