Metrics

Interface

Counter, Gauge, Observer are the three major metric interface of kratos.

Counter

  1. type Counter interface {
  2. With(lvs ...string) Counter
  3. Inc()
  4. Add(delta float64)
  5. }

Counter is just a standard counter. It should expose Inc and Add method. This counter can only count the increasing. It usually used at counting the numbers of errors or QPS.

Gauge

  1. type Gauge interface {
  2. With(lvs ...string) Gauge
  3. Set(value float64)
  4. Add(delta float64)
  5. Sub(delta float64)
  6. }

Gauge is a status indicator. It records the current status of service. The value of gauge may increase or decrease. It usually used at monitoring CPU usage or Mem usage etc.

Observer

  1. type Observer interface {
  2. With(lvs ...string) Observer
  3. Observe(float64)
  4. }

Observer is a kind of more complex metric. It provides more extra information for monitoring sums, quantities and percentages. It is corresponding to Prometheus’Histogram and Summary. The Histogram is used for record the counts in different buckets, such as the count of requests in different latency ranges. The Histogram is efficient. Summary records the percentiles, because of extra computation, it maybe slower.

Usage

Metrics in server

  1. import (
  2. "github.com/go-kratos/kratos/v2/middleware"
  3. kmetrics "github.com/go-kratos/prometheus/metrics"
  4. "github.com/go-kratos/kratos/v2/middleware/metrics"
  5. "github.com/go-kratos/kratos/v2/transport/http"
  6. "github.com/prometheus/client_golang/prometheus"
  7. )
  8. func NewHTTPServer(c *conf.Server) *http.Server {
  9. // for prometheus
  10. counter := prometheus.NewCounterVec(prometheus.CounterOpts{Name: "kratos_counter"}, []string{"server", "qps"})
  11. var opts = []http.ServerOption{
  12. http.Middleware(
  13. middleware.Chain(
  14. recovery.Recovery(),
  15. metrics.Server(metrics.WithRequests(kmetrics.NewCounter(counter))),
  16. ),
  17. ),
  18. }

Metrics in Client

  1. import (
  2. "context"
  3. "github.com/go-kratos/kratos/v2/middleware"
  4. kmetrics "github.com/go-kratos/prometheus/metrics"
  5. "github.com/go-kratos/kratos/v2/middleware/metrics"
  6. "github.com/go-kratos/kratos/v2/transport/http"
  7. "github.com/prometheus/client_golang/prometheus"
  8. )
  9. func useClient() {
  10. counter := prometheus.NewCounterVec(prometheus.CounterOpts{Name: "kratos_counter"},
  11. []string{"client", "qps"})
  12. client, _ := http.NewClient(context.Background(),
  13. http.WithMiddleware(metrics.Client(metrics.WithRequests(kmetrics.NewCounter(counter)))))
  14. // ...
  15. }

References