json.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package metrics
  2. import (
  3. "encoding/json"
  4. "io"
  5. "time"
  6. )
  7. // MarshalJSON returns a byte slice containing a JSON representation of all
  8. // the metrics in the Registry.
  9. func (r *StandardRegistry) MarshalJSON() ([]byte, error) {
  10. data := make(map[string]map[string]interface{})
  11. r.Each(func(name string, i interface{}) {
  12. values := make(map[string]interface{})
  13. switch metric := i.(type) {
  14. case Counter:
  15. values["count"] = metric.Count()
  16. case Gauge:
  17. values["value"] = metric.Value()
  18. case GaugeFloat64:
  19. values["value"] = metric.Value()
  20. case Healthcheck:
  21. values["error"] = nil
  22. metric.Check()
  23. if err := metric.Error(); nil != err {
  24. values["error"] = metric.Error().Error()
  25. }
  26. case Histogram:
  27. h := metric.Snapshot()
  28. ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
  29. values["count"] = h.Count()
  30. values["min"] = h.Min()
  31. values["max"] = h.Max()
  32. values["mean"] = h.Mean()
  33. values["stddev"] = h.StdDev()
  34. values["median"] = ps[0]
  35. values["75%"] = ps[1]
  36. values["95%"] = ps[2]
  37. values["99%"] = ps[3]
  38. values["99.9%"] = ps[4]
  39. case Meter:
  40. m := metric.Snapshot()
  41. values["count"] = m.Count()
  42. values["1m.rate"] = m.Rate1()
  43. values["5m.rate"] = m.Rate5()
  44. values["15m.rate"] = m.Rate15()
  45. values["mean.rate"] = m.RateMean()
  46. case Timer:
  47. t := metric.Snapshot()
  48. ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
  49. values["count"] = t.Count()
  50. values["min"] = t.Min()
  51. values["max"] = t.Max()
  52. values["mean"] = t.Mean()
  53. values["stddev"] = t.StdDev()
  54. values["median"] = ps[0]
  55. values["75%"] = ps[1]
  56. values["95%"] = ps[2]
  57. values["99%"] = ps[3]
  58. values["99.9%"] = ps[4]
  59. values["1m.rate"] = t.Rate1()
  60. values["5m.rate"] = t.Rate5()
  61. values["15m.rate"] = t.Rate15()
  62. values["mean.rate"] = t.RateMean()
  63. }
  64. data[name] = values
  65. })
  66. return json.Marshal(data)
  67. }
  68. // WriteJSON writes metrics from the given registry periodically to the
  69. // specified io.Writer as JSON.
  70. func WriteJSON(r Registry, d time.Duration, w io.Writer) {
  71. for _ = range time.Tick(d) {
  72. WriteJSONOnce(r, w)
  73. }
  74. }
  75. // WriteJSONOnce writes metrics from the given registry to the specified
  76. // io.Writer as JSON.
  77. func WriteJSONOnce(r Registry, w io.Writer) {
  78. json.NewEncoder(w).Encode(r)
  79. }