example_metrics_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. package clientv3_test
  15. import (
  16. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "log"
  20. "net"
  21. "net/http"
  22. "strings"
  23. "go.etcd.io/etcd/clientv3"
  24. grpcprom "github.com/grpc-ecosystem/go-grpc-prometheus"
  25. "github.com/prometheus/client_golang/prometheus/promhttp"
  26. "google.golang.org/grpc"
  27. )
  28. func ExampleClient_metrics() {
  29. cli, err := clientv3.New(clientv3.Config{
  30. Endpoints: endpoints,
  31. DialOptions: []grpc.DialOption{
  32. grpc.WithUnaryInterceptor(grpcprom.UnaryClientInterceptor),
  33. grpc.WithStreamInterceptor(grpcprom.StreamClientInterceptor),
  34. },
  35. })
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. defer cli.Close()
  40. // get a key so it shows up in the metrics as a range RPC
  41. cli.Get(context.TODO(), "test_key")
  42. // listen for all Prometheus metrics
  43. ln, err := net.Listen("tcp", ":0")
  44. if err != nil {
  45. log.Fatal(err)
  46. }
  47. donec := make(chan struct{})
  48. go func() {
  49. defer close(donec)
  50. http.Serve(ln, promhttp.Handler())
  51. }()
  52. defer func() {
  53. ln.Close()
  54. <-donec
  55. }()
  56. // make an http request to fetch all Prometheus metrics
  57. url := "http://" + ln.Addr().String() + "/metrics"
  58. resp, err := http.Get(url)
  59. if err != nil {
  60. log.Fatalf("fetch error: %v", err)
  61. }
  62. b, err := ioutil.ReadAll(resp.Body)
  63. resp.Body.Close()
  64. if err != nil {
  65. log.Fatalf("fetch error: reading %s: %v", url, err)
  66. }
  67. // confirm range request in metrics
  68. for _, l := range strings.Split(string(b), "\n") {
  69. if strings.Contains(l, `grpc_client_started_total{grpc_method="Range"`) {
  70. fmt.Println(l)
  71. break
  72. }
  73. }
  74. // Output:
  75. // grpc_client_started_total{grpc_method="Range",grpc_service="etcdserverpb.KV",grpc_type="unary"} 1
  76. }