如何在Nginx日志中记录反向代理上游服务器服务请求?

Pol*_*Pol 22 reverse-proxy nginx

我们使用Nginx作为此设置的反向代理:

upstream frontends {
  server 127.0.0.1:8000;
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
  [...]
}

server {
  location / {
    proxy_pass http://frontends;
    [...]
  }
  [...]
}
Run Code Online (Sandbox Code Playgroud)

作为访问日志的一部分,我想记录为请求提供服务的上游服务器,在我们的例子中,这意味着关联的localhost端口.

文档中的变量(http://wiki.nginx.org/HttpProxyModule#Variables)提到$ proxy_host和$ proxy_port,但在日志中它们总是以"frontends"和"80"的值结束.

kak*_*oni 42

首先添加新的日志记录格式

log_format upstreamlog '[$time_local] $remote_addr - $remote_user - $server_name $host to: $upstream_addr: $request $status upstream_response_time $upstream_response_time msec $msec request_time $request_time';
Run Code Online (Sandbox Code Playgroud)

然后将accesslog重新定义为

[18/Nov/2019:10:08:15 -0700] <request IP> - - - <config host> <request host> to: 127.0.0.1:8000: GET /path/requested HTTP/1.1 200 upstream_response_time 0.000 msec 1574096895.474 request_time 0.001
Run Code Online (Sandbox Code Playgroud)

log_format转到http {}部分,access_log可以在内部位置.


akh*_*bis 28

使用$upstream_addr,你会得到,例如,127.0.0.1:8000unix:/home/my_user/www/my_site/tmp/.unicorn.sock