是否可以将响应数据记录在Nginx访问日志中?


Answers:


11

使用body_filter_by_lua以分配请求主体的nginx的变量,下面是一个例子:

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    log_format log_req_resp '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $body_bytes_sent '
        '"$http_referer" "$http_user_agent" $request_time req_body:"$request_body" resp_body:"$resp_body"';

    server {
        listen 8082;
        access_log logs/access.log log_req_resp;

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

        location / {
            echo "Hello World!";
        }
    }
}

1
在代码中,我们似乎是将响应块中的前1000个字节放入resp_body中,即在这一行中“ resp_body = string.sub(ngx.arg [1],1,1000)”。是否有特定的原因将其设置为
1000。– doon

在我的情况下,它不是给我响应正文,而是给我这样的日志路径,例如“ resp_body:”“ access_log / usr / local / openresty / nginx / logs / access.logupstreamlog”您能建议出什么问题吗?
SMT

3

使用ngx_lua模块

像这样

body_filter_by_lua 'ngx.log(ngx.CRIT,ngx.arg[1])';

在右边 location


1
我想我更喜欢使用ngx.DEBUG。CRIT可能会打印到控制台,通过电子邮件发送给整个系统管理员团队,等等……
Michael Hampton

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.