[모니터링] prometheus, loki, grafana

남순식·2026년 4월 10일

스프링 부트 모니터링 시스템 구축: Prometheus, Grafana, Loki

서비스의 안정적인 운영을 위해서는 시스템 내부의 메트릭과 로그를 가시화하는 것이 필수적이다. 이를 위해 가장 많이 사용되는 조합인 Prometheus, Grafana, Loki의 구축 방법과 핵심 코드를 정리한다.

1. Prometheus: 메트릭 수집 및 저장

Prometheus는 애플리케이션의 상태(CPU, 메모리, HTTP 요청 수 등)를 숫자 형태의 메트릭으로 수집하여 저장한다.

애플리케이션 설정 (Spring Boot)

build.gradle

// build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'io.micrometer:micrometer-registry-prometheus'
}

application.yml

spring:
  application:
    name: sample

server:
  port: 8080

management:
  endpoint:
    health:
      show-details: always
    prometheus:
      access: unrestricted
  endpoints:
    web:
      exposure:
        include: "*"

Prometheus 서버 설정 (prometheus.yml)

Prometheus가 어느 주소에서 데이터를 가져갈지 설정한다.

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'spring-boot'
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['host.docker.internal:8080']

이후

docker run -d --name=prometheus -p 9090:9090 -v ${prometheus.yml이 있는 경로}/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus;  

2. Loki: 로그 집계 및 통합

Loki는 텍스트 로그를 수집하며, Prometheus와 유사한 라벨링 구조를 사용하여 로그를 효율적으로 관리한다.

Logback 설정 (logback.xml)

loki-logback-appender를 사용하여 애플리케이션의 로그를 직접 Loki로 전송한다.

build.gradle 추가

implementation 'com.github.loki4j:loki-logback-appender:1.5.1'

logback.xml
예시)

<configuration>
  <appender name="LOKI" class="com.github.loki4j.logback.Loki4jAppender">
    <http>
      <url>http://localhost:3100/loki/api/v1/push</url>
    </http>
    <format>
      <label>
        <pattern>app=my-app,host=${HOSTNAME}</pattern>
      </label>
      <message class="com.github.loki4j.logback.JsonLayout" />
    </format>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="LOKI" />
  </root>
</configuration>

loki-config.yml

auth_enabled: false

server:
  http_listen_port: 3100
  grpc_listen_port: 9096

common:
  instance_addr: 127.0.0.1
  path_prefix: /tmp/loki
  storage:
    filesystem:
      chunks_directory: /tmp/loki/chunks
      rules_directory: /tmp/loki/rules
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory

query_range:
  results_cache:
    cache:
      embedded_cache:
        enabled: true
        max_size_mb: 100

schema_config:
  configs:
    - from: 2020-10-24
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

ruler:
  alertmanager_url: http://localhost:9093

# By default, Loki will send anonymous, but uniquely-identifiable usage and configuration
# analytics to Grafana Labs. These statistics are sent to https://stats.grafana.org/
#
# Statistics help us better understand how Loki is used, and they show us performance
# levels for most users. This helps us prioritize features and documentation.
# For more information on what's sent, look at
# https://github.com/grafana/loki/blob/main/pkg/analytics/stats.go
# Refer to the buildReport method to see what goes into a report.
#
# If you would like to disable reporting, uncomment the following lines:
#analytics:
#  reporting_enabled: false

loki 실행

docker run --name loki -d -v ${loki-config.yml 이 저장된 폴더}:/mnt/config -p 3100:3100 grafana/loki:3.0.0 -config.file=/mnt/config/loki-config.yml

3. Grafana: 데이터 시각화 및 알림

Prometheus의 메트릭과 Loki의 로그를 하나의 대시보드에서 통합하여 보여준다.

구축 요약

도구사용 이유핵심 사용법
Prometheus숫자 기반 상태 데이터 저장Actuator 연동 및 up, http_requests_total 등 쿼리 사용
Loki텍스트 기반 로그 데이터 저장Logback 앱엔더 설정 및 {app="delivery-service"} 라벨 쿼리 사용
Grafana데이터 통합 시각화Data Source 등록(Prometheus, Loki) 및 대시보드 구성

종합

모니터링 시스템 구축 시 가장 유의해야 할 점은 보안이다. Spring Boot Actuator는 힙 덤프나 환경 변수 등 민감한 정보를 노출할 수 있으므로 반드시 다음과 같은 조치가 병행되어야 한다.

  • 포트 분리: 서비스 포트와 모니터링 포트를 물리적으로 분리한다.
  • IP 화이트리스팅: Prometheus 서버의 IP만 모니터링 엔드포인트에 접근할 수 있도록 방화벽 설정을 적용한다.
  • 로그 마스킹: Loki로 전송되는 로그에 개인정보나 비밀번호가 포함되지 않도록 Logback 설정 단계에서 필터링을 강화한다.

이러한 모니터링 체계는 단순히 장애를 확인하는 용도를 넘어, 시스템의 트래픽 패턴을 분석하고 인프라 확장(Scaling) 시점을 결정하는 중요한 근거 데이터가 된다.

profile
응집력있는 시간을 보내기 위한 블로그

0개의 댓글