본문 바로가기
Infra

Spring Boot Fluentd AWS S3 연동

by whitele 2024. 8. 20.
반응형

Spring Boot Fluentd 연동

흔히 모니터링으로 Spring actuator+Prometheus+Grafana나 ELK가 있습니다. 이외 다양한 오픈소스들이 있습니다. fluentd는 logstash를 대체하여 EFK로도 활용됩니다. fluentd의 장점으로는 매우 경량화되어 있으며 다른 시스템과 결합하여 통합적인 로그 모니터링(DB 등)과 경량화된 프로그램으로 매우 저렴한 비용에 로그를 수집할 수 있습니다.

여기에서는 spring boot와 fluent를 연동한뒤 AWS S3를 저장하는 예시를 작성하였습니다.

Fluentd 설정

Fluentd설치

mac 기준으로 작성하였습니다. 직접 fluent 공식페이지에서 다운로드하여 사용할 수 있습니다. mac을 사용하여 mac homebrew를 이용하여 사용합니다.

brew install td-agent

이후 fluent-gem을 이용하여 fluent-plugin-s3를 설치합니다. 보통 td-agent를 설치하면 /opt/td-agent/bin 폴더 내에 설치됩니다. 추가적으로 chmod +x fluent-gem을 해주어야 할 수 있습니다.

sudo /opt/td-agent/bin/fluent-gem install fluent-plugin-s3

fluent.conf 작성

작업환경 루트디렉터리에서 해당 fluent.conf 파일을 작성합니다. ${value}로 되어있는 곳은 모두 값을 채워줘야 합니다.

fluent output 예시
| https://docs.fluentd.org/output/file
| https://docs.fluentd.org/output/s3

<source>
  @type forward
  port 24224
  bind 0.0.0.0
</source>

<match springboot.**>
  @type s3

  aws_key_id ${AWS_ACCESS_KEY_ID}
  aws_sec_key ${AWS_SECRET_ACCESS_KEY}
  s3_bucket ${S3_BUCKET_NAME}
  s3_region ${S3_REGION}
  path logs/
  s3_object_key_format %{path}%{time_slice}_%{index}.log

  <format>
    @type json
  </format>

  <buffer>
    @type file
    path /var/log/fluent/s3
    timekey 1h  # 1시간 단위로 로그 파일을 나눔
    timekey_wait 10m  # 로그 전송 대기 시간
    timekey_use_utc true  # UTC 시간 사용
  </buffer>
</match>

fluent.conf를 다음과 같이 작성합니다.

s3를 사용할 경우 반드시 @type s3를 포함하여 작성합니다. 이후 aws키, 버킷 저장소, 리전을 지정합니다. 버킷 내 특정 경로를 사용하고 싶다면 path를 변경합니다. path의 기본값은 “”입니다.

s3_object_key_format는 실제 path의 저장될 형식을 지정합니다.

path는 앞서 지정했던 경로 time_slice는 버퍼 설정에 지정된 타임 스트링입니다.

index 주어진 경로에 대한 인덱스. 버퍼 플러시당 증가합니다.

format의 경우 json을 사용합니다. @type json을 사용합니다.

만약 더 다양한 csv 등 다른 포맷을 지원하고 싶다면 https://docs.fluentd.org/formatter 해당 문서를 참조하면 됩니다.

buffer

s3 같은 저장소를 이용할 때 주로 사용합니다. 이 예시의 경우 s3를 사용하였으므로 버퍼 플러그인을 사용합니다.

s3로 전송하기 전 스트림을 일시적으로 저장합니다.

timekeyFluentd가 로그를 1시간 단위로 분할해 버퍼에 저장하는 시간 주기입니다. 즉, 로그가 수신되면 해당 시간을 기준으로 1시간 단위로 나누어 파일을 생성합니다

timekey_wait 은 설정한 시간으로부터 지난 뒤 얼마나 대기가 가능한지 설정하는 시간입니다. 여기에서는 1h뒤 10분까지 더 로그를 수집하다 전송합니다.

버퍼에 관한 더 자세한 설정은 다음 문서를 참조하면 됩니다. https://docs.fluentd.org/buffer

스프링 작업

의존성

의존성은 다음과 같이 설정합니다.

boot-starter-web에 logback 관련이 있지만 logback을 추가로 넣어줍니다. fluent-logger와 logback-more-appenders를 필수로 추가합니다.

logback-spring.xml 작성

resources디렉터리 내에 logback-spring.xml을 작성합니다.

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
        <remoteHost>localhost</remoteHost> <!-- Fluentd가 실행 중인 호스트 -->
        <port>24224</port> <!-- Fluentd 포트 -->
        <tag>springboot</tag> <!-- 로그 태그 -->

        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d %-5level %logger{35} - %msg%n</Pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="Console"/>
        <appender-ref ref="FLUENT"/>
    </root>
</configuration>

콘솔과 Fluent로 보내는 logback 설정을 하는 파일입니다.

이후 fluentd를 전역에서 사용하기 위한 환경 변수를 추가합니다. 굳이 추가하지 않고 bin폴더 내에서 직접 실행하여도 되지만 편의상 추가합니다.

nano ~/.zshrc

줄에 해당 코드 추가

export PATH=$PATH:/opt/td-agent/bin
source ~/.azhrc

이제 fluentd를 먼저 실행한 뒤 그 후에 spring boot 앱을 실행합니다.

fluentd -c ./fluent.conf

-c는 지정된 conf파일을 이용하는 명령어입니다.

이후 fluentd 실행 후 springboot앱을 실행했다면 버퍼 시간 이후에 AWS S3를 확인하면 제대로 저장된 걸 확인할 수 있습니다.

728x90
반응형

댓글