prometheus.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package prometheus exposes go-metrics into a Prometheus format.
  17. package prometheus
  18. import (
  19. "fmt"
  20. "net/http"
  21. "sort"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/metrics"
  24. )
  25. // Handler returns an HTTP handler which dump metrics in Prometheus format.
  26. func Handler(reg metrics.Registry) http.Handler {
  27. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  28. // Gather and pre-sort the metrics to avoid random listings
  29. var names []string
  30. reg.Each(func(name string, i interface{}) {
  31. names = append(names, name)
  32. })
  33. sort.Strings(names)
  34. // Aggregate all the metrics into a Prometheus collector
  35. c := newCollector()
  36. for _, name := range names {
  37. i := reg.Get(name)
  38. switch m := i.(type) {
  39. case metrics.Counter:
  40. c.addCounter(name, m.Snapshot())
  41. case metrics.Gauge:
  42. c.addGauge(name, m.Snapshot())
  43. case metrics.GaugeFloat64:
  44. c.addGaugeFloat64(name, m.Snapshot())
  45. case metrics.Histogram:
  46. c.addHistogram(name, m.Snapshot())
  47. case metrics.Meter:
  48. c.addMeter(name, m.Snapshot())
  49. case metrics.Timer:
  50. c.addTimer(name, m.Snapshot())
  51. case metrics.ResettingTimer:
  52. c.addResettingTimer(name, m.Snapshot())
  53. default:
  54. log.Warn("Unknown Prometheus metric type", "type", fmt.Sprintf("%T", i))
  55. }
  56. }
  57. w.Header().Add("Content-Type", "text/plain")
  58. w.Header().Add("Content-Length", fmt.Sprint(c.buff.Len()))
  59. w.Write(c.buff.Bytes())
  60. })
  61. }