Starting Prometheus Metrics Server with Custom Collector

  • Share this:

Code introduction


This function starts a Prometheus HTTP metrics server and registers a custom collector that exposes a gauge metric named 'custom_metric', based on two random values.


Technology Stack : Prometheus, Prometheus Client Library for Python

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
from prometheus_client import Collector, Gauge

# Custom Collector to expose custom metrics
class CustomCollector(Collector):
    def __init__(self):
        super(CustomCollector, self).__init__('custom_collector')
        self.custom_gauge = Gauge('custom_metric', 'A custom gauge metric', labelnames=['label1', 'label2'])

    def collect(self):
        # Simulate some logic to update the gauge
        value1 = random.randint(1, 100)
        value2 = random.randint(1, 100)
        self.custom_gauge.set(value1, label1='value1', label2='value2')

# Function to start the metrics server and register the custom collector
def start_metrics_server():
    from prometheus_client import start_http_server
    start_http_server(8000)
    custom_collector = CustomCollector()
    custom_collector.register()

# JSON representation of the code