filebeat 篇章——解析 json 日志
解析 json 日志(Parsing json logs)
https://www.elastic.co/guide/en/beats/filebeat/8.7/running-on-kubernetes.html#_parsing_json_logs
It is common case when collecting logs from workloads running on Kubernetes that these applications are logging in json format. In these case, special handling can be applied so as to parse these json logs properly and decode them into fields. Bellow there are provided 2 different ways of configuring filebeat’s autodiscover so as to identify and parse json logs. We will use an example of one Pod with 2 containers where only one of these logs in json format.
{"type":"log","@timestamp":"2020-11-16T14:30:13+00:00","tags":["warning","plugins","licensing"],"pid":7,"message":"License information could not be obtained from Elasticsearch due to Error: No Living connections error"}
1、Using json.*
options with templates.(使用带模版的 json.* 选项)
# 指定自动发现功能,它能够自动识别新的容器,并开始收集这些容器的日志
filebeat.autodiscover:
# 指明该配置为 kubernets 提供程序
providers:
# 声明使用 kubernetes 提供程序
- type: kubernetes
# 绑定了命名空间中的环境变量。使用该声明时,filbeat 可以检索容器所在的节点名称并自动收集日志
node: ${NODE_NAME}
# 声明要应用的模板数组
templates:
# 选择用于模版的条件
- condition:
# 要查询的对象类型
contains:
# 需要匹配的容器名称。如果容器名称中包含了“no-json-logging”,则使用第一个模板来匹配容器。
kubernetes.container.name: "no-json-logging"
# 为日志源提供参数
config:
# 告知Filebeat使用容器日志
- type: container
# 用于指定文件路径,可以使用通配符匹配来捕获容器日志
paths:
- "/var/log/containers/*-${data.kubernetes.container.id}.log"
# 需要匹配的同样是容器名称,但是如果名称中包含“json-logging”,则使用第二个模板来匹配容器。
- condition:
contains:
kubernetes.container.name: "json-logging"
# 为第二个模板配置参数
config:
- type: container
paths:
- "/var/log/containers/*-${data.kubernetes.container.id}.log"
# 告诉Filebeat在Elasticsearch中将所有JSON键放在根级别,而不是将它们放在一个单独的“json”字段中
json.keys_under_root: true
# 编码遇到的所有错误都将提交到添加一个“error”键的JSON对象中,以便更容易地诊断问题
json.add_error_key: true
# 告诉Filebeat将“message”作为消息字段名来使用,而不是从默认的“message”的JSON属性中检索消息
json.message_key: message
2、Using json.*
options with hints.(使用带提示的 json.* 选项)
Key part here is to properly annotate the Pod to only parse logs of the correct container as json logs. In this, annotation should be constructed like this:
co.elastic.logs.<container_name>/json.keys_under_root: "true"
自动发现配置:
filebeat.autodiscover: providers: - type: kubernetes node: ${NODE_NAME} hints.enabled: true hints.default_config: type: container paths: - /var/log/containers/*${data.kubernetes.container.id}.log
然后正确注解 Pod:
annotations: co.elastic.logs.json-logging/json.keys_under_root: "true" co.elastic.logs.json-logging/json.add_error_key: "true" co.elastic.logs.json-logging/json.message_key: "message"