Skip to content

Instantly share code, notes, and snippets.

@hugotkk
Created April 25, 2023 22:40
Show Gist options
  • Save hugotkk/85c8b71bd25b01ca44c6de97d4b293cf to your computer and use it in GitHub Desktop.
Save hugotkk/85c8b71bd25b01ca44c6de97d4b293cf to your computer and use it in GitHub Desktop.
Expose metrics with prometheus client library
from prometheus_client import start_http_server, Counter, Gauge, Histogram, Summary, Info
import random
import time
import threading
# Define a counter metric
REQUESTS = Counter('http_requests_total', 'The total number of HTTP requests')
# Define a gauge metric
USERS = Gauge('active_users', 'The number of active users')
# Define a histogram metric
REQUEST_LATENCY = Histogram('request_latency_seconds', 'The latency of HTTP requests', buckets=[0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4, 12.8, 25.6, 51.2, float("inf")], labelnames=['method', 'endpoint'])
# Define a summary metric
REQUEST_TIME = Summary('request_processing_seconds', 'The processing time of HTTP requests')
i = Info('my_build_version', 'Description of info')
i.info({'version': '1.2.3', 'buildhost': 'foo@bar'})
def start_metrics_server():
start_http_server(8000)
t = threading.Thread(target=start_metrics_server)
t.daemon = True
t.start()
# Simulate some requests
while True:
REQUESTS.inc()
USERS.set(random.randint(0, 10))
latency = random.uniform(0.1, 5.0)
REQUEST_LATENCY.labels(method="GET", endpoint="/contact-us").observe(latency)
with REQUEST_TIME.time():
time.sleep(random.uniform(0.1, 0.5))
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment