모니터링: 시스템을 실시간으로 관찰하고 측정하는 것
모니터링의 중요성
💡 모니터링 도구를 사용하여 시스템의 상태를 추적하고, 문제를 감지하고, 성능을 최적화하며, 장애 발생 시 빠르게 대응할 수 있다.
프로메테우스(Prometheus) 연동
Prometheus란?
Prometheus는 오픈소스 모니터링 툴로 시계열 데이터베이스를 사용하여 메트릭 데이터를 수집하고, 쿼리 및 시각화를 통해 시스템 상태를 모니터링하고 경고를 설정할 수 있다.
Prometheus의 주요 구성 요소
- Prometheus 서버: 메트릭 데이터를 수집하고 저장하는 핵심 컴포넌트로, 각 타겟으로부터 데이터를 주기적으로 스크랩하여 시계열 데이터베이스에 저장한다.
- 시계열 데이터베이스(Time Series Database, TSDB)는 시간에 따라 변화하는 데이터를 효율적으로 저장하고 조회할 수 있도록 최적화된 데이터베이스
- Exporters: Prometheus는 기본적으로 애플리케이션에서 메트릭 데이터를 수집한다. Exporter는 특정 애플리케이션이나 시스템의 메트릭 데이터를 Prometheus가 이해할 수 있는 형식으로 변환해준다.
- Ex: Node Exporter (서버의 시스템 메트릭 수집), PostgreSQL Exporter (PostgreSQL 메트릭 수집), Spring boot의 micrometer-registry-prometheus 디펜던시
- Pushgateway: 짧은 수명의 작업(job)에서 메트릭을 수집하여 Prometheus 서버에 푸시(push)할 수 있다. 일반적으로 지속적으로 실행되지 않는 작업에서 사용된다. 예를 들어 배치 작업, 스크립트 실행, cron 작업 등이 있다.
- Alertmanager: Prometheus 서버에서 발생하는 경고(alert)를 처리하고, 이메일, PagerDuty, Slack 등 다양한 방법으로 알림을 보낼 수 있다.
build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
}
- actuator와 prometheus 추가
프로메테우스 설정 파일
prometheus.yml
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:/etc/prometheus/prometheus.yml prom/prometheus
Status > Targets 로 스프링부트 애플리케이션 확인
- 현재 실행되고 있지 않은 상태
실행시켜보면 다음과 같이 상태가 변경된다.
그라파나(Grafana) 연동
그라파나란?
Grafana는 오픈소스 데이터 시각화 및 모니터링 툴로 다양한 데이터 소스를 지원하여 데이터를 시각화하고 분석할 수 있다.
그라파나 주요기능
- 대시보드 생성: Grafana는 사용자가 데이터를 시각화할 수 있는 대시보드를 생성할 수 있도록 한다. 여러 가지 그래프, 차트, 게이지 등을 사용하여 데이터를 시각적으로 표현할 수 있다.
- 다양한 데이터 소스 지원: Prometheus, InfluxDB, Graphite, Elasticsearch, MySQL, PostgreSQL 등 다양한 데이터 소스를 지원한다. 이를 통해 여러 시스템과 애플리케이션의 데이터를 통합하여 시각화할 수 있다.
- 알림 기능: 조건을 설정하여 조건이 충족되면 이메일, Slack, PagerDuty 등 다양한 채널을 통해 알림을 보낼 수 있다.
- 플러그인 지원
- 사용자 관리: 대시보드와 데이터 소스에 대한 접근 권한 설정
그라파나 도커 컨테이너 실행
docker run -d --name=grafana -p 3000:3000 grafana/grafana
초기 ID: admin
/ PW: admin
Datasources > Prometheus > Connection URL 입력 > host.docker.internal:9090
Sava & test
Dashboard > create Dashboard > import dashboard > grafana.com/dashboards > spring 검색
사용할 dashboard 템플릿을 선택하고 Dashboard ID를 copy 한다.
import dashboard에서 붙여넣고, Load 후 프로메테우스 선택하고 import 클릭
즐겁게 모니터링하면 된다 ^^
다양한 기능들이 존재하니 필요하다면 지지고 볶고 하면 될 듯하다.
Grafana와 Slack을 연동해서 Alert를 받는 방법도 있다.
흐름
- 스프링 부트 애플리케이션이 프로메테우스 서버로 로그를 전송한다.
/actuator/prometheus
- 프로메테우스가 로그를 수집하고, 그라파나로 전송한다.
- 그라파나 로그를 수집하고, 대시보드로 보여준다.
- 필요하다면 Alert를 생성해서 Slack 같은 곳으로 알람을 받는다.
Loki를 활용한 어플리케이션 로깅
Loki는 Grafana Labs에서 개발한 로그 집계 시스템으로,
Prometheus의 메트릭 수집 방식과 유사하게 로그 데이터를 수집하고 쿼리할 수 있도록 설계되었다.
주로 로그 데이터를 저장하고, 이를 Grafana를 통해 시각화한다.
Loki의 주요 특징 중 하나는 라벨 기반의 메타데이터를 사용하여 로그를 효율적으로 검색할 수 있다는 것이다.
loki-logback-appender
loki-logback-appender는 Logback을 사용하는 Java 애플리케이션에서 로그를 Loki로 직접 전송하기 위한 라이브러리로, 이를 사용하면 별도의 Promtail 설정 없이도 로그를 Loki로 전송할 수 있다.
implementation 'com.github.loki4j:loki-logback-appender:1.5.1' // 추가
로깅 테스트용 SampleController
@RestController
public class SampleController {
private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
@GetMapping("/")
public String hello(HttpServletResponse response) throws IOException {
logger.info("Attempted access to / endpoint resulted in 403 Forbidden");
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
return null;
}
}
resources/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>
https://grafana.com/docs/loki/latest/setup/install/docker/
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
도커 명령어
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
http://localhost:3100/ready 에 접속하여 상태 확인
그라파나에서 Data sources Loki 추가 후 Connection url 입력
Explore에서 다음과 같이 설정하고 Run Query를 통해 수집된 로그를 확인한다.
SampleController에서 발생한 INFO 로그 레벨만 검색 결과
'Backend' 카테고리의 다른 글
어플리케이션 성능 테스트 - JMeter (0) | 2024.08.30 |
---|---|
RabbitMQ로 SAGA 패턴 구현 (0) | 2024.08.30 |
Kafka 기본 개념 및 연동 실험 (0) | 2024.08.19 |
RabbitMQ 기본 개념 및 실습 (0) | 2024.08.19 |
대규모 스트림 처리 (0) | 2024.08.18 |