Random Histogram Generator with Prometheus

  • Share this:

Code introduction


This function generates a random histogram using the Prometheus client library. It takes a collection of samples and a list of label values as input, then generates random samples for each label value and records them in the histogram.


Technology Stack : Prometheus client library

Code Type : Prometheus client code

Code Difficulty : Intermediate


                
                    
def random_histogram(collection, label_values):
    """
    This function generates a random histogram from a given collection and label values.
    """
    from prometheus_client import Histogram
    import random

    # Define the histogram
    histogram = Histogram('random_histogram', 'A random histogram', labelnames=['label'])

    # Record a random sample for each label value
    for label in label_values:
        count = random.randint(1, 100)
        histogram.observe(count, {'label': label})

    # Reset the histogram after recording
    histogram.reset()

    # Return the histogram data
    return histogram.get_samples()