在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
中的通知方式。參考來源: