-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-telemetry.py
More file actions
57 lines (48 loc) · 2.14 KB
/
Copy pathtest-telemetry.py
File metadata and controls
57 lines (48 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.semconv.resource import ResourceAttributes
import time
import random
# Configuration
COLLECTOR_ENDPOINT = "localhost:4317" # OTLP gRPC endpoint
SOURCES = ["src1", "src2", "src3", "src4"] # 4 sources
EXPORT_INTERVAL_SECONDS = 0.5 # How often to export metrics
GENERATION_INTERVAL_SECONDS = 0.1 # How often to generate new data
# Create a separate resource and meter provider per source
resources = {}
meter_providers = {}
counters = {}
for source in SOURCES:
# Resource with source.id
res = Resource(attributes={
ResourceAttributes.SERVICE_NAME: "telemetry-generator",
"source.id": source, # Key fix: resource attribute
})
resources[source] = res
# Exporter (shared, but per-resource meter provider)
exporter = OTLPMetricExporter(endpoint=COLLECTOR_ENDPOINT, insecure=True)
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=EXPORT_INTERVAL_SECONDS * 1000)
# Per-source meter provider
provider = MeterProvider(resource=res, metric_readers=[reader])
meter_providers[source] = provider
meter = provider.get_meter(f"telemetry-generator-{source}")
counter = meter.create_counter(
name="custom.request.count",
description="Number of requests per source"
)
counters[source] = counter
print("Generating metrics... Press Ctrl+C to stop")
try:
while True:
for source, counter in counters.items():
value = random.randint(1, 50)
timestamp_ns = int(time.time() * 1e9)
counter.add(value, attributes={"initial_timestamp": timestamp_ns}) # No extra attributes needed (source.id is on resource)
print(f"Sent {value} requests for {source} at {timestamp_ns}")
time.sleep(GENERATION_INTERVAL_SECONDS)
except KeyboardInterrupt:
print("\nShutting down...")
for provider in meter_providers.values():
provider.shutdown()