Generating a Random Histogram Metric with Prometheus

  • Share this:

Code introduction


This function uses Prometheus' Histogram metric to record the distribution of a series of random floating-point numbers. It takes two arguments: the first one indicates the number of times to generate random numbers, and the second one indicates the range of random numbers. The Histogram class from Prometheus is used to create a metric, and random numbers are generated in a loop and recorded into the metric.


Technology Stack : Prometheus, Prometheus Client Library for Python

Code Type : Prometheus indicator

Code Difficulty : Intermediate


                
                    
def random_histogram_metric(arg1, arg2):
    from prometheus_client import Histogram
    import random
    import time

    # Create a histogram metric
    histogram = Histogram('random_histogram', 'A histogram of random values', labelnames=['label'])

    # Generate random values and record them in the histogram
    for i in range(arg1):
        value = random.uniform(0, arg2)
        histogram.observe(value, ['label'])

    # Sleep for a bit to allow the histogram to collect data
    time.sleep(1)

    return histogram