github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/cache/metrics/prometheus.go (about) 1 package metrics 2 3 import ( 4 "github.com/angenalZZZ/gofunc/data/cache/codec" 5 "github.com/prometheus/client_golang/prometheus" 6 "github.com/prometheus/client_golang/prometheus/promauto" 7 ) 8 9 const ( 10 namespaceCache = "cache" 11 ) 12 13 var ( 14 cacheCollector = initCacheCollector(namespaceCache) 15 ) 16 17 // Prometheus represents the prometheus struct for collecting metrics 18 type Prometheus struct { 19 service string 20 collector *prometheus.GaugeVec 21 codecChannel chan codec.CodecInterface 22 } 23 24 func initCacheCollector(namespace string) *prometheus.GaugeVec { 25 c := promauto.NewGaugeVec( 26 prometheus.GaugeOpts{ 27 Name: "collector", 28 Namespace: namespace, 29 Help: "This represent the number of items in cache", 30 }, 31 []string{"service", "store", "metric"}, 32 ) 33 return c 34 } 35 36 // NewPrometheus initializes a new prometheus metric instance 37 func NewPrometheus(service string) *Prometheus { 38 prometheus := &Prometheus{ 39 service: service, 40 collector: cacheCollector, 41 codecChannel: make(chan codec.CodecInterface, 10000), 42 } 43 44 go prometheus.recorder() 45 46 return prometheus 47 } 48 49 // Record records a metric in prometheus by specyfing the store name, metric name and value 50 func (m *Prometheus) record(store, metric string, value float64) { 51 m.collector.WithLabelValues(m.service, store, metric).Set(value) 52 } 53 54 // Recorder records metrics in prometheus by retrieving values from the codec channel 55 func (m *Prometheus) recorder() { 56 for codec := range m.codecChannel { 57 stats := codec.GetStats() 58 storeType := codec.GetStore().GetType() 59 60 m.record(storeType, "hit_count", float64(stats.Hits)) 61 m.record(storeType, "miss_count", float64(stats.Miss)) 62 63 m.record(storeType, "set_success", float64(stats.SetSuccess)) 64 m.record(storeType, "set_error", float64(stats.SetError)) 65 66 m.record(storeType, "delete_success", float64(stats.DeleteSuccess)) 67 m.record(storeType, "delete_error", float64(stats.DeleteError)) 68 69 m.record(storeType, "invalidate_success", float64(stats.InvalidateSuccess)) 70 m.record(storeType, "invalidate_error", float64(stats.InvalidateError)) 71 } 72 } 73 74 // RecordFromCodec sends the given codec into the codec channel to be read from recorder 75 func (m *Prometheus) RecordFromCodec(codec codec.CodecInterface) { 76 m.codecChannel <- codec 77 }