github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-kit/kit/metrics/README.md (about) 1 # package metrics 2 3 `package metrics` provides a set of uniform interfaces for service instrumentation. 4 It has 5 [counters](http://prometheus.io/docs/concepts/metric_types/#counter), 6 [gauges](http://prometheus.io/docs/concepts/metric_types/#gauge), and 7 [histograms](http://prometheus.io/docs/concepts/metric_types/#histogram), 8 and provides adapters to popular metrics packages, like 9 [expvar](https://golang.org/pkg/expvar), 10 [StatsD](https://github.com/etsy/statsd), and 11 [Prometheus](https://prometheus.io). 12 13 ## Rationale 14 15 Code instrumentation is absolutely essential to achieve 16 [observability](https://speakerdeck.com/mattheath/observability-in-micro-service-architectures) 17 into a distributed system. 18 Metrics and instrumentation tools have coalesced around a few well-defined idioms. 19 `package metrics` provides a common, minimal interface those idioms for service authors. 20 21 ## Usage 22 23 A simple counter, exported via expvar. 24 25 ```go 26 import ( 27 "github.com/go-kit/kit/metrics" 28 "github.com/go-kit/kit/metrics/expvar" 29 ) 30 31 func main() { 32 var myCount metrics.Counter 33 myCount = expvar.NewCounter("my_count") 34 myCount.Add(1) 35 } 36 ``` 37 38 A histogram for request duration, 39 exported via a Prometheus summary with dynamically-computed quantiles. 40 41 ```go 42 import ( 43 "time" 44 45 stdprometheus "github.com/prometheus/client_golang/prometheus" 46 47 "github.com/go-kit/kit/metrics" 48 "github.com/go-kit/kit/metrics/prometheus" 49 ) 50 51 func main() { 52 var dur metrics.Histogram = prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ 53 Namespace: "myservice", 54 Subsystem: "api", 55 Name: "request_duration_seconds", 56 Help: "Total time spent serving requests.", 57 }, []string{}) 58 // ... 59 } 60 61 func handleRequest(dur metrics.Histogram) { 62 defer func(begin time.Time) { dur.Observe(time.Since(begin).Seconds()) }(time.Now()) 63 // handle request 64 } 65 ``` 66 67 A gauge for the number of goroutines currently running, exported via StatsD. 68 69 ```go 70 import ( 71 "net" 72 "os" 73 "runtime" 74 "time" 75 76 "github.com/go-kit/kit/metrics" 77 "github.com/go-kit/kit/metrics/statsd" 78 ) 79 80 func main() { 81 statsd := statsd.New("foo_svc.", log.NewNopLogger()) 82 report := time.NewTicker(5 * time.Second) 83 defer report.Stop() 84 go statsd.SendLoop(report.C, "tcp", "statsd.internal:8125") 85 goroutines := statsd.NewGauge("goroutine_count") 86 go exportGoroutines(goroutines) 87 // ... 88 } 89 90 func exportGoroutines(g metrics.Gauge) { 91 for range time.Tick(time.Second) { 92 g.Set(float64(runtime.NumGoroutine())) 93 } 94 } 95 ``` 96 97 For more information, see [the package documentation](https://godoc.org/github.com/go-kit/kit/metrics).