registry.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 mutex-protected mapping of names to metrics.
  16. type StandardRegistry struct {
  17. mutex *sync.Mutex
  18. metrics map[string]interface{}
  19. }
  20. // Create a new registry.
  21. func NewRegistry() *StandardRegistry {
  22. return &StandardRegistry{
  23. &sync.Mutex{},
  24. make(map[string]interface{}),
  25. }
  26. }
  27. // Call the given function for each registered metric.
  28. func (r *StandardRegistry) Each(f func(string, interface{})) {
  29. r.mutex.Lock()
  30. defer r.mutex.Unlock()
  31. for name, i := range r.metrics {
  32. f(name, i)
  33. }
  34. }
  35. // Get the metric by the given name or nil if none is registered.
  36. func (r *StandardRegistry) Get(name string) interface{} {
  37. r.mutex.Lock()
  38. defer r.mutex.Unlock()
  39. return r.metrics[name]
  40. }
  41. // Register the given metric under the given name.
  42. func (r *StandardRegistry) Register(name string, i interface{}) {
  43. switch i.(type) {
  44. case Counter, Gauge, Healthcheck, Histogram, Meter, Timer:
  45. r.mutex.Lock()
  46. defer r.mutex.Unlock()
  47. r.metrics[name] = i
  48. }
  49. }
  50. // Run all registered healthchecks.
  51. func (r *StandardRegistry) RunHealthchecks() {
  52. r.mutex.Lock()
  53. defer r.mutex.Unlock()
  54. for _, i := range r.metrics {
  55. if h, ok := i.(Healthcheck); ok {
  56. h.Check()
  57. }
  58. }
  59. }
  60. // Unregister the metric with the given name.
  61. func (r *StandardRegistry) Unregister(name string) {
  62. r.mutex.Lock()
  63. defer r.mutex.Unlock()
  64. delete(r.metrics, name)
  65. }