github.com/puellanivis/breton@v0.2.16/lib/metrics/metrics.go (about) 1 // Package metrics provides an abstracted metrics library compatible with prometheus client specifications. 2 // 3 // This package works very much like the standard flag library: 4 // 5 // var ( 6 // counter = metrics.Counter("counter_name", "usage information") 7 // gauge = metrics.Gauge("gauge_name", "usage information") 8 // histogram = metrics.Histogram("histogram_name", "usage informationn") // default buckets 9 // summary = metrics.Summary("summary_name", "usage information") // no objectives 10 // ) 11 // 12 // Setting up timing for a function is hopefuly straight-forward. 13 // 14 // func httpHandler(w http.ResponseWriter, r *http.Request) { 15 // done := summary.Timer() 16 // defer done() 17 // 18 // // do work here. 19 // } 20 // 21 // A set of common 50-90-95 Summary objectives is available: 22 // 23 // var summary = metrics.Summary("summary", "usage", metrics.CommonObjectives()) 24 // 25 // Defining labels for a metric is hopefully also straight-forward: 26 // 27 // const ( 28 // labelCode = metrics.Label("code") 29 // ) 30 // 31 // var counter = metrics.Counter("http_status", "usage", metrics.WithLabels(labelCode)) 32 // 33 // func httpError(w http.ResponseWriter, error string, code int) { 34 // label := labelCode.WithValue(strconv.Itoa(code)) 35 // counter.WithLabels(label).Inc() 36 // 37 // http.Error(w, error, code) 38 // } 39 package metrics 40 41 import ( 42 "fmt" 43 "regexp" 44 "time" 45 46 "github.com/prometheus/client_golang/prometheus" 47 //pb "github.com/prometheus/client_model/go" 48 ) 49 50 // Observer is implemented by any value that has an Observe(float64) format. 51 // The primary metric types implementing this are Summary and Histogram. 52 type Observer interface { 53 Observe(float64) 54 } 55 56 // Timer is implemented by any value that permits timing a piece of code. 57 type Timer interface { 58 Timer() (done func()) 59 } 60 61 type metric struct { 62 registry *prometheus.Registry 63 64 name, help string 65 66 labels *labelScope 67 68 *summarySettings 69 *histogramSettings 70 } 71 72 type summarySettings struct { 73 objectives map[float64]float64 74 maxAge time.Duration 75 ageBuckets uint32 76 bufCap uint32 77 } 78 79 type histogramSettings struct { 80 buckets []float64 81 } 82 83 var validName = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`) 84 85 func newMetric(name, help string) *metric { 86 if !validName.MatchString(name) { 87 panic("invalid metric name") 88 } 89 90 return &metric{ 91 registry: prometheus.DefaultRegisterer.(*prometheus.Registry), 92 name: name, 93 help: help, 94 } 95 } 96 97 func (m metric) helpString() string { 98 if m.help == "" { 99 return "" 100 } 101 102 return fmt.Sprintf("# HELP %s %s\n", m.name, m.help) 103 }