咱們在k8s部署服務時,通常來講一個服務會對應一類pod,而pod經過rs實現副本集,而這些pod的日誌通常有控制檯stdout和文件的,通常會把這些日誌最終輸出到elasticsearch裏,再經過kabana進行分析,而在實現由pod到elasticsearch(es)時有多種方法,下面我列舉一下:docker
從上面的解析能夠看到第1種若是你是docker swarm環境能夠使用,而第2種與業務代碼耦合太緊也不合適,只有第三種是將來的趨勢,目前大都是使用這種方式!api
1 sidecar的fluentd的mapconfigbash
apiVersion: v1 kind: ConfigMap metadata: name: fluentd-config namespace: saas data: fluentd.conf: | <source> type tail format none path /var/log/*.log pos_file /var/log/log.pos tag saas </source> <match **> @id elasticsearch @type elasticsearch @log_level debug index_name fluentd type_name _doc host elasticsearch.elk port 9200 include_tag_key true tag_key @log_name logstash_format true flush_interval 10s </match>
運行elasticsearch
kubectl create -f fluentd-config-sidecar.yaml
測試一個pod,像容器輸出日誌到目錄,定時反覆輸出ide
apiVersion: v1 kind: Pod metadata: labels: example: logging-sidecar name: logging-sidecar-example spec: containers: - name: synthetic-logger image: 172.17.0.22:8888/saas/hello-world:latest command: ["bash", "-c", "i=\"0\"; while true; do echo \"`hostname`: $i \" >> /var/log/1.log; date --rfc-3339 ns >> /var/log/1.log; sleep 4; i=$[$i+1]; done"] volumeMounts: - name: varlog mountPath: /var/log - name: sidecar-log-collector image: registry.cn-beijing.aliyuncs.com/k8s-mqm/fluentd-elasticsearch:v2.1.0 env: - name: FLUENTD_ARGS value: -c /etc/fluentd-config/fluentd.conf volumeMounts: - name: varlog mountPath: /var/log - name: config-volume mountPath: /etc/fluentd-config volumes: - name: varlog emptyDir: {} - name: config-volume configMap: name: fluentd-config
部署它測試
kubectl create -f fluentd-demo.yaml
而後去你的kabana裏查看日誌,能夠按着@log_name字段去查詢,這就是咱們日誌裏的tag,這個咱們能夠在代碼裏配置,能夠設置成一個namespace,這樣方便日誌的跟蹤!spa