InfraLab
GRAFANA-LOKI40 cmd

Grafana / Loki / LogQL チート集

Grafana の dashboard/変数/provisioning、Loki の LogQL ラベル抽出・集計、Promtail/Vector/Fluent Bit 連携、retention 運用をまとめたチート集。

更新日
2026-05-14
参照範囲
公式ドキュメント / man page / 主要ベンダーCLI
対象実装
主要 Linux / BSD / ネットワーク機器 CLI の一般的な実装
免責
OS とバージョン差分は実環境で確認してください。

40 / 40

CommandDescriptionExampleCopy
dashboard JSON panelsダッシュボード JSON の基本構造。{"title":"API","panels":[{"type":"timeseries","targets":[{"expr":"sum(rate(http_requests_total[5m]))"}]}]}
templating customcustom 変数を定義する。{"templating":{"list":[{"name":"env","type":"custom","query":"prod,stg,dev"}]}}
$__intervalパネル幅に応じた集計間隔を使う。sum by (job) (rate(http_requests_total[$__interval]))
$__rate_intervalrate に安全な間隔を使う。rate(container_cpu_usage_seconds_total[$__rate_interval])
annotationsデプロイイベントを注釈表示する。annotations: list: - name: deploy datasource: Prometheus expr: changes(deploy_revision[1m]) > 0
playlist複数ダッシュボードを巡回表示する。curl -H "Authorization: Bearer $TOKEN" https://grafana.example.com/api/playlists
provisioning dashboardsダッシュボード provisioning を設定する。apiVersion: 1 providers: - name: infra folder: Infra type: file options: { path: /var/lib/grafana/dashboards }
grafana-cli plugins installプラグインをインストールする。grafana-cli plugins install grafana-piechart-panel
dashboard API importAPI でダッシュボードを投入する。curl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d @dashboard.json https://grafana.example.com/api/dashboards/db
{job="nginx"}Loki のラベルセレクタ基本形。{job="nginx"}
|= "error"文字列を含む行だけ残す。{job="nginx"} |= "error"
!= "health"文字列を含まない行だけ残す。{job="nginx"} != "GET /health"
|~ regex正規表現に一致する行だけ残す。{app="api"} |~ "status=(5..|429)"
!~ regex正規表現に一致しない行だけ残す。{app="api"} !~ "DEBUG|TRACE"
| jsonJSON ログをパースする。{app="api"} | json | level="error"
| logfmtlogfmt ログをパースする。{app="api"} | logfmt | status >= 500
| patternパターンでフィールド抽出する。{job="nginx"} | pattern `<ip> - - <_> "<method> <path> <_>" <status> <_>`
| line_format出力行を整形する。{job="nginx"} | pattern `<ip> - - <_> "<method> <path> <_>" <status> <_>` | line_format "{{.ip}} {{.method}} {{.path}}"
| label_format抽出値をラベルとして整形する。{app="api"} | json | label_format endpoint="{{.method}} {{.path}}"
unwrap duration数値フィールドをメトリクス化する。{app="api"} | json | unwrap duration_ms
rate logsログ行の秒間レートを計算する。rate({job="nginx"} |= "error" [5m])
count_over_time期間内ログ件数を数える。count_over_time({app="api"} |= "timeout" [5m])
sum by levellevel ごとにログ件数を集計する。sum by (level) (count_over_time({app="api"} | json [5m]))
bytes_over_time期間内のログバイト量を計算する。bytes_over_time({namespace="prod"}[5m])
quantile_over_timeunwrap した値の分位点を出す。quantile_over_time(0.95, {app="api"} | json | unwrap duration_ms [5m])
topk log streamsログ量の多い stream を探す。topk(10, sum by (pod) (rate({namespace="prod"}[5m])))
loki retention configLoki retention を compactor で設定する。limits_config: retention_period: 744h compactor: retention_enabled: true delete_request_store: s3
ingester roleingester はログを受信して chunk 化する。kubectl -n observability get pod -l app.kubernetes.io/component=ingester
querier rolequerier は保存済み chunk を検索する。kubectl -n observability get pod -l app.kubernetes.io/component=querier
compactor rolecompactor は index 圧縮と retention 削除を担う。kubectl -n observability logs deploy/loki-compactor --tail=100
promtail pipeline jsonPromtail で JSON ログをラベル化する。pipeline_stages: - json: expressions: { level: level, msg: message } - labels: level:
promtail pipeline regexPromtail で正規表現抽出する。pipeline_stages: - regex: expression: "^(?P<ip>\S+) .* (?P<status>[0-9]{3})$" - labels: status:
Vector to LokiVector から Loki sink へ送る。sinks.loki.type = "loki" sinks.loki.endpoint = "https://loki.example.com" sinks.loki.inputs = ["kubernetes_logs"]
Fluent Bit Loki outputFluent Bit の Loki 出力設定。[OUTPUT] Name loki Match kube.* Host loki.example.com Labels job=fluent-bit
logcli queryCLI で LogQL を実行する。logcli --addr=https://loki.example.com query '{job="nginx"} |= "error"' --limit=20
logcli labels利用可能なラベルを確認する。logcli --addr=https://loki.example.com labels
Loki readinessLoki の readiness を確認する。curl -f http://loki.example.com/ready
Grafana datasource APILoki datasource を API で作る。curl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"name":"Loki","type":"loki","url":"http://loki:3100"}' https://grafana.example.com/api/datasources
Explore URLExplore へ LogQL 付きで遷移する。https://grafana.example.com/explore?left={"datasource":"Loki","queries":[{"expr":"{app=\"api\"} |= \"error\""}]}
derived fieldsログから trace ID リンクを作る。derivedFields: - name: TraceID matcherRegex: "trace_id=(\w+)" url: "https://tempo.example.com/trace/$${__value.raw}"
Related