温馨提示×

Filebeat如何过滤日志

小樊
41
2026-07-08 16:39:21
栏目: 编程语言

Filebeat 中过滤日志,常见方式主要有 include / exclude 规则processors 处理、以及 条件判断。下面按实际使用场景给你一个清晰总结。


一、按文件路径过滤(最常用)

1️⃣ 只采集某些日志(include)

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/nginx/*.log

2️⃣ 排除某些文件(exclude)

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/*
  exclude_files: ['.gz$', 'error.log$']

✅ 适合:

  • 忽略压缩文件
  • 忽略特定日志文件

二、按日志内容过滤(重点)

方式一:使用 processors + drop_event(推荐)

✅ 丢弃包含某些关键词的日志

processors:
  - drop_event:
      when:
        regexp:
          message: "healthcheck|ping"

✅ 只保留包含某些关键词的日志

processors:
  - drop_event:
      when:
        not:
          regexp:
            message: "ERROR|WARN"

方式二:按字段值过滤

processors:
  - drop_event:
      when:
        equals:
          level: "DEBUG"

方式三:按日志长度过滤

processors:
  - drop_event:
      when:
        range:
          message:
            lt: 10

三、按时间过滤(忽略历史日志)

忽略修改时间超过 24 小时的日志

filebeat.inputs:
- type: log
  ignore_older: 24h

✅ 常用于:

  • 首次部署 Filebeat
  • 避免采集旧日志

四、多条件组合过滤

processors:
  - drop_event:
      when:
        and:
          - regexp:
              message: "ERROR"
          - equals:
              fields.env: "test"

五、在输出阶段过滤(不太推荐)

output.elasticsearch:
  hosts: ["localhost:9200"]
  indices:
    - index: "error-log-%{+yyyy.MM.dd}"
      when.contains:
        message: "ERROR"

⚠️ 这种方式只是控制输出,日志仍然会被采集


六、常见实战示例

✅ 只采集 ERROR 日志

processors:
  - drop_event:
      when:
        not:
          regexp:
            message: "ERROR"

✅ 忽略心跳/健康检查日志

processors:
  - drop_event:
      when:
        regexp:
          message: "GET /health"

✅ 忽略 DEBUG 日志

processors:
  - drop_event:
      when:
        equals:
          level: "DEBUG"

七、注意事项(很重要)

Filebeat 不能修改日志内容里的字段顺序
drop_event 是在内存中丢弃,不会发送到 ES / Kafka
正则性能敏感,避免过于复杂


八、推荐组合方案

需求 推荐方式
忽略某些文件 exclude_files
忽略旧日志 ignore_older
按内容过滤 processors.drop_event
按环境/标签 fields + when

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

  • 日志示例
  • 使用 ES / Kafka / Logstash 哪个
  • 想过滤的具体规则

我可以直接帮你写一份 可用的 filebeat.yml

0