15

I am trying to print the response data for development/debugging purposes. I couldn't find a similar question or any info on this. If you do, please add a comment.

2

3 Answers 3

13

Use body_filter_by_lua to assign request body to a nginx variable, here is an example:

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!";
        }
    }
}
2
  • 1
    In the code , we seem to be putting the first 1000 bytes from the response chunk and putting into resp_body i.e. in this line "resp_body = string.sub(ngx.arg[1], 1, 1000)". Is there a specific reason for this to be 1000.
    – doon
    Jun 2, 2015 at 11:51
  • In my case its not giving me response body but its giving me the path of log like this "resp_body:""access_log/usr/local/openresty/nginx/logs/access.logupstreamlog" Can you please suggest what's wrong?
    – SMT
    Mar 27, 2019 at 9:56
3

use ngx_lua module

like this

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

in the right location

1
  • 1
    I think I'd prefer to use ngx.DEBUG. CRIT might get printed to the console, emailed to the whole sysadmin team, etc... Feb 15, 2013 at 8:08
0

I've found this one for example, and I think the echo module can also do it.

1
  • 2
    The echo module and the example provided talk about logging the request headers/body but I want to log the response body. Thanks petermolanar.
    – vamsu
    Feb 21, 2012 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.