LoginSignup
2
2

More than 3 years have passed since last update.

nginxリバプロで、requestに入っているheaderをlogに出す方法

Last updated at Posted at 2020-07-23

<1> header まるごと出す方法

ぱっと調べた感じverboseすぎるけどdebug modeが一番よかった。こういうことをしたいときは全体的な動きを作ってるとき、debug中が多いと思うので、debugにするのはいいと思う。

step 1. debug moduleをいれてbuildする

yumやaptで入れたnginxは、最初から入ってるのでこの手順は不要。docker hub の nginx official image (nginx:latestなど)は入っていないので注意

  && ./configure \
   ...
  --with-debug \
   ...

参考

nginxにモジュールを追加できるDockerfile
https://qiita.com/uturned0/items/3a0a7cb971edac40b11e

step 2.

error logのlevel をdebugにする。これは nginx.conf でやってもいいし server.conf でやってもいい

http {
    error_log /var/log/nginx/error_log debug;
}

もしくは

server {
    error_log /var/log/nginx/error_log debug;
}

step 3.

リバプロでやってる場合、logを見るとこんな感じで http proxy header という行がわかりやすく値を出してくれます。

...
2020/07/23 17:06:42 [debug] 8#0: *1 http proxy header: "X-Forwarded-Port: 443"
2020/07/23 17:06:42 [debug] 8#0: *1 http proxy header: "X-Forwarded-Proto: https"
2020/07/23 17:06:42 [debug] 8#0: *1 http proxy header: "MY_CUSTOM_HEADER1: foovar1"
2020/07/23 17:06:42 [debug] 8#0: *1 http proxy header: "MY_CUSTOM_HEADER2: foovar2"
...

<2> 特定のheaderだけ毎回loggingする方法

nginx 1.19.1 を使用

nginx.conf


http {

    log_format addHeaderlog '$remote_addr - $remote_user [$time_local] ' 
                        '"$request" $status $body_bytes_sent ' 
                        '"$http_referer" "$http_user_agent" "$http_x_forwarded_for" "$request_body" "$http_Authorization" "$http_x_my_header1" "$http_x_my_header2"'
                        '"$http_my_header1" "$http_my_header2" ';

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


    error_log  /var/log/nginx/error.log debug; |

}

log_format ディレクティブは http{} の中にしか書けないぽいので nginx.conf に書く。

nginx の log_format て不思議ね。single quoteで囲むと改行できるのかな?

access_log は各 server{} にも書ける。

$http_x_my_header1$http_my_header1 の2つが _x_ あるなしであるのは、どっちで取れるのかわからなかったから。今回は xなし で取れました。

nginx posts

nginxのstatusを表示するモジュール /nginx_status
https://qiita.com/uturned0/items/b4eb6839d75050933c7f

nginxにモジュールを追加できるDockerfile
https://qiita.com/uturned0/items/3a0a7cb971edac40b11e

nginxリバプロで header を cookieに書き込む方法
https://qiita.com/uturned0/items/112b8faba403bd534d5c

nginxリバプロで、requestに入っているheaderをlogに出す方法
https://qiita.com/uturned0/items/31162eeb03af05c7dc4b

nginxだけでコンテンツを返す方法 - Load balancerのhealth checkに
https://qiita.com/uturned0/items/a8bcca111b75c5055ed9

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2