Go で書かれた HTTP サーバーの計測

このチュートリアルでは、シンプルな Go HTTP サーバーを作成し、サーバーが処理したリクエストの合計数をカウントするためのカウンターメトリクスを追加して計測を行います。

ここに、/ping エンドポイントを持ち、pong を応答として返すシンプルな HTTP サーバーがあります。

package main

import (
   "fmt"
   "net/http"
)

func ping(w http.ResponseWriter, req *http.Request){
   fmt.Fprintf(w,"pong")
}

func main() {
   http.HandleFunc("/ping",ping)

   http.ListenAndServe(":8090", nil)
}

サーバーをコンパイルして実行します

go build server.go
./server

ブラウザで https://:8090/ping を開くと、pong と表示されるはずです。

Server

次に、ping エンドポイントへのリクエスト数を計測するメトリクスをサーバーに追加しましょう。リクエスト数は減ることがなく、常に増加するため、カウンターメトリクスタイプが適しています。

Prometheus カウンターを作成する

var pingCounter = prometheus.NewCounter(
   prometheus.CounterOpts{
       Name: "ping_request_count",
       Help: "No of request handled by Ping handler",
   },
)

次に、pingCounter.Inc() を使用してカウンターのカウントを増やすように ping ハンドラーを更新しましょう。

func ping(w http.ResponseWriter, req *http.Request) {
   pingCounter.Inc()
   fmt.Fprintf(w, "pong")
}

その後、カウンターをデフォルトレジスターに登録し、メトリクスを公開します。

func main() {
   prometheus.MustRegister(pingCounter)
   http.HandleFunc("/ping", ping)
   http.Handle("/metrics", promhttp.Handler())
   http.ListenAndServe(":8090", nil)
}

prometheus.MustRegister 関数は、pingCounter をデフォルトのレジスターに登録します。メトリクスを公開するために、Go Prometheus クライアントライブラリは promhttp パッケージを提供します。promhttp.Handler() は、デフォルトのレジスターに登録されたメトリクスを公開する http.Handler を提供します。

サンプルコードは、

package main

import (
   "fmt"
   "net/http"

   "github.com/prometheus/client_golang/prometheus"
   "github.com/prometheus/client_golang/prometheus/promhttp"
)

var pingCounter = prometheus.NewCounter(
   prometheus.CounterOpts{
       Name: "ping_request_count",
       Help: "No of request handled by Ping handler",
   },
)

func ping(w http.ResponseWriter, req *http.Request) {
   pingCounter.Inc()
   fmt.Fprintf(w, "pong")
}

func main() {
   prometheus.MustRegister(pingCounter)

   http.HandleFunc("/ping", ping)
   http.Handle("/metrics", promhttp.Handler())
   http.ListenAndServe(":8090", nil)
}

例を実行する

go mod init prom_example
go mod tidy
go run server.go

これで、localhost:8090/ping エンドポイントを数回叩き、localhost:8090 にリクエストを送信するとメトリクスが提供されます。

Ping Metric

ここでは、ping_request_count/ping エンドポイントが3回呼び出されたことを示しています。

デフォルトのレジスターには Go ランタイムメトリクスのコレクターが含まれているため、go_threadsgo_goroutines などの他のメトリクスも表示されます。

最初のメトリクスエクスポーターを構築しました。次に、Prometheus の設定を更新して、サーバーからメトリクスをスクレイプするようにしましょう。

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: simple_server
    static_configs:
      - targets: ["localhost:8090"]

prometheus --config.file=prometheus.yml

このページの内容