nginx で proxy_pass の行き先をログに出す、複数ログファイルを指定する

nginx で location と proxy_pass を組み合わせて使うとURLパターンごとに行き先が違うリバースプロキシがとても簡単に作れる。

このとき、proxy_pass によるリバースプロキシが設定したとおりに動いているのか確認したい。それぞれのアクセス先をログに出力したい。

ログ設定は /etc/nginx/nginx.conf に書いてある。

元々のログ出力の記述は以下のようになっている。クライアントが nginx に接続してきたログだ。コレはこれで変更したくない。

 

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;

 

通常のログ出力はそのままにしておきつつ、別のログファイルに proxy_pass による行き先をロギングしたい。

この場合、以下のような内容を nginx.conf に追記する。

 

log_format upstreamlog '[$time_local] $remote_addr $host $upstream_addr $request;
access_log /var/log/nginx/upstream.log upstreamlog;

 

access.log ファイルは今まで通り出力しながら、別のファイルに別のフォーマットでproxy_pass による行き先が記録されるようになった。満足。

$upstream_addr 等、ログに出すとき使える変数は Module ngx_http_upstream_module の "Embedded Variables" に列挙してあるのでよく読むと良い。