【go-kit教程】go-kit集成Prometheus
在 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()) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
上次更新: 2023/04/16, 18:35:33