このチュートリアルでは、シンプルなGo HTTPサーバーを作成し、サーバーで処理されたリクエストの総数をカウントするカウンタメトリクスを追加して計装します。
ここでは、/ping
エンドポイントを持つシンプルなHTTPサーバーがあり、pong
をレスポンスとして返します。
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
と表示されるはずです。
次に、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")
}
次に、カウンタをDefault Registerに登録し、メトリクスを公開します。
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc("/ping", ping)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)
}
prometheus.MustRegister
関数は、pingCounterをデフォルトのRegisterに登録します。メトリクスを公開するために、Go Prometheusクライアントライブラリはpromhttpパッケージを提供しています。promhttp.Handler()
は、Default Registerに登録されたメトリクスを公開する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回呼び出されたことを示しています。
Default Registerには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
このドキュメントはオープンソースです。課題の報告やプルリクエストの送信により、改善にご協力ください。