You can download this code by clicking the button below.
This code is now available for download.
This function uses the Prometheus third-party library to generate a random Prometheus metric series. It randomly selects a label pair from the provided list of label pairs, and uses this label pair and the specified value to create a full metric name. Then, it creates a counter metric and increments it by the specified value. Finally, it generates the metric in Prometheus text format.
Technology Stack : prometheus_client, random
Code Type : Prometheus indicator generating function
Code Difficulty : Intermediate
def generate_random_series(label_pairs, metric_name, value):
from prometheus_client import CollectorRegistry, generate_latest
from random import choice
# Randomly choose a label pair from the provided list
selected_label_pair = choice(label_pairs)
# Construct the full metric name with the selected label pair and value
full_metric_name = f"{metric_name}_{selected_label_pair[0]}={selected_label_pair[1]}"
# Create a registry and add a simple counter metric
registry = CollectorRegistry()
from prometheus_client.metrics import Counter
counter = Counter(full_metric_name, 'help', 'description')
counter.inc(value=value)
# Generate the Prometheus text format output
return generate_latest(registry)