모니터링이 필요한 이유
우리 소프트웨어를 사용하고 있는 고객 또는 사용자를 위해 지속적으로 품질을 보장해야하기 때문이다. 그리고 개발했던 기능이 리모트 환경에서 예상과는 다르게 오작동 할 수 있을 수 있다 또한, 시스템 자원적인 문제로 서버 전체가 다운될 수 도 있다
이러한 문제들을 로그로 추적하여 할 수 있다. 하지만 로그는 엄청난 텍스트 덩어리로 개발자의 눈으로 일일히 파악하기는 매우 불편하다. 모니터링은 보통 로그추적 이전에 시각적으로 문제를 빠르게 파악하기 위해 사용되어진다.
프로메테우스와 그라파나
Prometheus
metric을 수집하고 모니터링 및 알람에 사용되는 오픈소스 애플리케이션이다. time series database를 사용해 metric을 저장하고 flexible한 query를 사용하 metric을 조회할 수 있다.
Grafana
데이터 시각화, 모니터링 및 분석을 위한 오픈소스 플랫폼이다. 사용자는 Grafana에서 패널(panel)을 사용해 설정된 기간 동안 특정 metric을 나타내는 dashboard를 만들 수 있다.Grafana는 그래프, 테이블 같은 것들을 지원할 뿐만 아니라 시각화를 위한 별도의 플러그인을 추가해서 사용할 수도 있다.
모니터링 적용하기
- build.gradle 의존성 추가하기
// Prometheus runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
- 서버 실행하기
엑추에이터 접근해보기 - http://localhost:8080/actuator

매트릭 접근해보기 - http://localhost:8080/actuator/metrics

프로메테우스 접근하기 - http://localhost:8080/actuator/prometheus

- promethus 설치 [docker - compose]
- prometheus yml 설정 가이드
- prometheus rule yml 설정 가이드
global: scrape_interval: 10s # default=1m := 말 그대로 스크랩 주기 scrape_timeout: 10s # default := 스크랩 타임아웃 evaluation_interval: 10s # default=1m := 모니터링 rule(규칙) 평가 주기 external_labels: monitor: 'come-us-monitor' # 단순 라벨 명 query_log_file: query_log_file.log # prometheus 쿼리 로그 기록 # 규칙 로딩 evaluation_interval 평가 목록이라고 이해하면 됨 rule_files: - "rule.yml" # 매트릭을 수집할 앤드포인트로 서버 자신을 가르킴. scrape_configs: - job_name: 'come-us_monitoring' metrics_path: /actuator/prometheus static_configs: - targets: ['host.docker.internal:8080'] # 스크랩하는 타깃. (docker환경의 웹 애플리케이션임)
groups: - name: latency-and-down # 단순 이름 rules: # Alert for any instance that is unreachable for >5 minutes. # 서버가 다운되거나 혹은 레이턴시가 길때 알림을 준다! - alert: DownInstance expr: up == 0 for: 5m labels: severity: page annotations: summary: "Instance {{ $labels.instance }} down" description: "{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes." # Alert for any instance that has a median request latency >1s. - alert: ApiRequestHighLatency expr: api_http_request_latencies_second{quantile="0.5"} > 1 for: 10m annotations: summary: "request high latency on {{ $labels.instance }}" description: "{{ $labels.instance }} has a median request latency above 1s (current value: {{ $value }}s)"
prometheus: image: prom/prometheus container_name: prometheus volumes: - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml ports: - "9090:9090" restart: unless-stopped
애플리케이션 실행후 해당 localhost:9090으로 접속하고 상단 status에 target로 접근
본 화면은 잘 연결이 안된 화면이다.

잘연결이 되면 라벨이 녹새으로 되어있을 것이다.

상단에 그래프에서 http_server_requests_seconds_max를 입력하고,아래 Tab에 Graph를 선택해 보면 그래프가 보일 것이다. 하지만 모니터링을 일일히 탐색하기 불편하다. 이점을 해소하기 위해 패널들로 한번에 이상현상을 파악하기 용이한 것이 그라파나이다. 또한 별도의 플로그인을 추가하여 뛰어난 시각화 모니터링 업그레이드가 가능하다.


- grafana 설치 [docker-compose]
grafana: image: grafana/grafana container_name: grafana ports: - "3000:3000" volumes: - ./grafana/volume:/var/lib/grafana restart: always
docker 실행 후http://localhost:3000에 접속해보자. 다음과 같이 Grafana login 화면을 볼 수 있다. 기본 설정된 ID/PW인admin | admin으로 로그인한다.

Add Data Source를 클릭해 추가한다. Grafana에서 시각화할 데이터로서 Prometheus에 수집되고 있는 metric을 사용할 것이기 때문에 Prometheus를 선택한다.


Prometheus가 Data Source로 추가되었다.
전반적으로 보면 각 패널들이 보이고 자원에 대한 이름들 등 한눈에 웹 애플리케이션 상태를 확인할 수 있게 된다.

다음으로는 Data Source를 이용해 Dashboard를 생성해보자.

그래프를 이용해볼 것이기 때문에
Choose Visualization
을 클릭한다.
Metrics로 이전에 Prometheus에서도 확인해보았던 jvm_memoruy_used_bytes를 선택한다.

작업한 Dashboard를 저장한다.

추가된 Dashboard를 확인할 수 있다.

Spring Boot Application에서 생성하는 metric을 Prometheus를 통해 수집하고, Grafana로 시각화하는 것까지 마무리했다.실제로는 애플리케이션에서 기본적으로 제공하는 Metric 뿐만 아니라 Micrometer를 이용해 직접 필요한 Metric을 추가할 수도 있다.또한 Grafana에는 소개하지 않은 더 많은 유용한 기능들이 있다. 필요한 기능은 문서를 통해 찾아가며 사용해보자.
Refer
- promethus yaml 설정 참고