handler.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package metrics
  2. import (
  3. "net/http"
  4. "github.com/prometheus/client_golang/prometheus"
  5. "github.com/prometheus/client_golang/prometheus/promhttp"
  6. )
  7. // HTTPHandlerOpts describes a set of configurable options of http metrics
  8. type HTTPHandlerOpts struct {
  9. DurationBuckets []float64
  10. RequestSizeBuckets []float64
  11. ResponseSizeBuckets []float64
  12. }
  13. const (
  14. InstrumentHandlerResponseSize = iota
  15. InstrumentHandlerRequestSize
  16. InstrumentHandlerDuration
  17. InstrumentHandlerCounter
  18. InstrumentHandlerInFlight
  19. )
  20. type HTTPMetric struct {
  21. prometheus.Collector
  22. handlerType int
  23. }
  24. var (
  25. defaultDurationBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 25, 60}
  26. defaultRequestSizeBuckets = prometheus.ExponentialBuckets(1024, 2, 22) //1K to 4G
  27. defaultResponseSizeBuckets = defaultRequestSizeBuckets
  28. )
  29. // Handler returns the global http.Handler that provides the prometheus
  30. // metrics format on GET requests. This handler is no longer instrumented.
  31. func Handler() http.Handler {
  32. return promhttp.Handler()
  33. }
  34. func InstrumentHandler(metrics []*HTTPMetric, handler http.Handler) http.HandlerFunc {
  35. return InstrumentHandlerFunc(metrics, handler.ServeHTTP)
  36. }
  37. func InstrumentHandlerFunc(metrics []*HTTPMetric, handlerFunc http.HandlerFunc) http.HandlerFunc {
  38. var handler http.Handler
  39. handler = http.HandlerFunc(handlerFunc)
  40. for _, metric := range metrics {
  41. switch metric.handlerType {
  42. case InstrumentHandlerResponseSize:
  43. if collector, ok := metric.Collector.(prometheus.ObserverVec); ok {
  44. handler = promhttp.InstrumentHandlerResponseSize(collector, handler)
  45. }
  46. case InstrumentHandlerRequestSize:
  47. if collector, ok := metric.Collector.(prometheus.ObserverVec); ok {
  48. handler = promhttp.InstrumentHandlerRequestSize(collector, handler)
  49. }
  50. case InstrumentHandlerDuration:
  51. if collector, ok := metric.Collector.(prometheus.ObserverVec); ok {
  52. handler = promhttp.InstrumentHandlerDuration(collector, handler)
  53. }
  54. case InstrumentHandlerCounter:
  55. if collector, ok := metric.Collector.(*prometheus.CounterVec); ok {
  56. handler = promhttp.InstrumentHandlerCounter(collector, handler)
  57. }
  58. case InstrumentHandlerInFlight:
  59. if collector, ok := metric.Collector.(prometheus.Gauge); ok {
  60. handler = promhttp.InstrumentHandlerInFlight(collector, handler)
  61. }
  62. }
  63. }
  64. return handler.ServeHTTP
  65. }