[ELK Stack] 3. Filebeat와 ELK Stack으로 Apache log 관리
IT/Etc

[ELK Stack] 3. Filebeat와 ELK Stack으로 Apache log 관리

728x90
반응형

ELK Stack 목차

 

1. Filebeat 란?

log파일을 Logstash로 수집하지 않고 Filebeat를 사용하는 이유는 경량화되어 data 수집 및 전달에 최적화되어있기 때문이다.

(Filebeat는 Logstash보다 시스템 공간과 사용 공간이 적기 때문에 더 적은 리소스를 요구한다.)

 

 

Filebeat는 크게 Prospector, Harvester, Spooler로 이루어져 있다.

Prospector는 읽어야 할 소스를 식별하고 구분하는 역할을 한다. log, stdin 타입을 지원하며 Prospector 당 2개 이상의 type 선언이 가능하며, 어디까지 읽었는지 meta data를 별도 디스크에 저장한다. (default : /var/lib/filebeat/registry)

Harvester는 파일을 읽고 출력하는 역할을 한다. 하나의 Harvester가 각각 하나의 파일을 담당하는 구조를 가진다. 파일을 열고 닫는 것까지 담당하기 때문에 Harvester가 실행되고 있다는 것은 file descriptor가 남아 있다는 의미이다.

Spooler는 Harvester가 읽은 데이터를 집계하고 각각 설정한 output으로 전달한다.

 

2. Apache 설치

2.1 apache 설치

$ sudo yum -y install httpd

 

2.2 apache 설치 확인

$ httpd -v

 

2.3 apache 실행

$ sudo systemctl start httpd

 

2.4 apache web service 접근

 

2.5 apache access log 확인

$ tail -f /var/log/httpd/access_log

 

3. Filebeat 설치

3.1. Import the Elasticsearch GPG Key

공개 서명키 (public signing key) 설치

$ sudo rpm --import https://packages.elastic.co/GPG-KEY-elasticsearch

 

3.2 Filebeat 설치

/etc/yum.repos.d/ 디렉토리 아래에 Elastic.repo 파일을 만들고 아래와 같이 내용을 입력한다.

$ vi /etc/yum.repos.d/Elastic.repo
    [elastic-7.x]
    name=Elasticsearch repository for 7.x packages
    baseurl=https://artifacts.elastic.co/packages/7.x/yum
    gpgcheck=1
    gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
    enabled=1
    autorefresh=1
    type=rpm-md

 

파일을 추가한 후 yum명령을 이용해 filebeat 설치한다.

$ sudo yum -y install filebeat

 

3.3 Filebeat module list 확인

$ filebeat modules list

 

4. Filebeat 설정

Filebeat를 이용하여 apache log를 수집하고 logstash 또는 elasticsearch에 보내는 방법은 크게 2가지가 있다.

 

4.1 Enable apache module

첫 번째는 filebeat에서 제공하는 apache 모듈을 이용하는 것이다.

# apache module 활성화
$ filebeat modules enable apache

$ filebeat modules list

 

apache 모듈을 활성화시킨 후 초기 환경을 셋팅한다.

$ filebeat setup -e  # -e : debug mode

 

이후 /etc/filebeat/modules.d/apache.yml 파일을 아래와 같이 수정한다.

$ vi /etc/filebeat/modules.d/apache.yml
# Module: apache
# Docs: https://www.elastic.co/guide/en/beats/filebeat/7.10/filebeat-module-apache.html

- module: apache
  # Access logs
  access:
    enabled: true
    input:
      fields:
        server_name: elk-web
        log_type: apache_access
    var.paths: ["/var/log/httpd/access_log"]

    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    #var.paths:

  # Error logs
  error:
    enabled: true
    input:
      fields:
        server_name: elk-web
        log_type: apache_error
    var.paths: ["/var/log/httpd/error_log"]

    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    #var.paths:

 

하지만 우리는 apache module을 사용하지 않고 filebeat.yml 파일을 직접 수정하여 log를 수집할 것이다.

이를 위해 위에서 활성화한 apache module은 다시 비활성화 해주자.

$ filebeat modules disable apache

 

4.2 Configuration filebeat.yml

/etc/filebeat/filebeat.yml 파일을 아래와 같이 설정한다.

 

Inputs

# ============================== Filebeat inputs ===============================

filebeat.inputs:

