このチュートリアルでは、シンプルなGo HTTPサーバーを作成し、カウンターメトリックを追加してサーバーが処理したリクエストの総数をカウントすることで、インストルメンテーションを行います。
ここでは、レスポンスとして「pong」を返す/ping
エンドポイントを持つシンプルな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
ブラウザでhttp://localhost:8090/ping
を開くと、「pong」が表示されます。
次に、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_request_count
は/ping
エンドポイントが3回呼び出されたことを示しています。
デフォルトレジスタには、Goランタイムメトリックのコレクターが含まれており、そのためgo_threads
、go_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
このドキュメントはオープンソースです。問題点やプルリクエストを提出して、改善にご協力ください。