sy/dev
Study
9 min read

모니터링·로깅 — Prometheus, Grafana, ELK Stack으로 운영 환경 관찰하기

배포 완료 후 '지금 서버는 잘 돌고 있나?' 하고 싶으면? 모니터링과 로깅이 필요하다. 메트릭 수집(Prometheus) → 시각화(Grafana) → 알람 설정, 그리고 로그 수집(ELK)으로 운영 환경의 모든 신호를 포착하자.

💡

한 줄 요약모니터링(메트릭) = CPU, 메모리, 요청 수 같은 수치를 실시간으로 수집 및 시각화. 로깅(로그) = 앱에서 발생하는 모든 이벤트를 기록해 문제 분석. 둘 다 운영의 눈과 귀다.

배포까지 완료했다. 이제 시스템이 잘 돌아가는지 어떻게 알까?

개발자: "서버 상태 어때?"
운영: "... 몰라. 콘솔 로그 봤더니 에러가 막 떨어지는데 뭔지 모르겠어"

이런 상황을 막기 위해 필요한 게 모니터링로깅이다.

모니터링 vs 로깅

모니터링 (Monitoring)

시스템의 수치 데이터를 실시간으로 수집하고 시각화

CPU 사용률: 45%
메모리 사용률: 2.1GB / 8GB
네트워크 수신: 1.2Mbps
요청 처리 시간: 45ms
에러율: 0.01%

용도:

  • 실시간 대시보드 (지금 당장 서버 상태)
  • 알람 (CPU 80% 이상 → Slack 알림)
  • 용량 계획 (트래픽 추이 보고 서버 확장 결정)

로깅 (Logging)

앱에서 발생하는 모든 이벤트(로그)를 기록하고 검색

2026-06-04 15:30:45 INFO   User registered: user_id=12345
2026-06-04 15:30:46 INFO   Payment processed: order_id=67890
2026-06-04 15:30:47 ERROR  Connection to DB failed: timeout
2026-06-04 15:30:48 WARN   Slow query: duration=2500ms

용도:

  • 문제 분석 (에러 발생 원인 파악)
  • 감사 (누가 언제 뭘 했는지 기록)
  • 성능 분석 (느린 요청 찾기)

모니터링: Prometheus + Grafana

Prometheus — 메트릭 수집

시스템 전역에서
├─ Node Exporter (서버 메트릭)
├─ kube-state-metrics (Kubernetes 상태)
├─ 앱의 Prometheus 클라이언트
└─ 모든 메트릭 → Prometheus에 저장

수집하는 메트릭 예:

# 시스템
node_cpu_seconds_total
node_memory_MemAvailable_bytes
node_network_receive_bytes_total

# Kubernetes
kube_pod_container_status_restarts_total
kube_deployment_status_replicas_available

# 앱 커스텀
http_requests_total{method="GET", status="200"}
http_request_duration_seconds
database_query_duration_ms

Prometheus 설정 (prometheus.yml):

global:
  scrape_interval: 15s  # 15초마다 수집
 
scrape_configs:
- job_name: 'kubernetes-nodes'
  kubernetes_sd_configs:
  - role: node
 
- job_name: 'kubernetes-pods'
  kubernetes_sd_configs:
  - role: pod
 
- job_name: 'myapp'
  static_configs:
  - targets: ['localhost:8000']  # 앱이 /metrics 엔드포인트 제공

Grafana — 시각화

Prometheus의 메트릭을 그래프로 표시.

기본 대시보드 구성:

┌─────────────────────────────────┐
│   CPU 사용률                     │  (라인 그래프)
│   45% ━━━━━╱╲____               │
└─────────────────────────────────┘

┌─────────────────────────────────┐
│   메모리 사용률                   │  (게이지)
│        60%                       │
│      /      \                    │
└─────────────────────────────────┘

┌─────────────────────────────────┐
│   요청 처리 시간                  │  (박스 플롯)
│   p50: 45ms                      │
│   p95: 120ms                      │
│   p99: 250ms                      │
└─────────────────────────────────┘

┌─────────────────────────────────┐
│   에러율                          │  (게이지)
│        0.05%                      │
└─────────────────────────────────┘

Grafana 대시보드 쿼리 예:

# CPU 사용률
rate(node_cpu_seconds_total{mode="user"}[5m])

# Pod 재시작 횟수
increase(kube_pod_container_status_restarts_total[1h])

# HTTP 요청 처리 시간 (p95)
histogram_quantile(0.95, http_request_duration_seconds)

알람 설정

# alert-rules.yml
groups:
- name: app-alerts
  rules:
  - alert: HighCPU
    expr: node_cpu_usage > 80
    for: 5m
    annotations:
      summary: "CPU 사용률 80% 초과"
      description: "{{ $labels.node }}에서 CPU 85%"
  
  - alert: HighErrorRate
    expr: rate(http_requests_total{status="5xx"}[5m]) > 0.01
    for: 2m
    annotations:
      summary: "에러율 1% 초과"
  
  - alert: PodCrashLooping
    expr: rate(kube_pod_container_status_restarts_total[15m]) > 0.1
    for: 5m
    annotations:
      summary: "Pod이 계속 재시작 중"

알람 전달:

Prometheus 규칙 트리거
  ↓
