Grafana Loki 日誌聚合
Vibe Prompt
「幫我建立 Grafana Loki + Promtail 收集 K8s 所有 Pod 日誌,並在 Grafana 中查詢。」
Docker Compose
services:
loki:
image: grafana/loki:latest
ports: ["3100:3100"]
command: -config.file=/etc/loki/local-config.yaml
promtail:
image: grafana/promtail:latest
volumes:
- /var/log:/var/log
- ./promtail-config.yaml:/etc/promtail/config.yaml
command: -config.file=/etc/promtail/config.yaml
grafana:
image: grafana/grafana:latest
ports: ["3000:3000"]
environment:
GF_SECURITY_ADMIN_PASSWORD: admin
Promtail Config
scrape_configs:
- job_name: system
static_configs:
- targets: [localhost]
labels:
job: varlogs
__path__: /var/log/*log
查詢語法(LogQL)
# 查詢某個應用的所有日誌
{app="my-app"}
# 包含 error 的日誌
{app="my-app"} |= "error"
# 排除 heartbeat
{app="my-app"} |= "error" != "heartbeat"
# 正則匹配
{app="my-app"} |~ "error|exception|failed"
# JSON 解析
{app="my-app"} | json | status >= 500
Grafana Explore
- 進入 Grafana → Explore
- 選擇 Loki 資料來源
- 輸入 LogQL 查詢
- 調整時間範圍
- 查看結果
關鍵要點
- ✅ Loki = 受 Prometheus 啟發的日誌系統,只索引 Label(不索引全文)
- ✅ LogQL 結合 PromQL 的標籤查詢與日誌內容過濾
- ✅ 與 Prometheus 無縫整合:同一個 Grafana 面板可同時顯示指標與日誌
- ✅
{app="nginx"} |= "error"= 在 nginx 日誌中搜尋含有 "error" 的行 - ✅ 成本遠低於 Elasticsearch(Loki 儲存成本約為 ELK 的 1/10)
Prometheus vs Loki
| 比較 | Prometheus | Loki | |------|:----------:|:----:| | 資料類型 | 數值指標 | 文字日誌 | | 索引方式 | Label 索引 + TSDB | Label 索引 + 原始日誌 | | 查詢語言 | PromQL | LogQL(基於 PromQL) | | 儲存成本 | 低 | 極低(不索引全文) | | 主要用途 | 監控與告警 | 除錯與稽核 |
# 從指標跳到日誌的關聯查詢
# 先找到高錯誤率的 Pod
# 再用同一個 Label 查詢該 Pod 的日誌
{namespace="production", pod=~"api-server.*"}
|= "error"
!= "timeout" # 排除已知的 timeout 錯誤
| json # 解析 JSON 格式日誌
| line_format "{{.message}}" # 只顯示 message 欄位
常見錯誤
程式碼範例
Loki:輕量級的日誌系統
Loki 是 Grafana 團隊開發的日誌聚合系統。跟 ELK Stack(Elasticsearch + Logstash + Kibana)不同,Loki 不索引日誌內容——只索引標籤,所以更省資源。
Loki vs ELK
| 比較 | Loki | ELK | |:----|:----|:---| | 索引方式 | 只索引標籤(label) | 全文索引 | | 儲存成本 | 低 | 高 | | 查詢語法 | LogQL | Lucene | | 與 Grafana 整合 | 原生整合 | 需要額外設定 |
下一章預告:OpenTelemetry
日誌告訴你發生了什麼事。下一章的分散式追蹤告訴你請求從哪裡來、經過哪些服務、花了多久。