Ubuntu上Filebeat设置报警的整体流程
Filebeat本身不具备直接报警功能,需结合Elastic Stack(Elasticsearch、Kibana)的X-Pack Alerting(原Watcher)组件实现。核心逻辑是:Filebeat收集日志并发送至Elasticsearch→通过Kibana或Elasticsearch的API创建报警规则→触发条件满足时通过邮件、Slack等渠道发送通知。
output.elasticsearch部分需填写Elasticsearch地址);elasticsearch.yml中的xpack.security.enabled: true)。编辑Filebeat主配置文件/etc/filebeat/filebeat.yml,确保以下关键配置正确:
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/*.log # 监控系统日志(可根据需求调整路径)
output.elasticsearch:
hosts: ["localhost:9200"] # Elasticsearch地址
index: "filebeat-%{[agent.version]}-%{+yyyy.MM.dd}" # 索引命名规则(按日期分割)
保存后启动/重启Filebeat服务:
sudo systemctl enable filebeat
sudo systemctl start filebeat
通过Kibana的Web界面创建报警规则,步骤如下:
http://localhost:5601),进入Stack Management → Alerts and Actions → Manage alerts;filebeat-*);若偏好命令行,可使用Elasticsearch的Watcher API创建报警规则。以下示例为每分钟检查filebeat-*索引中包含“error”的日志条目,若超过5条则发送邮件:
curl -X PUT "localhost:9200/_watcher/watch/error_alert" -H 'Content-Type: application/json' -d'
{
"trigger": {
"schedule": {
"interval": "1m" # 每分钟触发一次
}
},
"input": {
"search": {
"request": {
"indices": ["filebeat-*"],
"body": {
"query": {
"bool": {
"must": [
{"match": {"message": "error"}} # 匹配包含“error”的日志
],
"filter": [
{"range": {"@timestamp": {"gte": "now-1m", "lte": "now"}}} # 最近1分钟内的日志
]
}
}
}
}
}
},
"condition": {
"compare": {
"ctx.payload.hits.total": {
"gt": 5 # 日志条目超过5条时触发
}
}
},
"actions": {
"email_admin": {
"email": {
"to": "admin@example.com", # 接收人邮箱
"subject": "Elasticsearch Alert: High Error Logs",
"body": "The following error logs were detected:\n{{#ctx.payload.hits.hits}} {{_source.message}}\n{{/ctx.payload.hits.hits}}"
}
}
}
}'
若报警规则需发送邮件,需在Elasticsearch中配置SMTP设置(elasticsearch.yml):
xpack.notification.email:
account:
default:
smtp:
host: "smtp.example.com" # SMTP服务器地址(如Gmail为smtp.gmail.com)
port: 587
user: "your_email@example.com"
password: "your_email_password"
authentication: "plain"
starttls.enable: true
from: "alert@example.com" # 发件人邮箱
profile: "default"
修改后重启Elasticsearch服务:
sudo systemctl restart elasticsearch
/var/log/syslog写入包含“error”的条目:echo "This is an error message" | sudo tee -a /var/log/syslog);