Filebeat在Ubuntu上设置告警规则的核心流程(基于Elastic Stack)
Filebeat本身不具备原生告警功能,需结合Elasticsearch(用于存储日志和执行查询)、Kibana(用于可视化和管理告警)及Watcher/X-Pack Alerting(用于定义触发条件和通知)实现。以下是详细步骤:
安装Elastic Stack组件
在Ubuntu上安装Filebeat、Elasticsearch、Kibana(版本需兼容,建议使用7.x及以上):
# 导入Elastic GPG密钥并添加仓库
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 -a /etc/apt/sources.list.d/elastic-7.x.list
# 更新软件包并安装组件
sudo apt-get update
sudo apt-get install filebeat elasticsearch kibana
启动并启用服务
sudo systemctl enable --now elasticsearch # 启动Elasticsearch
sudo systemctl enable --now kibana # 启动Kibana(默认端口5601)
sudo systemctl enable --now filebeat # 启动Filebeat
配置Filebeat监控目标
编辑/etc/filebeat/filebeat.yml,指定日志路径(如系统日志、应用日志)并输出到Elasticsearch:
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/*.log
- /var/log/syslog
output.elasticsearch:
hosts: ["localhost:9200"]
保存后重启Filebeat使配置生效:sudo systemctl restart filebeat。
Watcher是Elasticsearch的原生告警工具,可通过Kibana Dev Tools或API创建。以下以“监控错误日志并发送邮件”为例:
确保Filebeat数据被正确索引,避免查询问题:
// 在Kibana Dev Tools中执行
PUT /_template/filebeat_template
{
"index_patterns": ["filebeat-*"],
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
}
}
通过Kibana Dev Tools创建Watcher(以“每分钟检测错误日志”为例):
PUT /_watcher/watch/filebeat_error_alert
{
"trigger": {
"schedule": {
"interval": "1m" // 检测频率:每分钟
}
},
"input": {
"search": {
"request": {
"indices": ["filebeat-*"], // 监控的索引
"body": {
"query": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": "now-1m", // 时间范围:最近1分钟
"lte": "now"
}
}
},
{
"term": {
"log.level": "ERROR" // 筛选条件:错误级别日志
}
}
]
}
}
}
}
}
},
"condition": {
"compare": {
"ctx.payload.hits.total": {
"gt": 0 // 触发条件:错误数>0
}
}
},
"actions": {
"send_email": {
"email": {
"to": "admin@example.com", // 接收邮箱
"subject": "【告警】Filebeat检测到错误日志",
"body": "在最近1分钟内检测到{{ctx.payload.hits.total}}条错误日志,请及时排查。\n\n详情请查看Kibana:http://kibana-ip:5601"
}
}
}
}
1m=每分钟、5m=每5分钟)。range、term、match等多种条件)。ctx.payload.hits.total>0表示有错误日志时触发)。email、slack、pagerduty等,需提前配置)。若需通过邮件接收告警,需配置Watcher的邮件通知功能。编辑/etc/filebeat/filebeat.yml,添加SMTP设置:
xpack.notification.email:
account:
monitoring:
smtp:
host: "smtp.example.com" # SMTP服务器地址(如QQ邮箱:smtp.qq.com)
port: 587 # SMTP端口(通常为587或465)
user: "your-email@qq.com" # 发件邮箱
password: "your-password" # 邮箱授权码(非登录密码)
from: "your-email@qq.com" # 发件人地址
to: "admin@example.com" # 收件人地址
保存后重启Filebeat:sudo systemctl restart filebeat。
手动触发测试
向监控的日志文件(如/var/log/syslog)添加一条错误日志:
echo "[ERROR] This is a test error log" | sudo tee -a /var/log/syslog
查看Watcher状态
在Kibana中导航至“Stack Management”→“Watcher”,查看“filebeat_error_alert”的运行状态(是否触发、最近执行时间)。
检查通知
查收收件箱(或垃圾邮件箱),确认是否收到告警邮件。
input.search中的查询条件(如时间范围、日志字段),确保能匹配到目标日志。通过以上步骤,即可在Ubuntu上使用Filebeat结合Elastic Stack实现日志告警。根据实际需求,可扩展告警条件(如CPU使用率、磁盘空间)或通知方式(如Slack、PagerDuty)。