Filebeat怎样进行日志分析
小樊
38
2025-12-28 12:33:02
Filebeat进行日志分析的完整流程
一 架构与核心概念
- Filebeat 负责轻量级采集与转发日志,常见输出为 Elasticsearch 或 Logstash。在 Kibana 中通过 Index Patterns 与 Discover/Visualize/Dashboard 完成检索、分析与可视化。
- 快速理解:Filebeat 采集 →(可选)Logstash 处理 → Elasticsearch 存储与检索 → Kibana 分析与展示。
二 安装与快速配置
- Ubuntu 安装
- 导入 GPG 并添加仓库(示例为 7.x,可按需替换为 8.x):
- wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
- echo “deb https://artifacts.elastic.co/packages/7.x/apt stable main” | sudo tee /etc/apt/sources.list.d/elastic-7.x.list
- sudo apt update && sudo apt install filebeat -y
- CentOS 安装
- 导入 GPG 并添加仓库(示例为 7.x):
- sudo rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
- echo -e “[elasticsearch-7.x]\nname=Elasticsearch repository for 7.x packages\nbaseurl=https://artifacts.elastic.co/packages/7.x/yum\ngpgcheck=1\ngpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch\nenabled=1\nautorefresh=1\ntype=rpm-md” | sudo tee /etc/yum.repos.d/elasticsearch.repo
- sudo yum install filebeat -y
- 最小可用配置 filebeat.yml(输出到本机 Elasticsearch)
- filebeat.inputs:
- type: log
enabled: true
paths:
- output.elasticsearch:
- hosts: [“localhost:9200”]
- index: “filebeat-%{[agent.version]}-%{+yyyy.MM.dd}”
- 启动与验证
- Ubuntu:sudo systemctl start filebeat && sudo systemctl enable filebeat
- CentOS:sudo systemctl start filebeat && sudo systemctl enable filebeat
- 语法检查:filebeat test config -e
- 运行状态:
- Ubuntu:sudo journalctl -u filebeat -f
- CentOS:sudo systemctl status filebeat
- 查看索引:curl -X GET “localhost:9200/_cat/indices?v”
三 解析与预处理要点
- 多行日志合并(如 Java 堆栈)
- filebeat.inputs:
- type: log
paths: [“/var/log/app/*.log”]
multiline.pattern: ‘^[^[]’
multiline.negate: true
multiline.match: after
- JSON 日志解析
- filebeat.inputs:
- type: log
paths: [“/var/log/app/json.log”]
json.keys_under_root: true
json.add_error_key: true
- 使用处理器 dissect/grok 结构化文本
- processors:
- dissect:
tokenizer: “%{timestamp} %{level} %{message}”
field: “message”
target_prefix: “”
- 字段脱敏与重命名
- processors:
- drop_fields:
fields: [“password”, “credit_card”]
- rename:
fields:
- from: “src_ip”
to: “clientip”
- 启用内置模块(自动采集与解析,如 system、nginx)
- sudo filebeat modules enable system
- sudo filebeat modules enable nginx
- 初始化模块与仪表板:sudo filebeat setup
四 在 Kibana 进行分析与可视化
- 访问 http://<kibana_host>:5601,进入 Stack Management > Index Patterns,创建索引模式(如 filebeat-*),时间字段选择 @timestamp。
- 在 Discover 中使用 KQL 检索与分析,例如:
- status: 500
- message: “ERROR”
- 按字段(如 level、clientip)筛选与统计。
- 在 Visualize Library 创建图表(柱状图、折线图等),并在 Dashboard 整合为运维/业务视图。
五 生产实践与优化
- 索引生命周期管理(ILM):配置 ILM 自动滚动与保留(如保留 30 天),控制存储成本。
- 监控与告警:使用 Watcher 设置阈值规则(如“1 小时内出现 10 次以上 ERROR”),触发邮件/短信/企业微信等告警。
- 版本化索引命名:使用 filebeat-%{[agent.version]}-%{+yyyy.MM.dd} 避免多版本混用带来的映射冲突。
- 复杂解析放 Logstash:当需要更强的 Grok/Date/GeoIP 等处理时,将输出指向 Logstash(localhost:5044),由 Logstash 完成过滤与增强后再写入 ES。