← Kursa Dön
📄 Text · 30 min

Beats — Filebeat, Metricbeat, Heartbeat

Giriş — Filebeat, Metricbeat, Heartbeat ve Packetbeat

Bir fabrikadaki sensörleri düşün. Sıcaklık sensörü, basınç sensörü, titreşim sensörü, güvenlik kamerası — her biri küçük, hafif ve tek bir iş yapar: veri toplar ve merkeze gönderir. Karmaşık hesaplama yapmaz, veriyi dönüştürmez — sadece toplar ve iletir. Merkezdeki sistem (SCADA) ise tüm verileri birleştirir, analiz eder ve gösterir.

Beats ailesi Elasticsearch ekosisteminin sensörleri. Her Beat küçük, hafif ve tek bir iş yapar:

  • Filebeat: Log dosyalarını toplar

  • Metricbeat: Sistem ve servis metriklerini toplar

  • Heartbeat: Servis uptime'ını izler

  • Packetbeat: Network trafiğini analiz eder

Logstash gibi ağır bir araç yerine, kaynağın yanında hafif bir Beat çalıştırıp veriyi Elasticsearch'e veya Logstash'e gönderirsiniz.


1. Beats Ailesi Genel Bakış

BeatGörevKaynak Kullanımı
FilebeatLog dosyası toplama~10MB RAM
MetricbeatSistem/servis metrikleri~20MB RAM
HeartbeatUptime monitoring (ping, HTTP, TCP)~15MB RAM
PacketbeatNetwork protokol analizi~30MB RAM
AuditbeatAudit log (Linux audit framework)~20MB RAM
WinlogbeatWindows Event Log~20MB RAM
FunctionbeatServerless (AWS Lambda)Varies

Beats vs Logstash

