5.2.2 · блок 5
Grafana Alloy и Loki: сбор и поиск логов
Grafana Alloy и Loki: сбор и поиск логов
Зачем это нужно
kubectl logs не масштабируется на сотни pods и несколько namespace. Grafana Loki — log aggregation, оптимизированная под Kubernetes labels (как Prometheus для logs). Grafana Alloy — agent на каждой node, читает container logs, обогащает их Kubernetes-метаданными и отправляет в Loki. Вместе дают единый поиск по всем ML-сервисам из Grafana.
Основные идеи
Loki architecture.
| Component | Role |
|-----------|------|
| **Grafana Alloy** | DaemonSet, читает log files, labels streams и отправляет их в Loki |
| **Loki** | Ingest, index by labels, store chunks |
| **Grafana** | LogQL queries, correlation with metrics |
Index only labels, not full text (conceptually). Дешевле Elasticsearch для «найти pod X за время T»; full-text search слабее — компенсируют хорошими labels и JSON parsing.
Log streams. Unique combo of labels: {namespace="ml-prod", app="churn-serving", pod="churn-abc"}.
Alloy pipeline. В Alloy конфигурация описывает поток компонентов: discovery Kubernetes → source файлов контейнеров → processing/parsing → Loki write.
1. CRI parsing — parse container log wrapper.
2. json — extract fields from structured app logs.
3. labels — promote safe fields to labels (level, model_version) — осторожно с cardinality!
4. output — send to Loki.
LogQL basics.
{namespace="ml-prod", app="churn-serving"} |= "error"
{namespace="ml-prod"} | json | level="error" | line_format "{{.msg}}"
rate({app="churn-serving"}[5m]) # log rate for alerts
Correlation metrics ↔ logs. Grafana: click spike on error rate panel → «View logs» with matched time range and labels.
Retention. Loki retention 7–30d typical; compliance archives → S3 (optional).
Istio access logs in Loki. Alloy читает sidecar log file или mesh telemetry export — unified search «503 from gateway» + app stack trace.
Security. Loki ingress TLS; RBAC in Grafana; redact PII in pipeline stage if accidentally logged.
vs ELK. ELK — powerful full-text, heavier ops. Loki — lighter, native Grafana, label-first — fits Prometheus-centric stack курса.
Как это выглядит на практике
Helm: separate Grafana Alloy DaemonSet + Loki in monitoring namespace. Для production фиксируйте версии chart/images и проверяйте labels до rollout.
Alloy config fragment (conceptual):
discovery.kubernetes "pods" {
role = "pod"
}
loki.source.kubernetes "pods" {
targets = discovery.kubernetes.pods.targets
forward_to = [loki.process.app.receiver]
}
loki.process "app" {
stage.cri {}
stage.json {
expressions = { level = "level", model_version = "model_version" }
}
stage.labels {
values = { level = "", model_version = "" }
}
forward_to = [loki.write.default.receiver]
}
loki.write "default" {
endpoint { url = "http://loki.monitoring.svc:3100/loki/api/v1/push" }
}
Incident workflow:
1. Alert: error rate high on churn-serving.
2. Grafana Explore: {namespace="ml-prod", app="churn-serving"} | json | level="error".
3. Find repeated feature tenure missing after deploy v1.3.0.
4. Cross-check MMS + feature pipeline deploy time.
Derived fields: link request_id to Tempo trace (урок 5.3.1).
Migration note. Promtail — legacy agent: Grafana прекратила его поддержку 2 марта 2026. Не закладывайте Promtail в новые установки; мигрируйте существующие конфигурации на Grafana Alloy и сверяйте эквивалентность parsing, relabeling и labels до переключения.
Что сделать после занятия
- [ ] Напишите 2 LogQL запроса: все errors за час; фильтр по
model_version. - [ ] Определите, какие JSON-поля можно поднять в labels без cardinality explosion.
- [ ] Свяжите с 5.2.1: какие поля ваш JSON log должен содержать для Loki.