温馨提示×

CentOS Filebeat如何过滤日志

小樊
47
2026-07-20 08:46:06
栏目: 智能运维

CentOS 上使用 Filebeat 过滤日志,常见做法是通过 Filebeat 自身的配置结合 Elasticsearch / Logstash 来实现。下面按由简单到进阶的方式说明。


一、Filebeat 过滤日志的几种方式

✅ 1. 使用 include_lines / exclude_lines(最常用)

适用于:按行内容过滤

示例:只采集包含 ERROR 的日志

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/app/*.log
  include_lines: ['ERROR']

示例:排除包含 DEBUG 的日志

  exclude_lines: ['DEBUG']

✅ 特点:

  • 在 Filebeat 采集阶段就过滤
  • 性能最好
  • 不支持复杂逻辑

✅ 2. 使用 exclude_files(按文件名过滤)

适用于:忽略某些日志文件

filebeat.inputs:
- type: log
  paths:
    - /var/log/app/*.log
  exclude_files: ['\.gz$', 'test\.log']

✅ 常用于忽略:

  • 压缩文件
  • 临时日志

✅ 3. 使用 processors 过滤(推荐进阶方式)

适用于:按字段、标签、条件删除或保留事件

示例:删除 message 中包含 health check 的日志

processors:
  - drop_event:
      when:
        regexp:
          message: "health check"

示例:只保留 level 为 ERROR 的日志

processors:
  - drop_event:
      when:
        not:
          equals:
            level: "ERROR"

✅ 特点:

  • 功能强大
  • 支持正则、条件、多字段判断
  • 官方推荐方式

✅ 4. 使用 fields + 条件过滤(分类日志)

适用于:给日志打标签,后续在 ES / Kibana 中过滤

filebeat.inputs:
- type: log
  paths:
    - /var/log/nginx/access.log
  fields:
    log_type: nginx_access
  fields_under_root: true

然后在 Kibana 中:

log_type: nginx_access

二、结合 Logstash 过滤(高级)

如果你使用 Filebeat → Logstash → ES,可以在 Logstash 中过滤。

Logstash 示例

filter {
  if "ERROR" not in [message] {
    drop {}
  }
}

✅ 适合:

  • 复杂解析(grok)
  • 多条件判断
  • 数据清洗

三、CentOS 上 Filebeat 常见配置路径

# 配置文件
/etc/filebeat/filebeat.yml

# 重启服务
systemctl restart filebeat

# 查看状态
systemctl status filebeat

# 测试配置
filebeat test config

四、推荐方案总结

需求 推荐方式
简单按关键字过滤 include_lines / exclude_lines
删除某些日志 processors.drop_event
忽略某些文件 exclude_files
复杂解析 Logstash
只做分类 fields

五、示例:完整 Filebeat 过滤配置

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/app/*.log
  exclude_lines: ['DEBUG']

processors:
  - drop_event:
      when:
        regexp:
          message: "health check"

output.elasticsearch:
  hosts: ["localhost:9200"]

如果你愿意,可以告诉我:

  • ✅ 日志路径
  • ✅ 想过滤的关键字
  • ✅ 是否使用 Elasticsearch / Logstash

我可以帮你写一份可直接使用的 Filebeat 配置

0