zoukankan      html  css  js  c++  java
  • 如何优雅打印nginx header和body

    场景

    参考https://segmentfault.com/a/1190000000606867可以获取response的报文体,由于业务测试有获取响应头Header或响应体Body的需求,这里是通过header_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" resp_header:"$resp_header"';
    
        server {
            listen 8082;
            access_log logs/access.log log_req_resp;
    
            set $resp_header "";
            header_filter_by_lua '
                local h = ngx.resp.get_headers()
                for k, v in pairs(h) do
                ngx.var.resp_header=ngx.var.resp_header..k..": "..v
                end
            ';
    
            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!";
            }
        }
    }

    然后access日志里就有啦~

  • 相关阅读:
    第7次实践作业 25组
    第6次实践作业 25组
    第5次实践作业
    第4次实践作业
    第3次实践作业
    第2次实践作业
    第1次实践作业
    软工实践个人总结
    2019 SDN大作业
    C语言Il作业01
  • 原文地址:https://www.cnblogs.com/sunsky303/p/9114813.html
Copyright © 2011-2022 走看看