我正在尝试使用Fluentd在Kubernetes中实现Streaming Sidecar Container日志记录架构。
在一个豆荚中,我有:
基本上,Application容器日志存储在共享的emptyDir卷中。流利的日志转发器容器将此日志文件拖到共享的emptyDir卷中,并将其转发到外部日志聚合器。
Fluentd日志转发器容器在td-agent.conf
中使用以下配置:
<source>
@type tail
tag "#{ENV['TAG_VALUE']}"
path (path to log file in volume)
pos_file /var/log/td-agent/tmp/access.log.pos
format json
time_key time
time_format %iso8601
keep_time_key true
</source>
<match *.*>
@type forward
@id forward_tail
heartbeat_type tcp
<server>
host (server-host-address)
</server>
</match>
我正在使用环境变量来设置tag
值,因此可以动态更改它,例如当我必须将此容器与其他应用程序容器并排使用时,不必修改此配置并再次重建该映像。
现在,我在Kubernetes中创建pod时设置环境变量值:
.
.
spec:
containers:
- name: application-pod
image: application-image:1.0
ports:
- containerPort: 1234
volumeMounts:
- name: logvolume
mountPath: /var/log/app
- name: log-forwarder
image: log-forwarder-image:1.0
env:
- name: "TAG_VALUE"
value: "app.service01"
volumeMounts:
- name: logvolume
mountPath: /var/log/app
volumes:
- name: logvolume
emptyDir: {}
部署Pod之后,我发现Fluentd日志转发器容器中的标签值显示为空(预期值:“ app.service01”)。我想这是因为Fluentd的td-agent在分配TAG_VALUE
环境变量之前首先进行了初始化。
所以,主要问题是...
如何动态设置td-agent的标签值?
但实际上,我想知道的是:
是否可以在Kubernetes中初始化容器之前分配环境变量?
答案 0 :(得分:1)
您可以使用组合fluent-plugin-kubernetes_metadata_filter和fluent-plugin-rewrite-tag-filter来设置容器名称或标签内容。
答案 1 :(得分:1)
作为第一个问题(如何动态设置td-agent的标签值?)的答案,这似乎是您在内部定义tag "#{ENV['TAG_VALUE']}"
的最佳方法流利的配置文件。
对于第二个问题,在初始化容器之前已分配环境变量。
所以这意味着它应该可以工作,我用下面的示例yaml进行了测试,并且效果很好。
apiVersion: v1
kind: ConfigMap
metadata:
name: fluentd-conf
data:
fluentd.conf.template: |
<source>
@type tail
tag "#{ENV['TAG_VALUE']}"
path /var/log/nginx/access.log
format nginx
</source>
<match *.*>
@type stdout
</match>
---
apiVersion: v1
kind: Pod
metadata:
name: log-forwarder
labels:
purpose: test-fluentd
spec:
containers:
- name: nginx
image: nginx:latest
volumeMounts:
- name: logvolume
mountPath: /var/log/nginx
- name: fluentd
image: fluent/fluentd
env:
- name: "TAG_VALUE"
value: "test.nginx"
- name: "FLUENTD_CONF"
value: "fluentd.conf"
volumeMounts:
- name: fluentd-conf
mountPath: /fluentd/etc
- name: logvolume
mountPath: /var/log/nginx
volumes:
- name: fluentd-conf
configMap:
name: fluentd-conf
items:
- key: fluentd.conf.template
path: fluentd.conf
- name: logvolume
emptyDir: {}
restartPolicy: Never
当我卷曲nginx pod时,我会在流畅的容器stdout上看到此输出。
kubectl logs -f log-forwarder fluentd
2019-03-20 09:50:54.000000000 +0000 test.nginx: {"remote":"10.20.14.1","host":"-","user":"-","method":"GET","path":"/","code":"200","size":"612","referer":"-","agent":"curl/7.60.0","http_x_forwarded_for":"-"}
2019-03-20 09:50:55.000000000 +0000 test.nginx: {"remote":"10.20.14.1","host":"-","user":"-","method":"GET","path":"/","code":"200","size":"612","referer":"-","agent":"curl/7.60.0","http_x_forwarded_for":"-"}
2019-03-20 09:50:56.000000000 +0000 test.nginx: {"remote":"10.128.0.26","host":"-","user":"-","method":"GET","path":"/","code":"200","size":"612","referer":"-","agent":"curl/7.60.0","http_x_forwarded_for":"-"}
如您所见,我的环境变量TAG_VALUE=test.nginx
已应用于日志条目。
我希望它会有用。