go.etcd.io/etcd@v3.3.27+incompatible/clientv3/example_metrics_test.go (about) 1 // Copyright 2016 The etcd Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package clientv3_test 16 17 import ( 18 "context" 19 "fmt" 20 "io/ioutil" 21 "log" 22 "net" 23 "net/http" 24 "strings" 25 26 "github.com/coreos/etcd/clientv3" 27 28 grpcprom "github.com/grpc-ecosystem/go-grpc-prometheus" 29 "github.com/prometheus/client_golang/prometheus/promhttp" 30 "google.golang.org/grpc" 31 ) 32 33 func ExampleClient_metrics() { 34 cli, err := clientv3.New(clientv3.Config{ 35 Endpoints: endpoints, 36 DialOptions: []grpc.DialOption{ 37 grpc.WithUnaryInterceptor(grpcprom.UnaryClientInterceptor), 38 grpc.WithStreamInterceptor(grpcprom.StreamClientInterceptor), 39 }, 40 }) 41 if err != nil { 42 log.Fatal(err) 43 } 44 defer cli.Close() 45 46 // get a key so it shows up in the metrics as a range RPC 47 cli.Get(context.TODO(), "test_key") 48 49 // listen for all Prometheus metrics 50 ln, err := net.Listen("tcp", ":0") 51 if err != nil { 52 log.Fatal(err) 53 } 54 donec := make(chan struct{}) 55 go func() { 56 defer close(donec) 57 http.Serve(ln, promhttp.Handler()) 58 }() 59 defer func() { 60 ln.Close() 61 <-donec 62 }() 63 64 // make an http request to fetch all Prometheus metrics 65 url := "http://" + ln.Addr().String() + "/metrics" 66 resp, err := http.Get(url) 67 if err != nil { 68 log.Fatalf("fetch error: %v", err) 69 } 70 b, err := ioutil.ReadAll(resp.Body) 71 resp.Body.Close() 72 if err != nil { 73 log.Fatalf("fetch error: reading %s: %v", url, err) 74 } 75 76 // confirm range request in metrics 77 for _, l := range strings.Split(string(b), "\n") { 78 if strings.Contains(l, `grpc_client_started_total{grpc_method="Range"`) { 79 fmt.Println(l) 80 break 81 } 82 } 83 // Output: 84 // grpc_client_started_total{grpc_method="Range",grpc_service="etcdserverpb.KV",grpc_type="unary"} 1 85 }