# Each - is an input. Most options can be set at the input level, so
# you can use different inputs for various configurations.
# Below are the input specific configurations.

- type: log
  # Change to true to enable this input configuration.
  enabled: true

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - /var/log/httpd/access_log
    #- c:\programdata\elasticsearch\logs\*

  # Exclude lines. A list of regular expressions to match. It drops the lines that are
  # matching any regular expression from the list.
  #exclude_lines: ['^DBG']

  # Include lines. A list of regular expressions to match. It exports the lines that are
  # matching any regular expression from the list.
  #include_lines: ['^ERR', '^WARN']

  # Exclude files. A list of regular expressions to match. Filebeat drops the files that
  # are matching any regular expression from the list. By default, no files are dropped.
  #exclude_files: ['.gz$']

  # Optional additional fields. These fields can be freely picked
  # to add additional information to the crawled log files for filtering
  fields:
    server_name: elk-web
    log_type: apache-access
  #fields:
  #  level: debug
  #  review: 1

fields의 항목은 output으로 보낼 때 추가한 필드를 포함하여 보낸다.

나중에 Kibana에서 해당 필드 키워드를 이용하여 data를 컨트롤할 수 있다.

 

Outputs

# ================================== Outputs ===================================

# Configure what output to use when sending the data collected by the beat.

# ---------------------------- Elasticsearch Output ----------------------------
#output.elasticsearch:
  # Array of hosts to connect to.
  #hosts: ["localhost:9200"]

  # Protocol - either `http` (default) or `https`.
  #protocol: "https"

  # Authentication credentials - either API key or username/password.
  #api_key: "id:api_key"
  #username: "elastic"
  #password: "changeme"

# ------------------------------ Logstash Output -------------------------------
output.logstash:
  # The Logstash hosts
  hosts: ["3.35.108.182:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

  # Client Certificate Key
  #ssl.key: "/etc/pki/client/cert.key"

elasticsearch output을 주석 처리하고 logstash output을 활성화한다.

hosts는 elk-master 서버의 IP로 설정한다.

hosts에는 여러 노드를 입력할 수 있으며, 각각의 host에서 data를 균등하게 보내고 싶다면 loadbalance: true 설정을 넣어주면 된다.

 

5. Run Filebeat

systemd 기준

$ sudo systemctl start filebeat

 

Filebeat 데몬 로그 확인

$ tail -f /var/log/filebeat/filebeat

 

6. Logstash 파이프라인 설정

/etc/logstash/conf.d/filebeats.conf를 아래와 같이 설정한다.

$ vi /etc/logstash/conf.d/filebeats.conf
input {
  beats {
    port => 5044
  }
}
filter {
  grok {
    match => { "message" => "%{TIMESTAMP_ISO8601:time}\t%{DATA:tag}\t{ % {DATA:data} }" }
  }
  mutate {
    add_field => { "json_data" => "{ %{data}}" }
  }
  json {
    source => "json_data"
  }
  alter {
    remove_field => [ "data", "json_data" ]
  }
  date {
    match => [ "time", "yyyy-MM-dd'T'HH:mm:ssZZ" ]
  }
}
output {
  elasticsearch {
    hosts => "localhost:9200"
    index => "%{[fields][log_type]}-%{+YYYY.MM.dd}"
  }
}

filter에서 grok 등의 패턴을 이용하여 메시지를 가공할 수 있지만 일단 test를 위해 filter 없이 bypass 시켜보자.

 

7. Logstash 실행

$ sh /usr/share/logstash/bin/logstash -f /etc/logstash/conf.d/filebeats.conf

 

8. Elasticsearch index 생성 확인

$ curl localhost:9200/_cat/indices?v

 

9. Kibana 확인

9.1 Kibana index pattern 생성

index pattern을 검색하면 방금 생성한 apache-access-2021.02.08이 확인된다.

 

@timestamp 필드를 설정하고 최종 생성을 한다.

 

만들어진 Index Patterns에 아까 filebeat.yml에서 설정한 2개의 fields값이 포함되어 있는 것을 확인할 수 있다. (log_type, server_name)

 

9.2 Kibana 데이터 탐색 및 조회

Discover 메뉴로 진입하면 elk-web 서버의 apache access_log를 수집한 것을 확인할 수 있다.

 

message field를 확인해보자.

 

 

Reference

728x90
반응형