ÖzellikBeatsLogstash
Kaynak kullanımıÇok düşük (~10-30MB)Yüksek (~1-4GB)
DönüşümMinimal (processor'lar)Maksimum (grok, aggregate)
DeploymentHer sunucuda çalışırMerkezi sunucuda
Veri kaynağıTek tip (log, metric...)Çoklu kaynak

Tipik Mimari

Sunucu 1                    Sunucu 2                    Merkez
┌──────────┐               ┌──────────┐               ┌──────────┐
│ App      │               │ App      │               │          │
│ Filebeat │──────┐        │ Filebeat │──────┐        │          │
│ Metricbeat│──── │        │ Metricbeat│──── │        │          │
└──────────┘     │        └──────────┘     │        │          │
                  ├───→ [Logstash] ──→    │ Elastic- │
                  │     veya doğrudan ──→  │ search   │
                  │                        │          │
Sunucu 3         │        Sunucu 4       │          │
┌──────────┐     │       ┌──────────┐    │ ┌────────┐│
│ Heartbeat│─────┤       │ Packetbeat│───┘ │ Kibana ││
└──────────┘     │       └──────────┘      └────────┘│
                  │                                    │
                  └────────────────────────────────────┘

2. Filebeat — Log Toplama

Filebeat Nedir?

Filebeat log dosyalarını izler, yeni satırları okur ve gönderir. Dosya rotasyonu, multiline log, JSON parsing gibi senaryoları destekler.

Kurulum

# Linux
sudo apt-get install filebeat  # Debian/Ubuntu
sudo yum install filebeat      # RedHat/CentOS

# Docker
docker run -d \
  --name filebeat \
  -v /var/log:/var/log:ro \
  -v /path/to/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro \
  docker.elastic.co/beats/filebeat:8.12.0

Temel Konfigürasyon

# filebeat.yml
filebeat.inputs:

# Nginx access log
- type: filestream
  id: nginx-access
  paths:
    - /var/log/nginx/access.log
  fields:
    service: nginx
    type: access
  fields_under_root: true

# Nginx error log
- type: filestream
  id: nginx-error
  paths:
    - /var/log/nginx/error.log
  fields:
    service: nginx
    type: error
  fields_under_root: true

# Application log (multiline — Java stack trace)
- type: filestream
  id: app-logs
  paths:
    - /var/log/myapp/*.log
  parsers:
    - multiline:
        type: pattern
        pattern: '^\d{4}-\d{2}-\d{2}'
        negate: true
        match: after
  fields:
    service: myapp
  fields_under_root: true

# JSON log
- type: filestream
  id: json-logs
  paths:
    - /var/log/myapp/structured/*.json
  parsers:
    - ndjson:
        target: ""
        add_error_key: true
  fields:
    service: myapp-structured
  fields_under_root: true

# Output — Elasticsearch'e doğrudan
output.elasticsearch:
  hosts: ["https://es-node1:9200", "https://es-node2:9200"]
  username: "filebeat_writer"
  password: "${ES_PASSWORD}"
  ssl.certificate_authorities: ["/etc/filebeat/certs/ca.crt"]
  index: "filebeat-%{[service]}-%{+yyyy.MM.dd}"

# Veya Logstash'e
# output.logstash:
#   hosts: ["logstash:5044"]
#   ssl.certificate_authorities: ["/etc/filebeat/certs/ca.crt"]

# Processors (hafif dönüşüm)
processors:
  - add_host_metadata:
      when.not.contains.tags: forwarded
  - add_cloud_metadata: ~
  - drop_fields:
      fields: ["agent.ephemeral_id", "agent.hostname", "agent.id"]

Filebeat Modules

Yaygın log formatları için hazır modüller:

# Mevcut modülleri listele
filebeat modules list

# Nginx modülünü etkinleştir
filebeat modules enable nginx

# Modül konfigürasyonu
# /etc/filebeat/modules.d/nginx.yml
# modules.d/nginx.yml
- module: nginx
  access:
    enabled: true
    var.paths: ["/var/log/nginx/access.log"]
  error:
    enabled: true
    var.paths: ["/var/log/nginx/error.log"]

Desteklenen modüller:

ModülLog Kaynağı
nginxNginx access/error
apacheApache access/error
systemSyslog, auth log
mysqlMySQL slow/error log
postgresqlPostgreSQL log
dockerDocker container logs
kubernetesK8s pod logs
awsCloudWatch, S3, ELB
kafkaKafka broker logs
elasticsearchES slow log, audit

Filebeat Processors

processors:
  # Field ekleme
  - add_fields:
      target: ''
      fields:
        environment: production
        datacenter: istanbul

  # Conditional drop
  - drop_event:
      when:
        regexp:
          message: "^DEBUG"

  # Field silme
  - drop_fields:
      fields: ["host.os", "agent.version"]

  # Rename
  - rename:
      fields:
        - from: "message"
          to: "log_message"

  # Dissect (grok'un hafif alternatifi)
  - dissect:
      tokenizer: "%{timestamp} [%{level}] %{logger} - %{message}"
      field: "log_message"
      target_prefix: ""

Filebeat Registry ve Veri Güvenliği

Filebeat hangi dosyanın hangi offset'ine kadar okuduğunu registry dosyasında tutar:

# Registry path
filebeat.registry.path: /var/lib/filebeat/registry

# Flush interval (ne sıklıkla diske yazılsın)
filebeat.registry.flush: 1s

Bu sayede Filebeat restart edildiğinde kaldığı yerden devam eder — veri kaybı yok, duplicate yok.


3. Metricbeat — Sistem ve Servis Metrikleri

Metricbeat Nedir?

Metricbeat, sistem (CPU, memory, disk, network) ve servis (Nginx, MySQL, Docker, Kubernetes) metriklerini periyodik olarak toplar.

Temel Konfigürasyon

# metricbeat.yml

# Sistem metrikleri
metricbeat.modules:

- module: system
  metricsets:
    - cpu
    - load
    - memory
    - network
    - process
    - process_summary
    - socket_summary
    - filesystem
    - diskio
  period: 10s
  processes: ['.*']
  cpu.metrics: [percentages, normalized_percentages]

# Docker metrikleri
- module: docker
  metricsets:
    - container
    - cpu
    - diskio
    - healthcheck
    - info
    - memory
    - network
  hosts: ["unix:///var/run/docker.sock"]
  period: 10s

# Nginx metrikleri
- module: nginx
  metricsets: ["stubstatus"]
  period: 10s
  hosts: ["http://localhost:80"]
  server_status_path: "nginx_status"

# MySQL metrikleri
- module: mysql
  metricsets: ["status", "galera_status"]
  period: 10s
  hosts: ["tcp(localhost:3306)/"]
  username: "metricbeat_reader"
  password: "${MYSQL_PASSWORD}"

# Elasticsearch metrikleri
- module: elasticsearch
  metricsets:
    - node
    - node_stats
    - index
    - index_recovery
    - index_summary
    - shard
    - cluster_stats
  period: 10s
  hosts: ["https://localhost:9200"]
  username: "monitoring_user"
  password: "${ES_PASSWORD}"

# Redis metrikleri
- module: redis
  metricsets: ["info", "keyspace"]
  period: 10s
  hosts: ["localhost:6379"]
  password: "${REDIS_PASSWORD}"

output.elasticsearch:
  hosts: ["https://es-monitoring:9200"]
  username: "metricbeat_writer"
  password: "${ES_PASSWORD}"
  index: "metricbeat-%{+yyyy.MM.dd}"

Kubernetes Metrikleri

- module: kubernetes
  metricsets:
    - node
    - system
    - pod
    - container
    - volume
  period: 10s
  host: ${NODE_NAME}
  hosts: ["https://${NODE_NAME}:10250"]
  bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
  ssl.verification_mode: none

# State metrics (kube-state-metrics üzerinden)
- module: kubernetes
  metricsets:
    - state_node
    - state_deployment
    - state_replicaset
    - state_pod
    - state_container
  period: 10s
  hosts: ["kube-state-metrics:8080"]

Metricbeat ile Dashboard

Metricbeat kurulduğunda hazır Kibana dashboard'ları yükleyebilirsiniz:

# Dashboard'ları Kibana'ya yükle
metricbeat setup --dashboards

# Sadece index template yükle
metricbeat setup --index-management

# Sadece Kibana dashboard yükle
metricbeat setup -E output.elasticsearch.enabled=false \
  -E setup.kibana.host=http://kibana:5601 \
  --dashboards

4. Heartbeat — Uptime Monitoring

Heartbeat Nedir?

Heartbeat, servislerinizin "canlı mı?" sorusunu cevaplar. HTTP, TCP veya ICMP ile periyodik kontrol yapar.

Konfigürasyon

# heartbeat.yml

heartbeat.monitors:

# HTTP monitor — Web sitesi kontrolü
- type: http
  id: website-check
  name: "Company Website"
  urls:
    - "https://www.company.com"
    - "https://api.company.com/health"
  schedule: "@every 30s"
  timeout: 10s
  check.response:
    status: [200]
    body:
      - "ok"
      - "healthy"
  ssl:
    certificate_authorities: ["/etc/heartbeat/certs/ca.crt"]

# HTTP monitor — API endpoint
- type: http
  id: api-health
  name: "Auth API"
  urls: ["https://api.company.com/v1/health"]
  schedule: "@every 10s"
  timeout: 5s
  check.response:
    status: [200]
    json:
      - description: "status is up"
        condition:
          equals:
            status: "UP"

# TCP monitor — Database bağlantı kontrolü
- type: tcp
  id: db-check
  name: "PostgreSQL"
  hosts: ["db-primary:5432", "db-replica:5432"]
  schedule: "@every 15s"
  timeout: 5s

# TCP monitor — Redis
- type: tcp
  id: redis-check
  name: "Redis Cache"
  hosts: ["redis-1:6379", "redis-2:6379"]
  schedule: "@every 10s"

# ICMP monitor — Ping
- type: icmp
  id: network-check
  name: "Network Connectivity"
  hosts: ["gateway.internal", "dns.internal"]
  schedule: "@every 30s"
  timeout: 5s

output.elasticsearch:
  hosts: ["https://es:9200"]
  username: "heartbeat_writer"
  password: "${ES_PASSWORD}"

Heartbeat Dashboard

Heartbeat verileri Kibana'nın Uptime (veya Synthetics) bölümünde gösterilir:

Sol menü → Observability → Uptime

# Görüntülenen bilgiler:
# - Monitor listesi (up/down durumu)
# - Availability yüzdesi
# - Response time trendi
# - TLS sertifika durumu (son kullanma tarihi)
# - Lokasyon bazlı sonuçlar

Synthetic Monitoring (Browser Tests)

Heartbeat ile tarayıcı bazlı test de yapılabilir:

- type: browser
  id: checkout-flow
  name: "E-Commerce Checkout Flow"
  schedule: "@every 5m"
  source:
    inline:
      script: |
        step('Go to homepage', async () => {
          await page.goto('https://shop.company.com');
        });
        step('Search product', async () => {
          await page.fill('#search', 'laptop');
          await page.click('#search-btn');
        });
        step('Add to cart', async () => {
          await page.click('.product-card:first-child .add-to-cart');
        });
        step('Verify cart', async () => {
          const cartCount = await page.textContent('.cart-count');
          expect(cartCount).toBe('1');
        });

5. Packetbeat — Network Trafiği Analizi

Packetbeat Nedir?

Packetbeat, network paketlerini yakalar ve uygulama katmanı protokollerini analiz eder. HTTP, MySQL, PostgreSQL, Redis, DNS gibi protokolleri otomatik tanır.

Konfigürasyon

# packetbeat.yml

# Network interface
packetbeat.interfaces.device: any

# Protokoller
packetbeat.protocols:

# HTTP trafiği
- type: http
  ports: [80, 8080, 8443]
  send_request: true
  include_body_for: ["application/json"]
  send_response: true
  include_body_for: ["application/json"]
  max_message_size: 10485760  # 10MB

# MySQL trafiği
- type: mysql
  ports: [3306]
  send_request: true
  send_response: true

# PostgreSQL trafiği
- type: pgsql
  ports: [5432]
  send_request: true
  send_response: true

# Redis trafiği
- type: redis
  ports: [6379]
  send_request: true
  send_response: true

# DNS trafiği
- type: dns
  ports: [53]
  send_request: true
  send_response: true

# TLS trafiği (sertifika bilgileri)
- type: tls
  ports: [443, 8443]

# Flow monitoring
packetbeat.flows:
  timeout: 30s
  period: 10s

output.elasticsearch:
  hosts: ["https://es:9200"]
  username: "packetbeat_writer"
  password: "${ES_PASSWORD}"

processors:
  - add_host_metadata: ~
  - add_cloud_metadata: ~

Packetbeat ile Görülebilecekler

AnalizKullanım
HTTP response timeEn yavaş endpoint'ler
SQL sorgularıYavaş sorgular, N+1 tespiti
DNS çözümlemeYavaş DNS, başarısız çözümlemeler
TLS sertifikalarSüresi dolan sertifikalar
Network flowServisler arası trafik haritası
Redis komutlarıEn sık çağrılan key'ler, yavaş komutlar

6. Beats Ortak Konfigürasyon

Output Ayarları

# Elasticsearch'e doğrudan (basit senaryo)
output.elasticsearch:
  hosts: ["https://es1:9200", "https://es2:9200"]
  loadbalance: true
  username: "beat_writer"
  password: "${ES_PASSWORD}"
  ssl.certificate_authorities: ["/etc/beats/certs/ca.crt"]
  bulk_max_size: 50
  compression_level: 3
  worker: 2

# Logstash'e (karmaşık dönüşüm gerekiyorsa)
# output.logstash:
#   hosts: ["logstash1:5044", "logstash2:5044"]
#   loadbalance: true
#   ssl.certificate_authorities: ["/etc/beats/certs/ca.crt"]

# Kafka'ya (buffer katmanı)
# output.kafka:
#   hosts: ["kafka1:9092", "kafka2:9092"]
#   topic: "beats-%{[agent.type]}"
#   codec.format.string: '%{[message]}'

Logging Ayarları

logging.level: info
logging.to_files: true
logging.files:
  path: /var/log/beats
  name: filebeat
  keepfiles: 7
  permissions: 0644

ILM (Index Lifecycle Management) Ayarları

setup.ilm.enabled: true
setup.ilm.rollover_alias: "filebeat"
setup.ilm.pattern: "{now/d}-000001"
setup.ilm.policy_name: "filebeat"

Autodiscover (Kubernetes/Docker)

# Docker autodiscover
filebeat.autodiscover:
  providers:
    - type: docker
      hints.enabled: true
      hints.default_config:
        type: container
        paths:
          - /var/lib/docker/containers/${data.container.id}/*.log

# Kubernetes autodiscover
filebeat.autodiscover:
  providers:
    - type: kubernetes
      hints.enabled: true
      hints.default_config:
        type: container
        paths:
          - /var/log/containers/*-${data.container.id}.log

Pod annotation'ları ile container başına konfigürasyon:

# Kubernetes Pod annotation'ları
metadata:
  annotations:
    co.elastic.logs/module: nginx
    co.elastic.logs/fileset.stdout: access
    co.elastic.logs/fileset.stderr: error
    co.elastic.metrics/module: prometheus
    co.elastic.metrics/hosts: "${data.host}:9090"

7. Elastic Agent — Beats'in Geleceği

Elastic 7.x+ ile tanıtılan Elastic Agent, tüm Beat'leri tek bir agent'ta birleştiren yeni yaklaşım:

Elastic Agent vs Individual Beats

ÖzellikIndividual BeatsElastic Agent
DeploymentHer Beat ayrı kurulurTek agent
YönetimHer Beat ayrı konfigüreFleet'ten merkezi yönetim
GüncellemeHer Beat ayrı güncellenirTek güncelleme
PolicyDosya bazlı konfigürasyonFleet policy
IntegrationModule bazlıIntegration bazlı

Fleet ile Merkezi Yönetim

Kibana → Fleet → Agent Policies

1. Policy oluştur: "Production Servers"
2. Integration ekle:
   - System (CPU, memory, disk, network)
   - Nginx (access, error log)
   - Docker (container metrics)
3. Agent'ları enroll et
4. Tüm agent'lar merkezi policy'yi alır
# Elastic Agent kurulum ve enrollment
sudo elastic-agent enroll \
  --url=https://fleet-server:8220 \
  --enrollment-token=<token> \
  --certificate-authorities=/etc/elastic-agent/certs/ca.crt

sudo systemctl start elastic-agent

8. Bütünleşik Örnek: Full Observability Stack

Bir web uygulaması için tam monitoring çözümü:

# === Sunucu 1: Web Server ===

# filebeat.yml — Nginx logları
filebeat.inputs:
- type: filestream
  id: nginx-access
  paths: ["/var/log/nginx/access.log"]
  fields: { service: "nginx", type: "access" }
  fields_under_root: true

output.elasticsearch:
  hosts: ["https://es:9200"]
  index: "logs-nginx-%{+yyyy.MM.dd}"

---

# metricbeat.yml — Sistem + Nginx metrikleri
metricbeat.modules:
- module: system
  metricsets: [cpu, memory, network, filesystem, diskio]
  period: 10s

- module: nginx
  metricsets: [stubstatus]
  period: 10s
  hosts: ["http://localhost:80"]

output.elasticsearch:
  hosts: ["https://es:9200"]
  index: "metrics-%{[event.module]}-%{+yyyy.MM.dd}"

---

# === Monitoring Server ===

# heartbeat.yml — Uptime monitoring
heartbeat.monitors:
- type: http
  id: web-check
  name: "Web Application"
  urls: ["https://www.myapp.com/health"]
  schedule: "@every 10s"
  check.response.status: [200]

- type: tcp
  id: db-check
  name: "PostgreSQL"
  hosts: ["db:5432"]
  schedule: "@every 15s"

output.elasticsearch:
  hosts: ["https://es:9200"]
  index: "heartbeat-%{+yyyy.MM.dd}"

---

# === Network Server ===

# packetbeat.yml — Network analizi
packetbeat.interfaces.device: eth0
packetbeat.protocols:
- type: http
  ports: [80, 8080]
- type: pgsql
  ports: [5432]
- type: redis
  ports: [6379]

output.elasticsearch:
  hosts: ["https://es:9200"]
  index: "packetbeat-%{+yyyy.MM.dd}"

9. Best Practices

✅ Yap

KonuÖneri
Beat seçimiBasit log → Filebeat, dönüşüm gerekli → Filebeat + Logstash
Module kullanHazır modüller parsing/dashboard yükü azaltır
AutodiscoverK8s/Docker ortamlarında autodiscover kullan
ILMBeat index'leri için ILM policy tanımla
SSLBeats → ES/Logstash arası TLS zorunlu
Dashboardbeat setup --dashboards ile hazır dashboard'ları yükle

❌ Yapma

KonuNeden
Filebeat'te ağır dönüşümBeats hafif olmalı, dönüşümü Logstash'e bırak
Tüm field'ları göndermedrop_fields ile gereksizleri at
Output olmadan debug logDisk dolar, Beat çöker
Beat'i root'suz çalıştırma (log okuma)Dosya izni hatası alırsın
Beat versiyon uyumsuzluğuBeat versiyonu ES versiyonuyla uyumlu olmalı

10. Yaygın Hatalar ve Çözümleri

Hata 1: "Filebeat Log Okumuyor"

# Kontrol 1: Dosya izinleri
ls -la /var/log/nginx/access.log
# filebeat kullanıcısının okuma izni olmalı

# Kontrol 2: Registry kontrolü
cat /var/lib/filebeat/registry/filebeat/log.json | jq .

# Kontrol 3: Filebeat log
journalctl -u filebeat -f
# "Harvester started" mesajını ara

# Çözüm: Registry sıfırla (dikkat — duplicate veri olabilir)
sudo systemctl stop filebeat
sudo rm -rf /var/lib/filebeat/registry
sudo systemctl start filebeat

Hata 2: "Metricbeat Connection Refused"

# Sorun: Metricbeat MySQL/Redis'e bağlanamıyor
# Kontrol: Host ve port doğru mu?
# Çözüm: Servis-specific user oluştur

# MySQL:
# CREATE USER 'metricbeat'@'localhost' IDENTIFIED BY 'pass';
# GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'metricbeat'@'localhost';

Hata 3: "Output Blocked"

# Sorun: Beat veri gönderemiyor, queue doluyor
# Kontrol:
# - ES cluster health
# - Network connectivity
# - SSL sertifika süresi

# Çözüm: Output worker ve bulk size ayarla
output.elasticsearch:
  worker: 4
  bulk_max_size: 100
  timeout: 90

Özet

  1. Beats hafif veri toplayıcılar — her sunucuda çalışır, minimal kaynak tüketir (~10-30MB RAM).

  2. Filebeat log dosyası toplama için standart — modüller ile Nginx, Apache, MySQL gibi yaygın log formatları hazır desteklenir.

  3. Metricbeat sistem ve servis metrikleri toplar — CPU, memory, disk + MySQL, Redis, Docker, Kubernetes metrikleri.

  4. Heartbeat uptime monitoring için — HTTP, TCP, ICMP ile servislerin canlılığını kontrol eder ve SLA raporları oluşturur.

  5. Packetbeat network trafiğini analiz eder — HTTP, SQL, DNS, Redis protokollerini otomatik tanır ve performans sorunlarını ortaya çıkarır.

  6. Elastic Agent Beats'in geleceği — tüm Beat'leri tek agent'ta birleştirir, Fleet ile merkezi yönetim sağlar.