Golang MustRegister示例

说明

golang mustregister示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: github.com/prometheus/client_golang/prometheus

示例#1
文件: metrics.go 项目: 40a/bootkube

// Metrics registers the DNS metrics to Prometheus, and starts the internal metrics
// server if the environment variable PROMETHEUS_PORT is set.
func Metrics() error {
	// We do this in a function instead of using var + init(), because we want to
	// able to set Namespace and/or Subsystem.
	if Port == "" {
		return nil
	}

	_, err := strconv.Atoi(Port)
	if err != nil {
		fmt.Errorf("bad port for prometheus: %s", Port)
	}

	defineMetrics()

	prometheus.MustRegister(requestCount)
	prometheus.MustRegister(requestDuration)
	prometheus.MustRegister(responseSize)
	prometheus.MustRegister(errorCount)
	prometheus.MustRegister(cacheMiss)

	http.Handle(Path, prometheus.Handler())
	go func() {
		fmt.Errorf("%s", http.ListenAndServe(":"+Port, nil))
	}()
	return nil
}

示例#2
文件: prometheus.go 项目: carriercomm/pritunl-monitor

func init() {
	prometheus.MustRegister(cpuUsage)
	prometheus.MustRegister(memUsage)
	prometheus.MustRegister(deviceCount)
	prometheus.MustRegister(serverCount)
	prometheus.MustRegister(threadCount)
}

示例#3
文件: exporter.go 项目: prometheus-junkyard/gmond_exporter

func New(configFile string) (e exporter, err error) {

	e = exporter{
		configFile: configFile,
		Metrics:    map[string]*prometheus.GaugeVec{},
		scrapeDuration: prometheus.NewSummaryVec(
			prometheus.SummaryOpts{
				Namespace: namespace,
				Name:      "scrape_duration_seconds",
				Help:      "gmond_exporter: Duration of a scrape job.",
			},
			[]string{"endpoint", "result"},
		),
		metricsUpdated: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: namespace,
				Name:      "metrics_updated_count",
				Help:      "gmond_exporter: Number of metrics updated.",
			},
			[]string{"endpoint"},
		),
		metricsExported: prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: namespace,
			Name:      "metrics_exported_count",
			Help:      "gmond_exporter: Number of metrics exported.",
		}),
		configChan:            make(chan config),
		listeningAddress:      ":8080",
		gangliaScrapeInterval: 60 * time.Second,
	}

	conf, err := e.readConfig()
	if err != nil {
		return e, fmt.Errorf("Couldn't read config: %s", err)
	}
	e.conf = conf

	if conf.ListeningAddress != "" {
		e.listeningAddress = conf.ListeningAddress
	}
	if conf.GangliaScrapeInterval != 0 {
		e.gangliaScrapeInterval = time.Duration(conf.GangliaScrapeInterval) * time.Second
	}

	prometheus.MustRegister(e.scrapeDuration)
	prometheus.MustRegister(e.metricsUpdated)
	prometheus.MustRegister(e.metricsExported)
	debug("Registered internal metrics")

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGHUP)
	go func() {
		for _ = range sig {
			e.reloadConfig() // sends a new config to configChan
		}
	}()

	go e.serveStatus()
	return e, nil
}

示例#4
文件: metrics.go 项目: 40a/bootkube

// Register registers all metrics to Prometheus with
// respect to the RequestLatency.
func Register() {
	// Register the metrics.
	registerMetrics.Do(func() {
		prometheus.MustRegister(RequestLatency)
		prometheus.MustRegister(RequestResult)
	})
}

示例#5
文件: metrics.go 项目: jonboulle/fleet

func init() {
	prometheus.MustRegister(leaderGauge)
	prometheus.MustRegister(engineTaskCount)
	prometheus.MustRegister(engineTaskFailureCount)
	prometheus.MustRegister(engineReconcileCount)
	prometheus.MustRegister(engineReconcileFailureCount)
}

示例#6
文件: metrics.go 项目: nhr/origin

