環境
- AWS
- nginx version: nginx/1.10.3 (Ubuntu)
- Rails5.1
- Unicorn
やりたいこと
- Nginxのログフォーマットを変更したい
- AWSのALBのアクセス元IPを表示したい
- アクセス元プロトコルを表示したい
- ついでにエラーログもフォーマットを変更したい
設定例
/etc/nginx/nginx.conf
access_logおよび、error_logに独自フォーマットのmain
を指定。
##
# Logging Settings
##
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $request_time $upstream_response_time '
'"$http_x_forwarded_for" "$http_x_forwarded_proto" $host';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log main;
発生した問題
- Nginxが起動しない
原因
Nginxのエラーログに、独自フォーマットのmain
を指定指定しているため。
構文チェックを行うと以下のエラーが表示される。
$ nginx -t -c /etc/nginx/nginx.conf
2018/01/16 15:34:00 [emerg] 29059#29059: invalid log level "main" in /etc/nginx/nginx.conf:53
nginx: configuration file /etc/nginx/nginx.conf test failed
正しい設定
error.logにはフォーマットは指定できません。
##
# Logging Settings
##
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $request_time $upstream_response_time '
'"$http_x_forwarded_for" "$http_x_forwarded_proto" $host';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;