在 Ubuntu 上使用 Filebeat 监控应用程序日志
一 安装与准备
sudo apt update
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 update
sudo apt install filebeat
sudo systemctl start filebeat
sudo systemctl enable filebeat
sudo cp /etc/filebeat/filebeat.yml /etc/filebeat/filebeat.yml.bak。二 快速上手 控制台输出验证
sudo tee /etc/filebeat/filebeat.yml >/dev/null <<'EOF'
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/myapp/*.log
output.console:
enabled: true
pretty: true
EOF
sudo systemctl restart filebeat
journalctl -u filebeat -f
/var/log/myapp/*.log 替换为你的应用实际日志路径。看到结构化日志输出即表示采集链路正常。三 生产常用架构与配置
sudo tee /etc/filebeat/filebeat.yml >/dev/null <<'EOF'
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/myapp/*.log
fields:
app: myapp
env: prod
fields_under_root: true
output.logstash:
hosts: ["logstash.example.com:5044"]
EOF
input {
beats { port => 5044 }
}
filter {
# 可添加 grok、date、mutate 等处理
}
output {
elasticsearch {
hosts => ["http://es.example.com:9200"]
index => "app-logs-%{+YYYY.MM.dd}"
}
}
sudo systemctl restart filebeat
sudo systemctl restart logstash
sudo tee /etc/filebeat/filebeat.yml >/dev/null <<'EOF'
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/myapp/*.log
fields:
app: myapp
env: prod
fields_under_root: true
output.elasticsearch:
hosts: ["es.example.com:9200"]
index: "app-logs-%{+YYYY.MM.dd}"
EOF
sudo systemctl restart filebeat
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/nginx/example.com.access.log
fields: { domain: "example.com" }
fields_under_root: true
- type: log
enabled: true
paths:
- /var/log/nginx/api.example.com.access.log
fields: { domain: "api.example.com" }
fields_under_root: true
output.elasticsearch:
hosts: ["es.example.com:9200"]
indices:
- index: "example-com-%{+yyyy.MM.dd}"
when.equals:
domain: "example.com"
- index: "api-example-com-%{+yyyy.MM.dd}"
when.equals:
domain: "api.example.com"
四 常用处理与运维要点
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/myapp/*.log
multiline.pattern: '^[[:space:]]'
multiline.negate: true
multiline.match: after
fields:
app: order-service
env: staging
fields_under_root: true
app-logs-%{+YYYY.MM.dd}),并在 Elasticsearch 配置相应的 Index Lifecycle Policy,避免无限增长。ReadWritePaths 或加入日志所属用户组)。sudo filebeat test configsudo filebeat test outputjournalctl -u filebeat -fapp-logs-*)验证字段与内容。