registry.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 { f(name, i) }
  32. r.mutex.Unlock()
  33. }
  34. // Get the metric by the given name or nil if none is registered.
  35. func (r *StandardRegistry) Get(name string) interface{} {
  36. r.mutex.Lock()
  37. i := r.metrics[name]
  38. r.mutex.Unlock()
  39. return i
  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. r.metrics[name] = i
  47. r.mutex.Unlock()
  48. }
  49. }
  50. // Run all registered healthchecks.
  51. func (r *StandardRegistry) RunHealthchecks() {
  52. r.mutex.Lock()
  53. for _, i := range r.metrics {
  54. if h, ok := i.(Healthcheck); ok { h.Check() }
  55. }
  56. r.mutex.Unlock()
  57. }
  58. // Unregister the metric with the given name.
  59. func (r *StandardRegistry) Unregister(name string) {
  60. r.mutex.Lock()
  61. r.metrics[name] = nil, false
  62. r.mutex.Unlock()
  63. }