根据nginx配置中的位置有条件地记录$ request_body

时间:2015-06-27 22:10:21

标签: nginx

我需要配置Nginx以仅针对某些$request_body块记录location

this post的启发,我希望以下方面有效:

http {

    log_format l2met "request_body = $xxxx";
    access_log logs/nginx/access.log l2met;
    error_log logs/nginx/error.log;

    server {

        location /path/to/log {
            set $xxxx $request_body;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }

        location / {
            set $xxxx "NOT_LOGGED";
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }
    }
}

但是,请求正文只会打印为-

我可以随时打印$request_body

http {

    log_format l2met "request_body = $request_body";
    access_log logs/nginx/access.log l2met;
    error_log logs/nginx/error.log;

    server {

        location /path/to/log {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }

        location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }
    }
}

我可以通过以下方式有条件地设置日志记录:

http {

    log_format l2met "xxxx = $xxxx";
    access_log logs/nginx/access.log l2met;
    error_log logs/nginx/error.log;

    server {

        location /path/to/log {
            set $xxxx "NEED TO LOG REQUEST BODY HERE";
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }

        location / {
            set $xxxx "NOT_LOGGED";
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }
    }
}

出于某种原因,似乎只要我从$request_body块中引用location,日志输出就会变为-

我已尝试将client_body_in_single_buffer添加到http块,但这似乎没有帮助。

我如何使这项工作?

我正在使用默认安装的apt-get

版本的nginx
$ nginx -v
nginx version: nginx/1.1.19

1 个答案:

答案 0 :(得分:1)

您可以声明任意数量的log_format并使用您需要的数量。

http {
  log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
  log_format capturebody "request_body = $request_body";
  access_log logs/nginx/access.log l2met;

  server {
    ...
    location / {
      ...
    }
    location /other/ {
      # this is the location where you need to log $request_body
      access_log logs/nginx/access.log capturebody;
      ...
    }
    ...
  }
}
相关问题