func init() {
	prometheus.MustRegister(sentBytes)
	prometheus.MustRegister(receivedBytes)
	prometheus.MustRegister(sentFailures)
	prometheus.MustRegister(recvFailures)
	prometheus.MustRegister(rtts)
}

示例#7
文件: pgsql.go 项目: robinjha/clair

func init() {
	prometheus.MustRegister(promErrorsTotal)
	prometheus.MustRegister(promCacheHitsTotal)
	prometheus.MustRegister(promCacheQueriesTotal)
	prometheus.MustRegister(promQueryDurationMilliseconds)
	prometheus.MustRegister(promConcurrentLockVAFV)
}

示例#8
文件: metrics.go 项目: CliffYuan/etcd

func init() {
	prometheus.MustRegister(readCounter)
	prometheus.MustRegister(writeCounter)
	prometheus.MustRegister(expireCounter)
	prometheus.MustRegister(watchRequests)
	prometheus.MustRegister(watcherCount)
}

示例#9
文件: main.go 项目: SLASH2NL/nats-prometheus

func main() {
	flag.Parse()
	if *consumeTime < 1 {
		log.Fatal("consume time should be >0")
	}

	resp, err := http.Get(fmt.Sprintf("http://%s/varz", *natsaddr))
	if err != nil {
		log.Fatal(err)
	}

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("expected statuscode 200 got %v", resp.StatusCode)
	}

	resp.Body.Close()

	prometheus.MustRegister(bytesCounter)
	prometheus.MustRegister(messageCounter)
	prometheus.MustRegister(connections)
	prometheus.MustRegister(slowConsumers)

	go consume()

	http.Handle("/metrics", prometheus.Handler())
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal(err)
	}
}

示例#10
文件: scrape.go 项目: yershalom/prometheus

func init() {
	prometheus.MustRegister(targetIntervalLength)
	prometheus.MustRegister(targetSkippedScrapes)
	prometheus.MustRegister(targetReloadIntervalLength)
	prometheus.MustRegister(targetSyncIntervalLength)
	prometheus.MustRegister(targetScrapePoolSyncsCounter)
}

示例#11
文件: metrics.go 项目: jmptrader/tidb

func init() {
	prometheus.MustRegister(cmdCounter)
	prometheus.MustRegister(cmdFailedCounter)
	prometheus.MustRegister(cmdDuration)
	prometheus.MustRegister(cmdFailedDuration)
	prometheus.MustRegister(requestDuration)
}

示例#12
文件: feeder.go 项目: jamessan/dcs

func init() {
	prometheus.MustRegister(failedLookfor)
	prometheus.MustRegister(successfulLookfor)
	prometheus.MustRegister(successfulGarbageCollect)
	prometheus.MustRegister(successfulSanityFeed)
	prometheus.MustRegister(lastSanityCheckStarted)
}

示例#13
文件: ted_exporter.go 项目: wrong-kendall/ted_exporter

