registry.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package metrics
  2. import "sync"
  3. // A Registry holds references to a set of metrics by name and can iterate
  4. // over them, calling callback functions provided by the user.
  5. //
  6. // This is an interface so as to encourage other structs to implement
  7. // the Registry API as appropriate.
  8. type Registry interface {
  9. Each(func(string, interface{}))
  10. Get(string) interface{}
  11. Register(string, interface{})
  12. RunHealthchecks()
  13. Unregister(string)
  14. }
  15. // The standard implementation of a Registry is a set of mutex-protected
  16. // maps of names to metrics.
  17. type StandardRegistry struct {
  18. mutex *sync.Mutex
  19. metrics map[string]interface{}
  20. }
  21. // Create a new registry.
  22. func NewRegistry() *StandardRegistry {
  23. return &StandardRegistry{
  24. &sync.Mutex{},
  25. make(map[string]interface{}),
  26. }
  27. }
  28. // Call the given function for each registered metric.
  29. func (r *StandardRegistry) Each(f func(string, interface{})) {
  30. r.mutex.Lock()
  31. for name, i := range r.metrics {
  32. f(name, i)
  33. }
  34. r.mutex.Unlock()
  35. }
  36. // Get the metric by the given name or nil if none is registered.
  37. func (r *StandardRegistry) Get(name string) interface{} {
  38. r.mutex.Lock()
  39. i := r.metrics[name]
  40. r.mutex.Unlock()
  41. return i
  42. }
  43. // Register the given metric under the given name.
  44. func (r *StandardRegistry) Register(name string, i interface{}) {
  45. switch i.(type) {
  46. case Counter, Gauge, Healthcheck, Histogram, Meter, Timer:
  47. r.mutex.Lock()
  48. r.metrics[name] = i
  49. r.mutex.Unlock()
  50. }
  51. }
  52. // Run all registered healthchecks.
  53. func (r *StandardRegistry) RunHealthchecks() {
  54. r.mutex.Lock()
  55. for _, i := range r.metrics {
  56. if h, ok := i.(Healthcheck); ok {
  57. h.Check()
  58. }
  59. }
  60. r.mutex.Unlock()
  61. }
  62. // Unregister the metric with the given name.
  63. func (r *StandardRegistry) Unregister(name string) {
  64. r.mutex.Lock()
  65. delete(r.metrics, name)
  66. r.mutex.Unlock()
  67. }