Custom Prometheus Collector with Random Metrics

  • Share this:

Code introduction


This function defines a custom Prometheus collector using the Prometheus client library. It generates a random metric name and creates a Gauge type metric. The collector randomly chooses a value and a type each time it is called, and adds this value and type as metric data.


Technology Stack : prometheus_client

Code Type : Prometheus Collector

Code Difficulty : Intermediate


                
                    
import random
from prometheus_client import Collector, Gauge

# Function to generate a random metric name
def generate_metric_name():
    words = ["cpu", "memory", "disk", "http", "network", "process"]
    return f"{random.choice(words)}_usage"

# Custom Collector using Prometheus Client Library
def custom_prometheus_collector():
    # Create a Gauge object for the custom metric
    metric_name = generate_metric_name()
    gauge = Gauge(f"{metric_name}_gauge", "A gauge for the custom metric", ["type"])
    
    class CustomCollector(Collector):
        def collect(self):
            # Randomly choose a value for the gauge
            value = random.randint(0, 100)
            # Randomly choose a type for the metric
            metric_type = random.choice(["total", "available", "used"])
            # Add the gauge value to the registry
            gauge.set(value, metric_type)
    
    return CustomCollector()

# Example usage
collector = custom_prometheus_collector()
collector.collect()