example_metrics_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "fmt"
  17. "io/ioutil"
  18. "log"
  19. "net"
  20. "net/http"
  21. "strings"
  22. "github.com/coreos/etcd/clientv3"
  23. grpcprom "github.com/grpc-ecosystem/go-grpc-prometheus"
  24. "github.com/prometheus/client_golang/prometheus"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. )
  28. func ExampleMetrics_range() {
  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", ":47989")
  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, prometheus.Handler())
  51. }()
  52. defer func() {
  53. ln.Close()
  54. <-donec
  55. }()
  56. // make an http request to fetch all prometheus metrics
  57. url := "http://localhost:47989/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: grpc_client_started_total{grpc_method="Range",grpc_service="etcdserverpb.KV",grpc_type="unary"} 1
  75. }