Qi
go-kit集成Prometheus

go-kit集成Prometheus

作者: Qi 发表时间: 2024-02-06 49

在 Go kit 中集成 Prometheus 进行 API 监控可以帮助开发人员更好地了解系统的性能和行为,提高系统的可观察性和可靠性。下面是一个简单的示例,演示如何在 Go kit 中集成 Prometheus 进行 API 监控:

package main

import (
	"net/http"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/metrics/prometheus"
	"github.com/go-kit/kit/metrics/provider"
	"github.com/go-kit/kit/transport"
	httptransport "github.com/go-kit/kit/transport/http"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	// 创建 Prometheus 监控器
	fieldKeys := []string{"method", "error"}
	requestCount := prometheus.NewCounterFrom(provider.NewProvider(), prometheus.CounterOpts{
		Namespace: "my_api",
		Name:      "request_count",
		Help:      "Number of requests received.",
	}, fieldKeys)
	requestLatency := prometheus.NewSummaryFrom(provider.NewProvider(), prometheus.SummaryOpts{
		Namespace: "my_api",
		Name:      "request_latency",
		Help:      "Total duration of requests in microseconds.",
	}, fieldKeys)

	// 创建 endpoint
	helloEndpoint := func() string {
		return "Hello, World!"
	}
	helloEndpoint = transport.NewServer(
		helloEndpoint,
		func(ctx context.Context, r *http.Request) (interface{}, error) {
			return nil, nil
		},
		func(ctx context.Context, w http.ResponseWriter, response interface{}) error {
			w.Header().Set("Content-Type", "text/plain; charset=utf-8")
			fmt.Fprint(w, response.(string))
			return nil
		},
		transport.ServerErrorLogger(log.NewNopLogger()),
		transport.ServerErrorEncoder(errorEncoder),
		transport.ServerBefore(prometheus.HTTPToContext()),
	).Endpoint()

	// 创建 HTTP server
	r := mux.NewRouter()
	r.Handle("/hello", httptransport.NewServer(
		helloEndpoint,
		httpDecodeRequest,
		httpEncodeResponse,
		httptransport.ServerBefore(prometheus.HTTPToContext()),
		httptransport.ServerErrorLogger(log.NewNopLogger()),
		httptransport.ServerErrorEncoder(errorEncoder),
		httptransport.ServerBefore(prometheus.HTTPToContext()),
	)).Methods("GET")
	r.Handle("/metrics", promhttp.Handler())

	fmt.Println("listening on :8080...")
	http.ListenAndServe(":8080", r)
}

func httpDecodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
	return nil, nil
}

func httpEncodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	fmt.Fprint(w, response.(string))
	return nil
}

func errorEncoder(_ context.Context, err error, w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusBadRequest)
	fmt.Fprint(w, err.Error())
}
go-kit
mysql数据库

本文作者: Qi

版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

我也是有底线的哦!

联系我呀

技术支持

学习网站

博主寄诗

学习是一辈子的事情,保持好奇心和学习的态度。

面对生活的挑战,要保持乐观的心态和勇气,相信自己能够克服困难。