自定义 Filebeat 日志处理规则的实用指南
一 配置结构与生效方式
二 输入与多行 JSON 配置
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/myapp/*.log
tags: ["myapp", "json"]
fields:
app_id: myapp-prod
env: prod
fields_under_root: true
multiline:
pattern: '^\\[?\\d{4}-\\d{2}-\\d{2}' # 以日期或 [ 开头的行作为新事件起点
negate: true
match: after
timeout: 5s
json.keys_under_root: true
json.overwrite_keys: true
json.add_error_key: true
json.message_key: message
processors:
- timestamp:
source: datetime
target: "@timestamp"
layouts:
- "2006-01-02T15:04:05.999999999Z07:00" # Go 时间格式,需与日志时间格式一致
output.elasticsearch:
hosts: ["http://localhost:9200"]
index: "filebeat-%{[agent.version]}-%{+yyyy.MM.dd}"
三 处理器与条件编排
processors:
- add_tags:
tags: ["error"]
when:
equals:
log.level: "ERROR"
- fingerprint:
fields: ["message", "host.name"]
target_field: "@metadata._id"
method: "sha256"
四 输出路由与索引管理
output.elasticsearch:
hosts: ["http://es:9200"]
index: "myapp-%{+yyyy.MM.dd}"
pipeline: "myapp-ingest-pipeline"
output.kafka:
hosts: ["kafka1:9092", "kafka2:9092"]
topic: "logs-myapp"
required_acks: 1
compression: gzip
partition.round_robin.reachable_only: false
五 Kubernetes 环境的提示式自动发现
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
template:
metadata:
annotations:
co.elastic.logs/module: nginx
co.elastic.logs/fileset.stdout: access
co.elastic.logs/fileset.stderr: error
co.elastic.logs/json.message_key: "log"
co.elastic.logs/json.add_error_key: "true"