Nginx记录响应与POST请求日志
                            
                                
                                Eave
                            
                            
                                
                                2016.08.10
                            
                            
                        
                        生产环境中的某些api出现故障,但是问题无法重现,但是又很想解决掉问题以及我们新项目上线,需要跟踪请求与响应的信息,可以预先找到一些bug,减少大面积的损失。
响应日志需要lua的支持
Linux中可以安装OpenResty
在Nginx的log_format中添加$response_body变量
Nginx虚拟主机配置
server
{
    listen       80;
    server_name  localhost;
    index index.html index.htm index.php;
    charset utf-8;
    access_log  /var/log/nginx/access.log main;
    error_log   /var/log/nginx/error.log debug_http;
    root   /var/www/vhosts/localhost;
    set $response_body "";
    lua_need_request_body on;
    body_filter_by_lua '
        local response_body = ngx.arg[1]
        ngx.ctx.buffered = (ngx.ctx.buffered or "") .. response_body
        if ngx.arg[2] then
            ngx.var.response_body = ngx.ctx.buffered
        end
    ';
}