logstash로 nginx 로그 수집하기 (ELK)

2021. 9. 10. 12:00util

적용 사유

이전에는 ELK를 사용할때 nginx로그 수집을 filebeat로 했었다. 그런 이유는 아래와 같다.

 

1. 구축난의도가 쉽다. (kibana 접속하여 "add data" 들어갈경우 자세하게 알려줌)

2. 모듈형식이라 유지보수할게 거의 없다.

3. 메모리를 적게 사용한다. (사실 이럴경우 flunted, flunted-bit를 사용하면 되지만 설정값을 찾는게 어려웠다. 또한 설치된 앱의 이름이 실제 td-agent 라서 실제 구축한 사람이 아니면 다른사람들은 기억하기 어려울수 있다 생각했다.)

 

 

그러나 nginx 로그를 logstash로 변경한 이유는 아래와 같다.

 

1. aws의 Amazon opensearch service (구 Amazon elasticsearch) 로 서비스를 옮기면서 open distro for elasticsearch에서 filebeat oss 버전을 깔았지만 모듈 enable 후 elasticsearch와 연동 할경우 실패가 된다.
(이건 스택오버플로우나 다른곳을 봤을때 아마존 정책상 http 통신을 막아서 그런다고함, 그리고 정책을 풀거나 filebeat 로그를 logstsh로 보낸다음 받으면 된다는데 실제 받는 로그의 차이가 있을것 같다.)

 

2. 현재 그냥 서로 연동을 안하고 통신을 통해 로그만 보내서 인스턴스의 정보는 보이되 원래 filebeat에서 보내줘야할 nginx로그를 수집하지 못함

 

 

적용 방법

※ ubuntu 에서 작업을 했다.

1. filebeat를 정지 시킨다.

2. 버전에 맞는 logstash oss 버전을 설치 한다. (https://www.elastic.co/kr/downloads/past-releases#logstash-oss)

3. /etc/nginx/nginx.conf 에 아래의 설정을 넣어준다. (http 안에 넣었음, 구글에 nginx format 치면 많이 나온다.)

# 1. nginx 로그를 json 타입으로 format
	log_format json_format escape=json '{"time": "$time_iso8601", '
      	'"remote-ip": "$remote_addr", '    #aws LB IP
        '"request-time": "$request_time", '
        '"request-status": "$status", '
        '"request-method" : "$request_method", '
        '"request": "$request", '
        '"body-bytes": "$body_bytes_sent", '
        '"user-agent": "$http_user_agent", '
        '"client-ip": "$http_x_forwarded_for", '
        '"document-root": "$document_root", '
        '"request-uri": "$request_uri", '
        '"server-ip": "$server_addr", '
        '"server-DNS": "$http_host", '
        '"server-port": "$server_port", '
        '"server-protocol": "$server_protocol", '
        '"request-body": "$request_body", '
        '"request-parameter": "$args", '
        '"uri": "$uri", '
        '"referrer": "$http_referer" }';
access_log /var/log/nginx/access.log upstream_time;
error_log /var/log/nginx/error.log;

# 2. logstash용 nginx 파일을 json_format 포맷으로 추가 생성
access_log /var/log/nginx/access_json.log json_format;

 

4. /etc/logstash/conf.d/ 에다가 설정 파일을 만든다.

sudo vi nginx-log.conf
input {
    file {
        path => "/var/log/nginx/access_json.log"
        type => nginx
        codec => json
    }
}
output {
  elasticsearch {
    hosts => ["https://elasticsearch-url"]
    ssl => true
    index => "nginx-log"
    user => "elastic"
    password => "elastic"
    ilm_enabled => false
  }
}

 

5. nginx, logstash 를 재시작 한다.