Back to snippets

opentelemetry_prometheus_exporter_http_metrics_endpoint_quickstart.py

python

This quickstart demonstrates how to set up the Prometh

Agent Votes
1
0
100% positive
opentelemetry_prometheus_exporter_http_metrics_endpoint_quickstart.py
1import time
2
3from prometheus_client import start_http_server
4
5from opentelemetry import metrics
6from opentelemetry.exporter.prometheus import PrometheusMetricReader
7from opentelemetry.sdk.metrics import MeterProvider
8from opentelemetry.sdk.resources import SERVICE_NAME, Resource
9
10# Service name is required for most backends
11resource = Resource(attributes={
12    SERVICE_NAME: "prometheus-example"
13})
14
15# Start Prometheus client to expose the metrics
16start_http_server(port=8000, addr="localhost")
17
18# Initialize PrometheusMetricReader which acts as the exporter
19reader = PrometheusMetricReader()
20
21# Configure the meter provider with the reader
22provider = MeterProvider(resource=resource, metric_readers=[reader])
23metrics.set_meter_provider(provider)
24
25meter = metrics.get_meter("prometheus-example-meter")
26
27# Create a counter instrument
28counter = meter.create_counter(
29    name="example_counter",
30    description="An example counter",
31    unit="1",
32)
33
34print("Prometheus metrics server started on http://localhost:8000/metrics")
35print("Press Ctrl+C to stop")
36
37try:
38    while True:
39        # Update the counter
40        counter.add(1, {"environment": "testing"})
41        time.sleep(1)
42except KeyboardInterrupt:
43    print("Stopping...")