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

conditionally logging $request_body based on location in nginx config

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

受到 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;
        }
    }
}

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

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

我该如何进行这项工作?

我使用的是默认安装的 nginx 版本 apt-get:

$ nginx -v
nginx version: nginx/1.1.19

您可以声明任意数量的 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;
      ...
    }
    ...
  }
}