...

Source file src/github.com/prometheus/client_golang/examples/exemplars/main.go

Documentation: github.com/prometheus/client_golang/examples/exemplars

     1  // Copyright 2022 The Prometheus Authors
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // A simple example of how to record a latency metric with exemplars, using a fictional id
    15  // as a prometheus label.
    16  
    17  package main
    18  
    19  import (
    20  	"fmt"
    21  	"log"
    22  	"math/rand"
    23  	"net/http"
    24  	"time"
    25  
    26  	"github.com/prometheus/client_golang/prometheus"
    27  	"github.com/prometheus/client_golang/prometheus/collectors"
    28  	"github.com/prometheus/client_golang/prometheus/promhttp"
    29  )
    30  
    31  func main() {
    32  	requestDurations := prometheus.NewHistogram(prometheus.HistogramOpts{
    33  		Name:    "http_request_duration_seconds",
    34  		Help:    "A histogram of the HTTP request durations in seconds.",
    35  		Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5),
    36  	})
    37  
    38  	// Create non-global registry.
    39  	registry := prometheus.NewRegistry()
    40  
    41  	// Add go runtime metrics and process collectors.
    42  	registry.MustRegister(
    43  		collectors.NewGoCollector(),
    44  		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
    45  		requestDurations,
    46  	)
    47  
    48  	go func() {
    49  		for {
    50  			// Record fictional latency.
    51  			now := time.Now()
    52  			requestDurations.(prometheus.ExemplarObserver).ObserveWithExemplar(
    53  				time.Since(now).Seconds(), prometheus.Labels{"dummyID": fmt.Sprint(rand.Intn(100000))},
    54  			)
    55  			time.Sleep(600 * time.Millisecond)
    56  		}
    57  	}()
    58  
    59  	// Expose /metrics HTTP endpoint using the created custom registry.
    60  	http.Handle(
    61  		"/metrics", promhttp.HandlerFor(
    62  			registry,
    63  			promhttp.HandlerOpts{
    64  				EnableOpenMetrics: true,
    65  			}),
    66  	)
    67  	// To test: curl -H 'Accept: application/openmetrics-text' localhost:8080/metrics
    68  	log.Fatalln(http.ListenAndServe(":8080", nil))
    69  }
    70  

View as plain text