在Ubuntu上使用Filebeat实现监控与告警,需结合Elastic Stack组件,核心步骤如下:
sudo apt-get update && sudo apt-get install filebeat
/etc/filebeat/filebeat.yml,指定日志路径(如系统日志、应用日志):filebeat.inputs:
- type: log
enabled: true
paths: ["/var/log/*.log", "/var/log/syslog"]
output.elasticsearch:
hosts: ["localhost:9200"] # 确保Elasticsearch已运行
启用模块(如系统日志):filebeat.modules:
- module: system
syslog:
enabled: true
sudo systemctl enable --now filebeat
PUT /_template/filebeat
{
"index_patterns": ["filebeat-*"],
"mappings": {
"_source": { "enabled": true }
}
}
PUT _watcher/watch/filebeat_error_alert
{
"trigger": { "schedule": { "interval": "1m" } }, // 每分钟触发一次
"input": {
"search": {
"request": {
"indices": ["filebeat-*"],
"body": {
"query": {
"bool": {
"must": [
{ "range": { "@timestamp": { "gte": "now-1m", "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 Error Alert",
"body": "Detected {{ctx.payload.hits.total}} error logs in the last minute."
}
}
}
}
说明:
trigger.interval:告警检测频率。input.query:通过Elasticsearch DSL定义筛选条件(如错误日志、特定字段值)。actions:支持邮件、Slack等通知方式(需提前配置SMTP或集成第三方服务)。query条件(如增加时间范围、关联字段)或actions中的通知方式。参考来源: