JVM/SpringCloud

모니터링(Micrometer, Prometheus, Grafana)

kyoulho 2024. 1. 3. 16:19

Micrometer


 애플리케이션의 메트릭 수집을 단순화하고, JVM 기반의 애플리케이션에서 사용하기 쉬운 메트릭 API를 제공하는 라이브러리이다. 특히 스프링 기반의 애플리케이션에서는 Micrometer가 스프링의 메트릭 제공에 통합되어 사용된다. 또한, 다양한 모니터링 시스템과의 통합을 지원하여 Prometheus, Grafana, InfluxDB, Datadog 등 다양한 백엔드로 메트릭을 전송할 수 있다.
 여러 Micrometer의 기능 중 하나로 Timer가 있다. Timer는 특정 코드 블록이나 메서드의 실행 시간을 측정하고 해당 지표를 메트릭으로 수집한다. 호출 빈도와 지연 시간을 시계열로 기록하여 애플리케이션의 동작을 모니터링할 수 있다. @Timed 어노테이션은 Micrometer에서 제공하는 주요 어노테이션 중 하나로, 특정 메서드의 실행 시간을 자동으로 측정하고 메트릭으로 기록한다. 이를 통해 코드의 성능을 쉽게 측정하고 프로파일링 할 수 있다.
 

라이브러리

implementation("io.micrometer:micrometer-registry-prometheus")

 

application.yml

management:
  endpoints:
    web:
      exposure:
        include: prometheus, metrics

 

@Timed

@GetMapping("/users")
@Timed(value = "users.users", longTask = true)
@ResponseStatus(HttpStatus.OK)
fun getUserByAll(): List<ResponseUser> {
    return userService.getUserByAll()
}

 

  • value: 메트릭의 이름을 지정
  • longTask: 해당 작업이 긴 작업(long task)인지 여부를 나타낸다.

 

메트리 목록 조회

localhost:8080/actuator/metrics
Spring Boot 애플리케이션에서 Micrometer를 사용하여 수집된 메트릭 데이터를 확인할 수 있는 엔드포인트이다. 이 엔드포인트를 통해 여러 메트릭의 현재 상태 및 값을 조회할 수 있다. 엔드포인트를 사용해야 조회할 수 있다.

 

 

Prometheus 메트릭 조회

localhost:8080/actuator/prometheus
Spring Boot 애플리케이션에서 수집된 메트릭을 Prometheus 형식으로 제공하는 엔드포인트이다. 이를 통해 Prometheus 서버가 애플리케이션의 메트릭을 주기적으로 수집할 수 있다.

# HELP users_users_seconds  
# TYPE users_users_seconds summary
users_users_seconds_active_count{class="com.example.userservice.controller.UserController",method="getUserByAll",} 0.0
users_users_seconds_duration_sum{class="com.example.userservice.controller.UserController",method="getUserByAll",} 0.0
# HELP users_users_seconds_max  
# TYPE users_users_seconds_max gauge
users_users_seconds_max{class="com.example.userservice.controller.UserController",method="getUserByAll",} 0.0

 
 
 

Prometheus


Prometheus는 이벤트 모니터링 및 경고 도구로, 다양한 서비스 및 시스템의 상태 및 성능을 실시간으로 수집하고 분석할 수 있는 오픈소스 애플리케이션이다. 프로메테우스는 특히 컨테이너 오케스트레이션 시스템인 Kubernetes와 잘 통합되어 있어, 클라우드 네이티브 환경에서 많이 사용된다.

  • 다차원 데이터 모델: Prometheus는 다차원 시계열 데이터 모델을 사용하여 서비스 및 시스템의 상태를 저장한다. 이 모델은 메트릭에 레이블을 추가함으로써 다양한 필터링 및 집계를 수행할 수 있게 한다.
  • 풍부한 쿼리 언어: Prometheus는 PromQL이라는 강력하고 표현력이 풍부한 쿼리 언어를 제공한다. 이를 사용하여 메트릭 데이터를 실시간으로 조회하고 분석할 수 있다.
  • 스크래핑(Scraping): Prometheus는 HTTP 엔드포인트를 통해 수집 대상 서비스의 메트릭을 주기적으로 스크랩(scrape)한다. 이를 통해 서비스가 직접 Prometheus 서버로 메트릭을 전송하지 않아도 된다.
  • 알림 및 경고 기능: Prometheus는 특정 조건이나 임계값을 초과할 때 알림을 생성하고, Alertmanager를 통해 경고를 관리한다.
  • 확장성: Prometheus는 수집 대상이 늘어나면서도 확장이 용이하며, 클러스터링 및 고가용성을 제공하는 샤딩 기능을 내장하고 있다.
  • 다양한 플러그인과 통합: Prometheus는 다양한 플러그인과 통합을 제공하여 여러 서비스 및 컴포넌트와의 쉬운 통합을 지원한다.

docker-compose.yml

version: '3.7'

services:
  prometheus:
    image: prom/prometheus
    container_name: prometheus
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
    ports:
      - 9090:9090
    command: # web.enalbe-lifecycle은 api 재시작없이 설정파일들을 reload 할 수 있게 해줌
      - '--web.enable-lifecycle'
      - '--config.file=/etc/prometheus/prometheus.yml'
    restart: always

 

prometheus.yml

prometheus.yml 파일은 Prometheus 서버의 설정 파일로, Prometheus가 어떤 대상에서 메트릭을 수집할지, 어떤 규칙에 따라 수집할지, 어떻게 알림을 설정할지 등을 정의한다. https://prometheus.io/docs/prometheus/latest/configuration/configuration/

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
    - targets: ['prometheus:9090']

  - job_name: 'user-service'
    scrape_interval: 10s
    metrics_path: '/user-service/actuator/prometheus'
    static_configs:
    - targets: [apigateway-service:8000]
  
  - job_name: 'order-service'
    scrape_interval: 10s
    metrics_path: '/order-service/actuator/prometheus'
    static_configs:
    - targets: [apigateway-service:8000]

  - job_name: 'apigateway-service'
    scrape_interval: 10s
    metrics_path: '/actuator/prometheus'
    static_configs:
    - targets: [apigateway-service:8000]

Prometheus Dashboad

http://localhost:9000

 

Grafana


Grafana는 대시보드를 만들고 시계열 데이터를 차트로 표현하는 기능을 제공하여 시스템 및 서비스의 성능을 모니터링하고 분석하는 오픈소스 애플리케이션이다. Grafana는 주로 시스템 관리자, 개발자, 운영팀 등이 서버 및 애플리케이션의 상태 및 성능을 모니터링하고 시각화하는 데 사용된다.

  • 다양한 데이터 소스 지원: Grafana는 다양한 데이터 소스와 통합이 가능하다. Prometheus, InfluxDB, Elasticsearch, MySQL, PostgreSQL 등 여러 데이터베이스 및 메트릭 수집 시스템과 연동할 수 있다.
  • 대시보드 및 패널: Grafana 대시보드는 여러 패널을 조합하여 구성할 수 있다. 각 패널은 특정 데이터를 시각적으로 나타낸다. 이러한 대시보드를 통해 여러 데이터 소스의 정보를 한눈에 볼 수 있다.
  • 다양한 차트 및 시각화 옵션: Grafana는 다양한 차트 및 그래프를 지원하여 데이터를 효과적으로 시각화할 수 있다. 선 그래프, 막대그래프, 히트맵, 테이블 등 다양한 형식을 사용할 수 있다.
  • 알림 및 경고 기능: Grafana는 데이터의 특정 조건이나 임계값을 초과할 때 알림을 생성하고 경고를 제공하는 기능을 지원한다.
  • 시계열 데이터 쿼리: Grafana는 사용자가 데이터를 쿼리하고 필터링하여 대화형으로 데이터를 분석할 수 있는 기능을 제공한다.
  • 플러그인 생태계: Grafana는 플러그인을 통해 기능을 확장할 수 있습니다. 사용자들은 Grafana 플러그인을 개발하여 새로운 데이터 소스, 패널, 테마, 알림 기능 등을 추가할 수 있다.

docker-compose.yml

version: '3.7'

services:
  grafana:
    image: grafana/grafana 
    ports:
      - "3000:3000"

Grafana Dashboard

http://localhost:3000로 접속한다. 초기 접속 정보는 admin, admin이다.
configuration -> add data source -> prometheus를 선택후 url:port를 추가해 주면 된다.