로깅: EFK 스택
Kubernetes 로그 수집, 집계, 시각화 시스템 구축
Kubernetes 로그 수집, 집계, 시각화 시스템 구축
목표: 프로덕션급 로깅 인프라를 구축하고 운영할 수 있는 수준
📚 EFK 스택 개요
아키텍처
graph LR
subgraph "로그 수집"
APP["📦 Application"] -->|"stdout/stderr"| NODE["💻 Node"]
NODE -->|"/var/log/containers"| AGENT["🚚 Fluentd/Filebeat"]
end
subgraph "로그 집계"
AGENT -->|"전송"| ES["🗄️ Elasticsearch"]
end
subgraph "로그 시각화"
ES -->|"질의"| KIBANA["📊 Kibana"]
end
구성 요소:
- Fluentd/Filebeat: 로그 수집 에이전트
- Elasticsearch: 로그 저장 및 검색
- Kibana: 로그 시각화
🚚 Fluentd
설치
# Fluentd DaemonSet 설치
kubectl apply -f https://raw.githubusercontent.com/fluent/fluentd-kubernetes-daemonset/master/fluentd-daemonset-elasticsearch.yaml
# 또는 Helm
helm repo add fluent https://fluent.github.io/helm-charts
helm install fluentd fluent/fluentd
ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
name: fluentd-config
data:
fluent.conf: |
# 소스: 컨테이너 로그
<source>
@type tail
path /var/log/containers/*.log
pos_file /var/log/fluentd-containers.log.pos
tag kubernetes.*
<parse>
@type multi_format
<pattern>
format json
time_key time
time_format %Y-%m-%dT%H:%M:%S.%NZ
keep_time_key true
</pattern>
<pattern>
format regexp
expression /^(?<time>.+) (?<stream>stdout|stderr) [^ ]* (?<log>.*)$/
time_format %Y-%m-%dT%H:%M:%S.%N%:z
</pattern>
</parse>
</source>
# Kubernetes 메타데이터 필터
<filter kubernetes.**>
@type kubernetes_metadata
</filter>
# Elasticsearch 출력
<match kubernetes.**>
@type elasticsearch
host elasticsearch-master
port 9200
logstash_format true
logstash_prefix k8s-logs
<buffer>
@type file
path /var/log/fluentd-buffers/kubernetes.system.buffer
flush_mode interval
retry_type exponential_backoff
flush_thread_count 2
flush_interval 5s
retry_forever false
retry_max_interval 30
chunk_limit_size 2M
queue_limit_length 8
total_limit_size 500M
</buffer>
</match>
🗄️ Elasticsearch
설치
# Elasticsearch 설치
helm repo add elastic https://helm.elastic.co
helm install elasticsearch elastic/elasticsearch \
--set replicas=3 \
--set resources.requests.memory="2Gi" \
--set resources.limits.memory="2Gi"
설정
# values.yaml
clusterName: "elasticsearch"
nodeGroup: "master"
replicas: 3
minimumMasterNodes: 2
resources:
requests:
cpu: "1000m"
memory: "2Gi"
limits:
cpu: "1000m"
memory: "2Gi"
volumeClaimTemplate:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 30Gi
📊 Kibana
설치
# Kibana 설치
helm install kibana elastic/kibana \
--set elasticsearchHosts=http://elasticsearch-master:9200
접근
# 포트 포워딩
kubectl port-forward svc/kibana-kibana 5601:5601
# 브라우저에서 접속
http://localhost:5601
인덱스 패턴
# Kibana Management > Index Patterns
# 패턴: k8s-logs-*
# 타임필드: @timestamp
🔍 로그 검색
Kibana 쿼리
# 기본 검색
kubernetes.pod.name: "my-app-*"
# 로그 레벨 필터
log.level: "ERROR"
# 시간 범위
@timestamp:[now-1h TO now]
# 복합 쿼리
kubernetes.namespace.name: "production" AND log.level: "ERROR"
# 정규식
message: /exception|error|failed/
📋 로깅 모범 사례
애플리케이션 로깅
# Python 예시 (structlog)
import structlog
import logging
logger = structlog.get_logger()
# 구조화된 로깅
logger.info(
"user_action",
user_id="12345",
action="login",
ip="192.168.1.1",
duration_ms=150
)
# 에러 로깅
try:
process_data()
except Exception as e:
logger.error(
"processing_failed",
error=str(e),
data_id="abc123",
retry_count=3
)
로그 형식
{
"timestamp": "2024-01-15T10:30:00.000Z",
"level": "INFO",
"service": "user-service",
"trace_id": "abc123",
"span_id": "def456",
"message": "User login successful",
"user_id": "12345",
"ip": "192.168.1.1",
"duration_ms": 150
}
📋 체크리스트
- Fluentd/Filebeat 설치
- Elasticsearch 클러스터 구성
- Kibana 설치 및 접근
- 인덱스 패턴 설정
- 로그 검색 쿼리
- 구조화된 로깅
- 로그 보관 정책
- 알림 설정
🔗 관련 노트
- 03-05-모니터링-Prometheus-Grafana — 메트릭 모니터링
- 03-07-분산추적 — 분산 추적
- 02-11-Pod-실패-원인-분석 — 문제 해결
마지막 업데이트: 2026-06-01