github.com/wfusion/gofusion@v1.1.14/metrics/prometheus.go (about)

     1  package metrics
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/pkg/errors"
     9  
    10  	"github.com/wfusion/gofusion/common/infra/metrics/prometheus"
    11  
    12  	proDrv "github.com/prometheus/client_golang/prometheus"
    13  )
    14  
    15  var (
    16  	prometheusRWLocker  = new(sync.RWMutex)
    17  	prometheusRegisters = map[string]proDrv.Registerer{}
    18  )
    19  
    20  type _Prometheus struct {
    21  	*abstract
    22  }
    23  
    24  func newPrometheusPush(ctx context.Context, appName, name, job string, interval time.Duration, conf *cfg) Sink {
    25  	sink, err := prometheus.NewPrometheusPushSink(ctx, conf.c.Endpoint.Addresses[0], interval, job, conf.logger)
    26  	if err != nil {
    27  		panic(errors.Errorf("initialize metrics component push mode prometheus failed: %s", err))
    28  	}
    29  	return &_Prometheus{abstract: newMetrics(ctx, appName, name, job, sink, conf)}
    30  }
    31  
    32  func newPrometheusPull(ctx context.Context, appName, name, job string, conf *cfg) Sink {
    33  	prometheusRWLocker.Lock()
    34  	if _, ok := prometheusRegisters[appName]; !ok {
    35  		prometheusRegisters[appName] = proDrv.NewRegistry()
    36  	}
    37  	prometheusRWLocker.Unlock()
    38  
    39  	sink, err := prometheus.NewPrometheusSinkFrom(prometheus.PrometheusOpts{
    40  		Expiration:           prometheus.DefaultPrometheusOpts.Expiration,
    41  		Registerer:           prometheusRegisters[appName],
    42  		GaugeDefinitions:     nil,
    43  		SummaryDefinitions:   nil,
    44  		CounterDefinitions:   nil,
    45  		HistogramDefinitions: nil,
    46  		Name:                 job,
    47  	})
    48  	if err != nil {
    49  		panic(errors.Errorf("initialize metrics component pull mode prometheus failed: %s", err))
    50  	}
    51  
    52  	return &_Prometheus{abstract: newMetrics(ctx, appName, name, job, sink, conf)}
    53  }