如何在非 2xx 状态码下记录 Openresty/nginx 的请求体?

我们正面临一个问题,我们需要记录每个调用的请求体,无论它是成功还是失败。

我能够记录状态码 200 的请求体,但无法记录其他状态码的请求体(使用 Openresty Web 服务器)

log_format detailed_log_format escape=json '$remote_addr - $remote_user [$time_local] '
               '"$request" $status $body_bytes_sent '
               '"$http_referer" "$http_user_agent" "$http_x_forwarded_for" Request : "$request_body" Response : "$response_body"'
               'Auth-header : "$http_auth" User : "$custom"'
               'rt=$request_time urt="$upstream_response_time"';

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.response_body = ngx.ctx.buffered
            end
    ';

access_log  /var/log/nginx/access.log detailed_log_format buffer=1 if=$loggable;

127.0.0.1 - [02/Apr/2021:11:52:51 +0530] "POST /example/api/ HTTP/1.1" 200 675 "https://example.com/test" "Mozilla/5.0 (X11; Linux x86_64) Apple WebKit/537.36 (KHTML, like Gecko) Chrome/xxx Safari/xx" "" Request : "{\"answer\":{\"n\":\"six\"}}" Response : ""Auth-header : "" User : ""rt=0.235 urt="0.236"

4xx 状态码下没有请求体被记录:

127.0.0.1 - - [06/Apr/2021:17:23:04 +0530] "POST /example/api/ HTTP/1.1" 403 0.000 71 "https://example.com/test" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/xxx Safari/xxx" "-"User : "-"

我找不到任何与记录状态代码有关的文档。我怀疑它是否可行,或者是否还有其他用途可以使用 Lua 块或其他任何方法?

点赞