Overview
Loki는 Grafana가 개발한 경량 로그 수집 및 분석 시스템으로, Prometheus의 메트릭 수집 방식과 유사하게 설계된 로그 수집 도구이다.
Kubernetes 환경에서 로그 파이프라인을 구축할 때 Loki는 높은 확장성과 효율성을 제공하며,
Promtail은 이 로그를 Loki에 전달하는 에이전트 역할을 한다.
본 글에서는 기존 Loki-Stack 대신 최신 Loki Helm Chart(2024.10월 기준)를 사용하여 단일 바이너리(SingleBinary) 모드로 Loki를 설치하고,
별도의 Helm Chart를 통해 Promtail까지 구성하는 방법을 정리하였다.
또한 Grafana 최신 버전과의 호환성을 고려하여 `values.yaml` 을 직접 커스터마이징하고,
실제 Loki API를 통해 로그 수집 결과를 검증하는 방식까지 다루었다.
참고
Loki-Stack 을 사용해서 간단하게 Loki와 Promtail을 배포할 수 있지만 배포해보니, L
oki-Stack에서 제공해주는 버전이 너무 낮아, 최신 Grafana에서 사용하는 Query와 호환되지 않는다.
따라서 Loki와 Promtail 모두 단일 Helm Chart를 사용해서 배포한다.
📅 관련 글
2024.03.05 - [Monitoring] - Fluent Bit (With Loki)
2024.09.12 - [Monitoring] - Prometheus와 Thanos란?
2024.09.12 - [Monitoring] - Prometheus 와 Thanos 설치 및 구성
2024.09.12 - [Monitoring] - Loki란?
2024.09.13 - [Monitoring] - Loki와 Promtail 설치
2025.01.13 - [Monitoring] - ELK Stack 구축해보기
Loki 설치
해당 설치과정은 간단하게 SingleBinary로 설치하는 내용이다.
Helm Chart 등록
helm repo add grafana https://grafana.github.io/helm-charts
helm repo update
git clone 및 values 파일 복사
# git clone
git clone https://github.com/grafana/loki.git
cd loki/production/helm/loki/
# helm 의존성 업데이트
helm dependency update
# values 파일 복사
mkdir values
cp values.yaml values/somaz.yaml
`values/somaz.yaml` 수정
global:
clusterDomain: "somaz-cluster.local"
dnsService: "coredns"
dnsNamespace: "kube-system"
deploymentMode: SingleBinary
loki:
commonConfig:
replication_factor: 1
storage:
type: filesystem
schemaConfig:
configs:
- from: "2024-01-01"
store: tsdb
index:
prefix: loki_index_
period: 24h
object_store: filesystem # we're storing on filesystem so there's no real persistence here.
schema: v13
singleBinary:
# -- Number of replicas for the single binary
replicas: 1
persistence:
enabled: true
storageClass: "default"
accessModes:
- ReadWriteOnce
size: 10Gi
gateway:
# -- Specifies whether the gateway should be enabled
enabled: true
service:
# -- Type of the gateway service
type: NodePort
nodePort: 31400
chunksCache:
enabled: false
resultsCache:
enabled: false
tableManager:
enabled: false
backend:
replicas: 0
read:
replicas: 0
write:
replicas: 0
ingester:
replicas: 0
querier:
replicas: 0
queryFrontend:
replicas: 0
queryScheduler:
replicas: 0
distributor:
replicas: 0
compactor:
replicas: 0
indexGateway:
replicas: 0
bloomCompactor:
replicas: 0
bloomGateway:
replicas: 0
test:
enabled: false
lokiCanary:
enabled: false
설치한다.
# lint 확인
helm lint --values ./values/somaz.yaml
# 설치 전 확인
helm install loki . -n monitoring -f ./values/somaz.yaml --create-namespace --dry-run >> output.yaml
# 설치
helm install loki . -n monitoring -f ./values/somaz.yaml --create-namespace
# 업그레이드 방법
helm upgrade loki . -n monitoring -f ./values/somaz.yaml
확인한다. NodePort로 배포했기 때문에 `Kubernetes Node IP:Port` 로 loki의 상태를 조회할 수 있다. Promtail 까지 배포한뒤에는 Query를 사용해 데이터를 확인할수도 있다.
# 상태 확인
curl 192.168.100.11:31400
OK
curl 192.168.100.11:31400/config
curl -G -s "http://192.168.100.11:31400/loki/api/v1/query_range" \
--data-urlencode 'query={app="node-feature-discovery"}'
...
{"status":"success","data":{"resultType":"streams","result":[{"stream":{"filename":"/var/log/pods/monitoring_node-feature-discovery-worker-5v2pp_3bd016b2-4a69-4a6c-8fc5-17f7f9749dd1/worker/0.log","instance":"node-feature-discovery","job":"monitoring/node-feature-discovery","namespace":"monitoring","app":"node-feature-discovery","container":"worker","stream":"stderr","node_name":"mgmt-w-01","pod":"node-feature-discovery-worker-5v2pp"},"values":[["1725606670299872220","I0906 07:11:10.299790 1 nfd-worker.go:660] \"feature discovery completed\""],["1725606670299519154","I0906 07:11:10.299254 1 nfd-worker.go:647] \"starting feature discovery...\""],["1725606610285963555","I0906 07:10:10.285522 1 nfd-worker.go:660] \"feature discovery completed\""],["1725606610285873819","I0906 07:10:10.285262 1 nfd-worker.go:647] \"starting feature discovery...\""],["1725606550312098625","I0906 07:09:10.312010 1 nfd-worker.go:660] \"feature discovery completed\""],["1725606550311763894","I0906 07:09:10.311531 1 nfd-worker.go:647] \"starting feature discovery...\""],["1725606490300176632","I0906 07:08:10.300070 1 nfd-worker.go:660] \"feature discov
curl -G -s "http://192.168.100.11:31400/loki/api/v1/query_range" \
--data-urlencode 'query={app="prometheus-node-exporter"}'
{"status":"success","data":{"resultType":"streams","result":[],"stats":{"summary":{"bytesProcessedPerSecond":0,"linesProcessedPerSecond":0,"totalBytesProcessed":0,"totalLinesProcessed":0,"execTime":0.001597489,"queueTime":0.00005817,"subqueries":1,"totalEntriesReturned":0},"querier":{"store":{"totalChunksRef":0,"totalChunksDownloaded":0,"chunksDownloadTime":0,"chunk":{"headChunkBytes":0,"headChunkLines":0,"decompressedBytes":0,"decompressedLines":0,"compressedBytes":0,"totalDuplicates":0}}},"ingester":{"totalReached":1,"totalChunksMatched":0,"totalBatches":0,"totalLinesSent":0,"store":{"totalChunksRef":0,"totalChunksDownloaded":0,"chunksDownloadTime":0,"chunk":{"headChunkBytes":0,"headChunkLines":0,"decompressedBytes":0,"decompressedLines":0,"compressedBytes":0,"totalDuplicates":0}}}}
Loki + S3 백엔드 구성 방법
단순 테스트에는 filesystem 저장소로 충분하지만,
운영 환경에서는 Amazon S3와 같은 객체 스토리지를 사용하는 것이 권장된다.
이는 로그를 장기간 보관하고, 여러 노드 간 공유가 가능하기 때문이다.
loki:
storage:
type: s3
s3:
bucketnames: "my-loki-logs"
endpoint: "s3.ap-northeast-2.amazonaws.com"
region: "ap-northeast-2"
access_key_id: "<your-access-key>"
secret_access_key: "<your-secret-key>"
schemaConfig:
configs:
- from: "2024-01-01"
store: tsdb
object_store: s3
schema: v13
index:
prefix: loki_index_
period: 24h
Loki API 활용 샘플
Loki는 RESTful API를 통해 쿼리를 직접 실행할 수 있다.
하지만 `logcli` 라는 공식 CLI 도구를 사용하면 쿼리 및 결과 분석이 훨씬 편리하다.
설치
brew install grafana/tap/logcli
기본 사용
export LOKI_ADDR=http://192.168.100.11:31400
# 최근 로그 100줄 가져오기
logcli query '{app="node-feature-discovery"}' --limit=100 --since=1h
# 특정 메시지 포함 로그 검색
logcli query '{app="nginx"} |= "GET /health"' --limit=50
Loki Canary 구성
- `lokiCanary.enabled: true`
Loki Canary는 Loki 수신 상태를 테스트하는 자체 로그 생성기이다.
Loki 설치 시 Canary를 활성화하면 일정 간격으로 Loki에 로그를 전송하고,
Grafana 또는 `logcli` 를 통해 수신 여부를 쉽게 확인할 수 있다.
설정 예시
lokiCanary:
enabled: true
배포 후에는 아래와 같은 쿼리로 확인 가능하다.
# logcli
logcli query '{job="loki-canary"}' --limit=10
# curl
curl -G -s "http://<LOKI_URL>/loki/api/v1/query" \
--data-urlencode 'query={job="loki-canary"}'
응답 예시는 아래와 같다.
{
"status": "success",
"data": {
"resultType": "streams",
"result": [
{
"stream": {
"job": "loki-canary",
...
},
"values": [
["1711951234567890000", "this is a test log from canary"]
]
}
]
}
}
promtail 설치
promtail 설치는 훨씬 간단하다.
git clone https://github.com/grafana/helm-charts.git
cd helm-charts/charts/promtail
helm dependency update
mkdir values
cp values.yaml values/somaz.yaml
`values/somaz.yaml` 수정
daemonset:
enabled: true
serviceMonitor:
enabled: true
config:
enabled: true
logLevel: info
logFormat: logfmt
serverPort: 3101
clients:
- url: http://loki-gateway/loki/api/v1/push
설치한다.
# lint 확인
helm lint --values ./values/somaz.yaml
# 설치 전 확인
helm install promtail . -n monitoring -f ./values/somaz.yaml --create-namespace --dry-run >> output.yaml
# 설치
helm install promtail . -n monitoring -f ./values/somaz.yaml --create-namespace
# 업그레이드 방법
helm upgrade promtail . -n monitoring -f ./values/somaz.yaml
Promtail 라벨링 커스터마이징 예시
Promtail에서 수집되는 로그에 붙일 라벨(Label) 은 쿼리 시 매우 중요한 필터 조건이다.
기본적으로 Promtail은 Kubernetes의 메타데이터를 활용해 다양한 라벨을 자동 부여하지만,
`pipelineStages` 항목을 추가하여 라벨을 명시적으로 지정하거나 정규식을 활용한 파싱도 가능하다.
예시
config:
snippets:
pipelineStages:
- cri: {}
- label:
values:
app: "my-app"
namespace: "my-namespace"
container: "my-container"
또는 로그 파일 경로를 기반으로 동적 라벨 추출도 가능하다.
pipelineStages:
- regex:
expression: "/var/log/pods/(?P<namespace>.*)_(?P<pod>.*)/(?P<container>.*)/.*.log"
- labels:
namespace: ""
pod: ""
container: ""
마무리: 단순하지만 확장 가능한 로그 스택 구성의 시작
단일 Helm Chart 기반으로 Loki와 Promtail을 직접 배포하면 다음과 같은 이점이 있다.
- 최신 Loki 기능 활용 (v2.9 기준 logql, range query 등 Grafana와 호환성 보장)
- 커스터마이징 유연성 확보 (스토리지, 라벨링, persistence 조정 등)
- Kubernetes DaemonSet 기반 확장성을 쉽게 갖춤
- Query API 기반으로 직접 로그 수집 검증 가능
간단하게 Loki와 Promtail을 설치해봤다면, 다음 단계로는 Grafana와 연동하여
메트릭 + 로그 + 트레이싱을 한눈에 보는 Observability 대시보드를 구축해보는 것도 좋은 흐름이다.
Grafana Datasource 등록법
Loki를 설치하고 로그 수집이 잘 되었다면, 이제 Grafana에 Loki를 연결하여 시각화를 해야 한다.
Grafana UI에서
- [Settings] → [Data Sources] → [Add data source] 클릭
- Loki 선택
- URL 입력: `http://loki-gateway:80` (혹은 NodePort 주소)
- 저장 후 쿼리 패널에서 `LogQL` 로 로그 확인
이후 Prometheus, Thanos, Loki까지 포함한 통합 Grafana 대시보드 구축 예제는
다음 포스팅에서 다룰 예정이다. (예: Explore → Logs 메뉴에서 필터링 실습 등)
Reference
- https://hackernoon.com/grafana-loki-architecture-summary-and-running-in-kubernetes
- https://github.com/grafana/loki/tree/main/production/helm/loki
- https://github.com/grafana/helm-charts/tree/main/charts/promtail
- https://github.com/grafana/helm-charts/tree/main/charts/loki-stack
- https://grafana.com/docs/loki/latest/setup/install/helm/install-monolithic/
'Monitoring' 카테고리의 다른 글
ELK Stack 구축해보기 (2) | 2025.01.27 |
---|---|
Loki란? (4) | 2024.09.26 |
Prometheus 와 Thanos 설치 및 구성 (0) | 2024.09.19 |
Prometheus와 Thanos란? (4) | 2024.09.12 |
Fluent Bit (With Loki) (4) | 2024.03.08 |