Debian Codegraph @

json.go

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