func main() {
	flag.Parse()

	handler := prometheus.Handler()
	prometheus.MustRegister(watts)
	prometheus.MustRegister(updatesPerPost)
	prometheus.MustRegister(voltage)

	http.Handle(*metricsPath, handler)
	http.HandleFunc("/activate", activateHandler)
	http.HandleFunc("/post", postHandler)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
			<head><title>TED Exporter</title></head>
			<body>
			<h1>TED Exporter</h1>
			<p><a href="` + *metricsPath + `">Metrics</a></p>
			</body>
			</html>`))
	})

	log.Infof("Starting ted_exporter v%s at %s", Version, *listenAddress)
	err := http.ListenAndServe(*listenAddress, nil)
	if err != nil {
		log.Fatal(err)
	}
}

示例#14
文件: main.go 项目: Luzifer/promcertcheck

func registerProbes() {
	for _, probe := range config.Probes {
		probeURL, _ := url.Parse(probe)

		monitors := &probeMonitor{}
		monitors.Expires = prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "certcheck_expires",
			Help: "Expiration date in unix timestamp (UTC)",
			ConstLabels: prometheus.Labels{
				"host": probeURL.Host,
			},
		})
		monitors.IsValid = prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "certcheck_valid",
			Help: "Validity of the certificate (0/1)",
			ConstLabels: prometheus.Labels{
				"host": probeURL.Host,
			},
		})

		prometheus.MustRegister(monitors.Expires)
		prometheus.MustRegister(monitors.IsValid)

		probeMonitors[probeURL.Host] = monitors
	}
}

示例#15
文件: main.go 项目: tomstaijen/rabbitmq_exporter

// Register metrics to Prometheus
func init() {
	prometheus.MustRegister(channelsTotal)
	prometheus.MustRegister(connectionsTotal)
	prometheus.MustRegister(queuesTotal)
	prometheus.MustRegister(exchangesTotal)
	prometheus.MustRegister(consumersTotal)
}

示例#16
文件: metrics.go 项目: lhchavez/quark

func setupMetrics(ctx *grader.Context) {
	for _, gauge := range gauges {
		prometheus.MustRegister(gauge)
	}
	for _, counter := range counters {
		prometheus.MustRegister(counter)
	}
	for _, summary := range summaries {
		prometheus.MustRegister(summary)
	}

	metricsMux := http.NewServeMux()
	metricsMux.Handle("/metrics", prometheus.Handler())
	go func() {
		addr := fmt.Sprintf(":%d", ctx.Config.Metrics.Port)
		ctx.Log.Error(
			"http listen and serve",
			"err", http.ListenAndServe(addr, metricsMux),
		)
	}()
	go func() {
		gaugesUpdate()
		time.Sleep(time.Duration(1) * time.Minute)
	}()
}

示例#17
文件: monitor.go 项目: desmondmcnamee/populr_go_api

func initMonitoring() {
	prometheus.MustRegister(UserCount)
	prometheus.MustRegister(MessageSentCount)
	prometheus.MustRegister(MessageReadCount)
	prometheus.MustRegister(PublicMessageCount)
	prometheus.MustRegister(DirectMessageCount)
}

示例#18
文件: middleware.go 项目: zbindenren/negroni-prometheus

// NewMiddleware returns a new prometheus Middleware handler.
func NewMiddleware(name string, buckets ...float64) *Middleware {
	var m Middleware
	m.reqs = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name:        reqsName,
			Help:        "How many HTTP requests processed, partitioned by status code, method and HTTP path.",
			ConstLabels: prometheus.Labels{"service": name},
		},
		[]string{"code", "method", "path"},
	)
	prometheus.MustRegister(m.reqs)

	if len(buckets) == 0 {
		buckets = dflBuckets
	}
	m.latency = prometheus.NewHistogramVec(prometheus.HistogramOpts{
		Name:        latencyName,
		Help:        "How long it took to process the request, partitioned by status code, method and HTTP path.",
		ConstLabels: prometheus.Labels{"service": name},
		Buckets:     buckets,
	},
		[]string{"code", "method", "path"},
	)
	prometheus.MustRegister(m.latency)
	return &m
}

示例#19
文件: metrics.go 项目: hongchaodeng/etcd

func init() {
	prometheus.MustRegister(watchersCoalescing)
	prometheus.MustRegister(eventsCoalescing)
	prometheus.MustRegister(cacheKeys)
	prometheus.MustRegister(cacheHits)
	prometheus.MustRegister(cachedMisses)
}

示例#20
文件: main.go 项目: discordianfish/byte-piper

func init() {
	prometheus.MustRegister(backupDuration)
	prometheus.MustRegister(backupSeen)
	prometheus.MustRegister(backupSize)
	prometheus.MustRegister(backupsTotal)
	prometheus.MustRegister(backupsFailed)
}

示例#21
文件: central.go 项目: thomasf/alkasir

func startMonitoring(addr string) {

	var redisActiveConn = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "redis_active_conn",
		Help: "Number of active redis connections.",
	})
	prometheus.MustRegister(redisActiveConn)

	var redisMaxConn = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "redis_max_conn",
		Help: "Maximum number of redis connections.",
	})
	prometheus.MustRegister(redisMaxConn)

	http.Handle("/metrics", prometheus.Handler())
	redisMaxConn.Set(float64(redisPool.MaxActive))
	go func() {
		tick := time.NewTicker(1 * time.Second)
		for range tick.C {
			if redisPool == nil {
				redisActiveConn.Set(0)
			} else {
				redisActiveConn.Set(float64(redisPool.ActiveCount()))
			}
		}
	}()
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		lg.Fatal(err)
	}
}

示例#22
文件: metrics.go 项目: qingyuancloud/qingyuan

// Register all metrics.
func Register() {
	// Register the metrics.
	registerMetrics.Do(func() {
		prometheus.MustRegister(E2eSchedulingLatency)
		prometheus.MustRegister(SchedulingAlgorithmLatency)
		prometheus.MustRegister(BindingLatency)
	})
}

示例#23
文件: metrics.go 项目: CliffYuan/etcd

func init() {
	prometheus.MustRegister(receivedCounter)
	prometheus.MustRegister(failedCounter)
	prometheus.MustRegister(handlingDuration)

	prometheus.MustRegister(sentBytes)
	prometheus.MustRegister(receivedBytes)
}

示例#24
文件: metrics.go 项目: humblec/kubernetes

func Register() {
	registerMetrics.Do(func() {
		prometheus.MustRegister(ZoneHealth)
		prometheus.MustRegister(ZoneSize)
		prometheus.MustRegister(UnhealthyNodes)
		prometheus.MustRegister(EvictionsNumber)
	})
}

示例#25
文件: consul.go 项目: prometheus/prometheus

func init() {
	prometheus.MustRegister(rpcFailuresCount)
	prometheus.MustRegister(rpcDuration)

	// Initialize metric vectors.
	rpcDuration.WithLabelValues("catalog", "service")
	rpcDuration.WithLabelValues("catalog", "services")
}

示例#26
文件: metrics.go 项目: 40a/bootkube

func Register() {
	registerMetrics.Do(func() {
		prometheus.MustRegister(OffersReceived)
		prometheus.MustRegister(OffersDeclined)
		prometheus.MustRegister(OffersAcquired)
		prometheus.MustRegister(OffersReleased)
	})
}

示例#27
文件: metrics.go 项目: humblec/kubernetes

// Register all metrics.
func Register() {
	// Register the metrics.
	registerMetrics.Do(func() {
		prometheus.MustRegister(EventProcessingLatency)
		prometheus.MustRegister(DirtyProcessingLatency)
		prometheus.MustRegister(OrphanProcessingLatency)
	})
}

示例#28
文件: instrumentation.go 项目: rugby110/glimpse

func init() {
	prometheus.MustRegister(dnsDurations)
	prometheus.MustRegister(storeCounts)
	prometheus.MustRegister(storeDurations)
	prometheus.MustRegister(storeErrors)
	prometheus.MustRegister(
		prometheus.NewProcessCollectorPIDFn(consulAgentPid, "consul"),
	)
}

示例#29
文件: etcd.go 项目: ConfusedReality/server_distributed-storage_torus

func init() {
	torus.RegisterMetadataService("etcd", newEtcdMetadata)
	torus.RegisterMetadataInit("etcd", initEtcdMetadata)
	torus.RegisterMetadataWipe("etcd", wipeEtcdMetadata)
	torus.RegisterSetRing("etcd", setRing)

	prometheus.MustRegister(promAtomicRetries)
	prometheus.MustRegister(promOps)
}

示例#30
文件: metrics.go 项目: Xmagicer/origin

// RegisterPrometheusMetrics defines and registers the appropriate metrics
// with prometheus.
func RegisterPrometheusMetrics(namespace, subsystem string) {
	defineMetrics(namespace, subsystem)

	prometheus.MustRegister(requestCount)
	prometheus.MustRegister(requestDuration)
	prometheus.MustRegister(responseSize)
	prometheus.MustRegister(errorCount)
	prometheus.MustRegister(cacheMiss)
}

展开阅读全文