45

We use Nginx as a reverse proxy with this setup:

    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;
        [...]
      }
      [...]
    }

As part of the access log, I would like to record the upstream server that has served the request, which in our case just means the associated localhost port.

The variables in the documentation (http://wiki.nginx.org/HttpProxyModule#Variables) mention $proxy_host and $proxy_port but in the log they always end up with the values "frontends" and "80".

ehsan shirzadi
  • 4,709
  • 16
  • 69
  • 112
Pol
  • 3,848
  • 1
  • 38
  • 55

2 Answers2

86

First add new logging format

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';

Example output:

[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

and then redefine accesslog as

access_log /var/log/nginx/access.log upstreamlog;

log_format goes to http {} section, access_log can be inside location.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
kakoni
  • 4,980
  • 3
  • 23
  • 14
42

Use $upstream_addr and you will get, for example, 127.0.0.1:8000 or unix:/home/my_user/www/my_site/tmp/.unicorn.sock

akhanubis
  • 4,202
  • 1
  • 27
  • 19