Ingress Nginx默認訪問日志都輸出到/var/log/nginx/access.log
文件中,但是對於一般的生產環境來說,不可能把所有日志都輸到一個日志文件中,一般情況都是根據域名分別輸出到各個文件中。所以這里區分http指令域默認配置以及單獨域名的日志的配置方式。
1.默認日志格式更改為json
修改mandatory.yaml部署文件nginx-configuration ConfigMap配置中log-format-upstream字段,具體修改如下:
注意:mandatory.yaml是官方ingress-nginx的默認安裝yaml文件,其中也有configmap的配置,這是配置為空,留給運維人員自定義發揮。這里只是截出configmap的配置。(安裝ingress這里不做演示,參考本人ingress安裝博客)
kind: ConfigMap
apiVersion: v1
metadata:
name: nginx-configuration namespace: ingress-nginx labels: app.kubernetes.io/name: ingress-nginx app.kubernetes.io/part-of: ingress-nginx data: log-format-upstream: '{"nginx_timestamp":"$time_iso8601","clientip":"$remote_addr","nginx_host":"$server_addr","host":"$http_host","request":"$request","url":"$request_uri","upstreamhost":"$upstream_addr","status":"$status","body_bytes_sent":"$body_bytes_sent","request_time":"$request_time","upstream_response_time":"$upstream_response_time","xff":"$http_x_forwarded_for","referer":"$http_referer","http_user_agent":"$http_user_agent","request_length":"$request_length","request_method":"$request_method"}'
部署了上述文件后,查看一下ingress-nginx的配置文件中發生了什么變化
#先將nginx配置文件拷貝出來比較容易查看
kubectl cp -n ingress-nginx nginx-ingress-controller-8f68db9b5-2flsq:/etc/nginx/nginx.conf /test/nginx.conf
#找到文件變化的配置文件

目前ingress-nginx配置日志文件格式為json輸出已經完成了。一般默認中server指令域中如果不配置單獨的日志輸出,會使用http中默認的日志配置。如果需要為每一個域名獨立配置文件,見如下。
2.根據域名配置訪問日志輸出
這里使用一個測試網站的ingress的yaml文件來作為演示。
cat gcc-21ldj-frontend-ingress.yaml
--- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: gcc-21ldj-frontend namespace: dev annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/configuration-snippet: | access_log /var/log/nginx/gcc-h5-test01.access.log upstreaminfo if=$loggable; # 這里直接引用了http指令域的upstreaminfo。 error_log /var/log/nginx/gcc-h5-test01.error.log; rewrite /gcc/21ldj/(.*) /$1 break; spec: tls: - hosts: - gcc-h5-test01.mbgadev.cn secretName: mbgadev-20210908 rules: - host: gcc-h5-test01.mbgadev.cn http: paths: - path: /gcc/21ldj/ backend: serviceName: gcc-21ldj-frontend servicePort: 80
部署該ingress文件后,查看一下nginx文件的變化。
#將最新的nginx文件拷貝一下
kubectl cp -n ingress-nginx nginx-ingress-controller-8f68db9b5-2flsq:/etc/nginx/nginx.conf /test/nginx.conf
#找到文件變化的配置文件

注:if=$loggable的含義
#參數 if,設置是否記錄日志,當參數值的條件成立,即不為 0 或空時,才記錄日志。
下面是ingress-nginx中的配置文件
map $status $loggable {
~^[23] 0; default 1; } access_log logs/access.log combined if=$loggable;
具體可參考:Nginx日志管理
3.參考
Ingress配置參考:https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/nginx-configuration/configmap.md
Ingress注釋參考https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/nginx-configuration/annotations.md