在 Ubuntu 上使用 Filebeat 过滤日志,通常有以下几种常见方式,按使用频率和场景从简单到复杂说明:
processors 在 Filebeat 端过滤(推荐)Filebeat 本身支持 processors,可以在采集阶段就过滤或处理日志。
例如:忽略包含 DEBUG 的日志
filebeat.inputs:
- type: log
paths:
- /var/log/app/*.log
processors:
- drop_event.when.contains:
message: "DEBUG"
processors:
- drop_event.when.regexp:
message: "^healthcheck"
processors:
- drop_event.when.not.contains:
message: "ERROR"
include_lines / exclude_lines适合简单文本过滤。
filebeat.inputs:
- type: log
paths:
- /var/log/app/app.log
include_lines: ['ERROR', 'WARN']
exclude_lines: ['^INFO', 'debug']
✅ 优点:简单
❌ 缺点:不能做复杂逻辑
exclude_files 过滤文件filebeat.inputs:
- type: log
paths:
- /var/log/app/*
exclude_files: ['.gz$', 'access.log']
fields + 条件输出(按日志类型分流)filebeat.inputs:
- type: log
paths:
- /var/log/nginx/access.log
fields:
log_type: nginx_access
然后在 output 中判断:
output.elasticsearch:
hosts: ["localhost:9200"]
indices:
- index: "nginx-access-%{+yyyy.MM.dd}"
when.equals:
fields.log_type: nginx_access
如果过滤逻辑非常复杂(JSON 解析、多条件、字段重组):
filter {
if [message] =~ "ERROR" {
mutate { add_tag => ["error"] }
}
}
# 测试配置
sudo filebeat test config
# 查看生效配置
sudo filebeat export config
# 前台运行看日志
sudo filebeat -e -c /etc/filebeat/filebeat.yml
filebeat.inputs:
- type: log
paths:
- /var/log/app/*.log
exclude_lines: ['^DEBUG']
processors:
- drop_event.when.contains:
message: "heartbeat"
如果你能告诉我:
我可以给你一份可直接用的配置。