server.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2016 Michal Witkowski. All Rights Reserved.
  2. // See LICENSE for licensing terms.
  3. // gRPC Prometheus monitoring interceptors for server-side gRPC.
  4. package grpc_prometheus
  5. import (
  6. prom "github.com/prometheus/client_golang/prometheus"
  7. "google.golang.org/grpc"
  8. )
  9. var (
  10. // DefaultServerMetrics is the default instance of ServerMetrics. It is
  11. // intended to be used in conjunction the default Prometheus metrics
  12. // registry.
  13. DefaultServerMetrics = NewServerMetrics()
  14. // UnaryServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Unary RPCs.
  15. UnaryServerInterceptor = DefaultServerMetrics.UnaryServerInterceptor()
  16. // StreamServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Streaming RPCs.
  17. StreamServerInterceptor = DefaultServerMetrics.StreamServerInterceptor()
  18. )
  19. func init() {
  20. prom.MustRegister(DefaultServerMetrics.serverStartedCounter)
  21. prom.MustRegister(DefaultServerMetrics.serverHandledCounter)
  22. prom.MustRegister(DefaultServerMetrics.serverStreamMsgReceived)
  23. prom.MustRegister(DefaultServerMetrics.serverStreamMsgSent)
  24. }
  25. // Register takes a gRPC server and pre-initializes all counters to 0. This
  26. // allows for easier monitoring in Prometheus (no missing metrics), and should
  27. // be called *after* all services have been registered with the server. This
  28. // function acts on the DefaultServerMetrics variable.
  29. func Register(server *grpc.Server) {
  30. DefaultServerMetrics.InitializeMetrics(server)
  31. }
  32. // EnableHandlingTimeHistogram turns on recording of handling time
  33. // of RPCs. Histogram metrics can be very expensive for Prometheus
  34. // to retain and query. This function acts on the DefaultServerMetrics
  35. // variable and the default Prometheus metrics registry.
  36. func EnableHandlingTimeHistogram(opts ...HistogramOption) {
  37. DefaultServerMetrics.EnableHandlingTimeHistogram(opts...)
  38. prom.Register(DefaultServerMetrics.serverHandledHistogram)
  39. }