how do I add the x-forwarded-for field to my access logs for the nginx ingress controller?

4/22/2019

Im using the nginx ingress controller on gke, by default these are what my access logs look like:

"10.123.0.20 - [10.123.0.20] - - [22/Apr/2019:18:47:59 +0000] "GET /sdflksdf/sdfsdf HTTP/2.0" 404 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/538.12 (KHTML, like Gecko) Chrome/73.0.3683.100 Safari/537.36" 26 0.002 [default-blah-80] 10.44.0.26:80 0 0.001 404 skjf0s93jf0ws93jfsijf3s3fjs3i

I want to add the x-forwarded-for header in my access logs. Id like that field to be added at the end of the current log lines if possible. OR at the start of the log line would be ok too i guess

Im looking at their docs and its not clear to me how to add x-forwarded-for to the access log: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/log-format/

-- red888
google-kubernetes-engine
kubernetes
nginx
nginx-ingress

1 Answer

4/23/2019

You should use a ConfigMap to customize the NGINX configuration:

ConfigMaps allow you to decouple configuration artifacts from image content to keep containerized applications portable.

The ConfigMap API resource stores configuration data as key-value pairs. The data provides the configurations for system components for the nginx-controller.

To configure custom logs, you need to use the log-format-upstream key.

e.g.:

Create the following configmap:

apiVersion: v1
data:
  log-format-upstream: '$remote_addr - $request_id - [$proxy_add_x_forwarded_for] - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_length $request_time [$proxy_upstream_name] $upstream_addr $upstream_response_length $upstream_response_time $upstream_status'
kind: ConfigMap
metadata:
  name: nginx-ingress-config

and make sure that you are using --configmap=$(POD_NAMESPACE)/nginx-ingress-config as command args for your nginx-ingress-controller (example from offical repo here).

-- Eduardo Baitello
Source: StackOverflow