You can download this code by clicking the button below.
This code is now available for download.
This function generates a specified number of random labels, each composed of a prefix and a random number. The value of the label is randomly chosen. These labels are used for Prometheus Gauge type metrics.
Technology Stack : Prometheus, CollectorRegistry, Gauge, random.randint, random.choice
Code Type : Prometheus custom function
Code Difficulty : Intermediate
def random_label_generator(label_prefix, num_labels):
import random
from prometheus_client import CollectorRegistry, Gauge
# 创建一个注册表
registry = CollectorRegistry()
# 创建一个Gauge对象,用于生成随机标签
gauge = Gauge('random_labels', 'Random labels for demonstration', registry=registry)
def generate_labels():
labels = {}
for i in range(num_labels):
label_name = f"{label_prefix}_{random.randint(0, 1000)}"
labels[label_name] = random.choice(['A', 'B', 'C'])
return labels
# 生成随机标签并更新到Gauge中
gauge.labels(**generate_labels()).set()
# 返回生成的标签
return generate_labels()