github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/metrics/prometheus/prometheus.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 // Package prometheus exposes go-metrics into a Prometheus format. 19 package prometheus 20 21 import ( 22 "fmt" 23 "net/http" 24 "sort" 25 26 "github.com/AigarNetwork/aigar/log" 27 "github.com/AigarNetwork/aigar/metrics" 28 ) 29 30 // Handler returns an HTTP handler which dump metrics in Prometheus format. 31 func Handler(reg metrics.Registry) http.Handler { 32 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 33 // Gather and pre-sort the metrics to avoid random listings 34 var names []string 35 reg.Each(func(name string, i interface{}) { 36 names = append(names, name) 37 }) 38 sort.Strings(names) 39 40 // Aggregate all the metris into a Prometheus collector 41 c := newCollector() 42 43 for _, name := range names { 44 i := reg.Get(name) 45 46 switch m := i.(type) { 47 case metrics.Counter: 48 c.addCounter(name, m.Snapshot()) 49 case metrics.Gauge: 50 c.addGauge(name, m.Snapshot()) 51 case metrics.GaugeFloat64: 52 c.addGaugeFloat64(name, m.Snapshot()) 53 case metrics.Histogram: 54 c.addHistogram(name, m.Snapshot()) 55 case metrics.Meter: 56 c.addMeter(name, m.Snapshot()) 57 case metrics.Timer: 58 c.addTimer(name, m.Snapshot()) 59 case metrics.ResettingTimer: 60 c.addResettingTimer(name, m.Snapshot()) 61 default: 62 log.Warn("Unknown Prometheus metric type", "type", fmt.Sprintf("%T", i)) 63 } 64 } 65 w.Header().Add("Content-Type", "text/plain") 66 w.Header().Add("Content-Length", fmt.Sprint(c.buff.Len())) 67 w.Write(c.buff.Bytes()) 68 }) 69 }