Metrics

Metrics middleware is used to monitor performance metrics for services, counting request time and request counts.

Configuration

Two configuration methods are available in metrics middleware WithSeconds() and WithRequests()

WithSeconds()

  1. func WithSeconds(c metrics.Observer) Option {
  2. return func(o *options) {
  3. o.seconds = c
  4. }
  5. }

The Observer histogram used to set up the metrics middleware statistics request.

WithRequests()

  1. func WithRequests(c metrics.Counter) Option {
  2. return func(o *options) {
  3. o.requests = c
  4. }
  5. }

The Counter counter used to set the metrics middleware statistics request count.

Usage

Prometheus

  1. // https://github.com/go-kratos/examples/tree/main/metrics
  2. _metricSeconds = prometheus.NewHistogramVec(prometheus.HistogramOpts{
  3. Namespace: "server",
  4. Subsystem: "requests",
  5. Name: "duration_ms",
  6. Help: "server requests duration(ms).",
  7. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  8. }, []string{"kind", "operation"})
  9. _metricRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
  10. Namespace: "client",
  11. Subsystem: "requests",
  12. Name: "code_total",
  13. Help: "The total number of processed requests",
  14. }, []string{"kind", "operation", "code", "reason"})
  15. prometheus.MustRegister(_metricSeconds, _metricRequests)
  16. httpSrv.Handle("/metrics", promhttp.Handler())

To configure metrics in servers

  1. // grpc sever
  2. grpcSrv := grpc.NewServer(
  3. grpc.Address(":9000"),
  4. grpc.Middleware(
  5. metrics.Server(
  6. metrics.WithSeconds(prom.NewHistogram(_metricSeconds)),
  7. metrics.WithRequests(prom.NewCounter(_metricRequests)),
  8. ),
  9. ),
  10. )
  11. // http server
  12. httpSrv := http.NewServer(
  13. http.Address(":8000"),
  14. http.Middleware(
  15. metrics.Server(
  16. metrics.WithSeconds(prom.NewHistogram(_metricSeconds)),
  17. metrics.WithRequests(prom.NewCounter(_metricRequests)),
  18. ),
  19. ),
  20. )

To configure metrics in clients

  1. // grpc client
  2. conn, err := grpc.DialInsecure(
  3. context.Background(),
  4. grpc.WithEndpoint("127.0.0.1:9000"),
  5. grpc.WithMiddleware(
  6. metrics.Client(
  7. metrics.WithSeconds(prom.NewHistogram(_metricSeconds)),
  8. metrics.WithRequests(prom.NewCounter(_metricRequests)),
  9. ),
  10. ),
  11. )
  12. // http client
  13. conn, err := http.NewClient(
  14. context.Background(),
  15. http.WithEndpoint("127.0.0.1:8000"),
  16. http.WithMiddleware(
  17. metrics.Client(
  18. metrics.WithSeconds(prom.NewHistogram(_metricSeconds)),
  19. metrics.WithRequests(prom.NewCounter(_metricRequests)),
  20. ),
  21. ),
  22. )

References