AlertManager
  ├─ Slack 채널로 메시지
  ├─ 이메일 전송
  ├─ PagerDuty (긴급 호출)
  └─ 웹훅 (커스텀 처리)

로깅: ELK Stack

ELK = Elasticsearch + Logstash + Kibana

앱 로그 → Logstash (수집) → Elasticsearch (저장) → Kibana (검색·분석)

1. Logstash — 로그 수집

# logstash.conf
input {
  file {
    path => "/var/log/app/*.log"
    start_position => "beginning"
  }
  # 또는 syslog, kafka, http 등
}
 
filter {
  grok {
    match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{DATA:msg}" }
  }
  mutate {
    add_field => { "[@metadata][index_name]" => "app-logs-%{+YYYY.MM.dd}" }
  }
}
 
output {
  elasticsearch {
    hosts => ["elasticsearch:9200"]
    index => "%{[@metadata][index_name]}"
  }
}

2. Elasticsearch — 저장소

로그를 전문 검색 엔진에 저장.

# 쿼리 예
GET app-logs-2026.06.04/_search
{
  "query": {
    "match": {
      "level": "ERROR"
    }
  },
  "aggs": {
    "error_by_user": {
      "terms": {
        "field": "user_id",
        "size": 10
      }
    }
  }
}

3. Kibana — 시각화 및 검색

┌─────────────────────────────────────────────┐
│ 로그 검색                                    │
│ [ERROR] [200-06-04] [user_id: *]           │
│                                             │
│ 결과: 1,245개 로그                          │
├─────────────────────────────────────────────┤
│ 2026-06-04 15:30:47 ERROR                   │
│ User registration failed                     │
│ user_id: 12345                              │
│ error: "Email already exists"               │
│ duration: 245ms                             │
│                                             │
│ 2026-06-04 15:30:46 ERROR                   │
│ Payment processing error                     │
│ order_id: 67890                             │
│ error: "Insufficient funds"                 │
└─────────────────────────────────────────────┘

실전: Kubernetes에서 모니터링·로깅 구성

모니터링 설치 (Prometheus + Grafana)

# Helm으로 한 번에 설치
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --create-namespace
 
# Pod 확인
kubectl get pods -n monitoring
prometheus-0          Running
grafana-xxx           Running
alertmanager-0        Running

로깅 설치 (ELK)

# Elasticsearch 설치
helm repo add elastic https://helm.elastic.co
helm install elasticsearch elastic/elasticsearch \
  --namespace logging \
  --create-namespace
 
# Kibana 설치
helm install kibana elastic/kibana \
  --namespace logging
 
# Logstash 설치 (DaemonSet으로 모든 노드에)
helm install logstash elastic/logstash \
  --namespace logging

대시보드 접근

# Grafana
kubectl port-forward -n monitoring svc/prometheus-grafana 3000:80
# http://localhost:3000 (기본 암호: admin/prom-operator)
 
# Kibana
kubectl port-forward -n logging svc/kibana-kibana 5601:5601
# http://localhost:5601

모니터링·로깅 체크리스트

운영 환경에서 필수:

메트릭 모니터링
- [ ] 서버 CPU, 메모리, 디스크
- [ ] Pod 상태 (Running, CrashLoopBackOff)
- [ ] 애플리케이션 응답 시간
- [ ] 에러율, 4xx/5xx 응답
- [ ] 데이터베이스 연결 풀 사용률

로그 수집
- [ ] 애플리케이션 로그 (stdout → Logstash)
- [ ] 시스템 로그 (/var/log)
- [ ] 접근 로그 (HTTP 요청)
- [ ] 에러 로그 (스택 트레이스)
- [ ] 감사 로그 (누가, 언제, 뭘)

알람
- [ ] CPU > 80% (5분)
- [ ] 메모리 > 85%
- [ ] 에러율 > 1%
- [ ] Pod 재시작 반복
- [ ] 디스크 공간 부족
- [ ] 응답 시간 p95 > 1s

시각화
- [ ] 실시간 대시보드 (경영진용)
- [ ] 상세 메트릭 (개발팀용)
- [ ] 로그 분석 대시보드 (운영팀용)

핵심 정리

목표도구역할
메트릭 수집Prometheus시스템 수치 기록
메트릭 시각화Grafana그래프로 표시
메트릭 알람AlertManager임계값 초과 시 알림
로그 수집Logstash로그 수집·전처리
로그 저장Elasticsearch대규모 로그 저장
로그 검색Kibana로그 검색·분석

배포 환경 이해하기 시리즈 완료! 🎉

1. ✅ Docker — 앱을 Container로 패키징
2. ✅ Kubernetes — Container를 자동으로 관리
3. ✅ AWS — 클라우드 인프라 제공
4. ✅ 배포 전략 — Blue-Green, Canary, Rolling
5. ✅ GitOps/CI-CD — 배포 자동화
6. ✅ 모니터링·로깅 — 운영 환경 관찰

이제 "코드를 git push → 자동 테스트 → 자동 빌드 → 자동 배포 → 실시간 모니터링" 의 완전한 파이프라인을 갖췄다!

다음 스텝

  • Kubernetes 심화 (StatefulSet, DaemonSet, 고급 스케줄링)
  • 보안 (RBAC, Network Policy, Pod Security Policy)
  • 성능 튜닝 (캐싱, 데이터베이스 최적화)

참고자료

Comments