Grafana + Loki + Promtailでログの可視化


この記事の概要

  • ちょっと気になっていたLokiがGAになったので触ってみる
  • アプリケーションはサーバーで稼働しているものを対象とする
    • →Promtailはアプリケーションサーバーに構築
  • Lokiはデータ永続化の観点で監視用サーバーに構築

※kubernetesでもpersistent volumeを使えばLokiを載せられるので時間があればチャレンジ

Document

Lokiの構築

1. binaryを以下のページからダウンロード

2. サーバーにscp等で送信

3. 解凍&配置

$ unzip loki-linux-amd64.zip
$ mkdir -p /opt/loki/{bin,conf}
$ cp loki-linux-amd64 /opt/loki/bin/loki

4. 設定ファイルを配置

$ cd /opt/loki/conf
$ curl https://raw.githubusercontent.com/grafana/loki/v1.4.1/cmd/loki/loki-local-config.yaml -o loki-config.yaml

5. 起動

$ vi /etc/systemd/system/loki.service
[Service]
ExecStart=/opt/loki/bin/loki -config.file=/opt/loki/conf/loki-config.yaml

$ systemctl start loki

promtailの構築

1. binaryを以下のページからダウンロード

2. サーバーにscp等で送信

3. 解凍&配置

$ unzip promtail-linux-amd64.zip
$ mkdir -p /opt/promtail/{bin,conf}
$ cp promtail-linux-amd64.zip /opt/promtail/bin/promtail

4. 設定ファイルを配置

$ cd /opt/promtail/conf
$ curl https://raw.githubusercontent.com/grafana/loki/v1.4.1/cmd/promtail/promtail-docker-config.yaml -o promtail-config.yaml

# 修正ポイントだけ記載
$ vi promtail-config.yaml
...
clients:
  - url: http://<監視用サーバー名>:3100/loki/api/v1/push
...
      __path__: <log file>
...

5. 起動

$ vi /etc/systemd/system/promtail.service
[Service]
ExecStart=/opt/promtail/bin/promtail -config.file=/opt/promtail/conf/promtail-config.yaml

$ systemctl start promtail

Grafanaの構築

kubernetes上に構築
※ダッシュボード等のデータの永続化をしたい場合はこちらをご参考ください

最新のGrafanaを使用していればLokiはデフォルトで有効になっているはず!

  • URLだけ設定すればとりあえず使える!
  • localhostの部分は適宜サーバーやkubernetesのservice名等に置き換えてください

Tips

ここからはやりたいことベースにどうすれば実現できるかを記載

特定のログを送らない

  • pipeline_stagesでaction: dropで定義
  • selectorはgrafanaとかで想定通りのログが抽出されるか確認するのがベター(自分への戒め)
  • 参考
scrape_configs:
- job_name: <job_name>
  pipeline_stages:
  - match:
      selector: '{app="<app>"} |~ ".*<Ignore regex>.*"'
      action: drop

ログをパースしてメトリクス化する

サンプルとしてログからレスポンスタイムを抽出して、メトリクス化してみます

ログサンプル
API end. [200] /path in 68 ms

Grafanaにて、以下のようにクエリを書くことで、ステータスごとパスごとのメトリクスにできます!

レスポンスの平均のサンプル
avg_over_time(
{job="<job_name>"} 
 |~ "API end"
 | regexp "API end. \\[(?P<status>[0-9]+)] (?P<path>[^ ]+) in (?P<response_time>[0-9]+)"
 | unwrap response_time [1m]
 ) by (status, path)

このblogが参考になりました
https://grafana.com/blog/2020/10/28/loki-2.0-released-transform-logs-as-youre-querying-them-and-set-up-alerts-within-loki/