git.zd.zone/hrpc/hrpc@v0.0.12/metrics/metrics.go (about)

     1  package metrics
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"sync"
     7  
     8  	"github.com/prometheus/client_golang/prometheus"
     9  	"github.com/prometheus/client_golang/prometheus/promauto"
    10  	"github.com/prometheus/client_golang/prometheus/promhttp"
    11  )
    12  
    13  func Run(prefix string) {
    14  	namePrefix = prefix
    15  	go func() {
    16  		defer func() {
    17  			if err := recover(); err != nil {
    18  				fmt.Println(err)
    19  			}
    20  		}()
    21  		http.Handle("/metrics", promhttp.Handler())
    22  		http.ListenAndServe(":2112", nil)
    23  	}()
    24  }
    25  
    26  type counterCollection struct {
    27  	counters map[string]prometheus.Counter
    28  	mu       sync.RWMutex
    29  }
    30  
    31  var (
    32  	cCollection = counterCollection{
    33  		counters: make(map[string]prometheus.Counter),
    34  	}
    35  	namePrefix = ""
    36  )
    37  
    38  // RegisterCounter will store a prometheus counter to be used later.
    39  // the parameters of name means the counter's name.
    40  // the parameters of help means the tips for the counter so that it can improve the readibility.
    41  func RegisterCounter(name, help string) {
    42  	cCollection.mu.Lock()
    43  	defer cCollection.mu.Unlock()
    44  	cCollection.counters[name] = promauto.NewCounter(prometheus.CounterOpts{
    45  		Name: namePrefix + "_" + name,
    46  		Help: help,
    47  	})
    48  }
    49  
    50  // Incr will increase a feature report to the prometheus
    51  func Incr(name string) {
    52  	cCollection.mu.RLock()
    53  	if v, ok := cCollection.counters[name]; ok {
    54  		v.Inc()
    55  		cCollection.mu.RUnlock()
    56  		return
    57  	}
    58  	cCollection.mu.RUnlock()
    59  
    60  	// add the new counter to the collection and increase
    61  	c := promauto.NewCounter(prometheus.CounterOpts{
    62  		Name: namePrefix + "_" + name,
    63  	})
    64  	cCollection.mu.Lock()
    65  	defer cCollection.mu.Unlock()
    66  	cCollection.counters[name] = c
    67  	c.Inc()
    68  }