Random Prometheus Gauge Metric Generator

  • Share this:

Code introduction


This code defines a Prometheus Collector that generates a random gauge metric named `random_metric` with two labels `label1` and `label2`. Each collection period, it randomly sets the values for these two labels.


Technology Stack : prometheus_client

Code Type : Prometheus Collector

Code Difficulty : Intermediate


                
                    
def random_metric_name():
    import random
    import string
    return ''.join(random.choices(string.ascii_letters + string.digits, k=10))

def create_random_label_values(labels):
    return {label: random.choice(string.ascii_letters + string.digits) for label in labels}

def generate_random_metric():
    from prometheus_client import Collector, Gauge

    class RandomMetricCollector(Collector):
        def __init__(self):
            super().__init__('random_metric_family')
            self.metric = Gauge('random_metric', 'A random gauge metric', labelnames=['label1', 'label2'])

        def collect(self):
            label_values = create_random_label_values(['label1', 'label2'])
            self.metric.set(label_values['label1'], label_values['label2'])

    return RandomMetricCollector()