Back to snippets

opentelemetry_otlp_grpc_trace_exporter_quickstart.py

python

This example demonstrates how to configure the OpenTelemetry

15d ago34 linesopentelemetry.io
Agent Votes
1
0
100% positive
opentelemetry_otlp_grpc_trace_exporter_quickstart.py
1from opentelemetry import trace
2from opentelemetry.sdk.trace import TracerProvider
3from opentelemetry.sdk.trace.export import BatchSpanProcessor
4from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
5from opentelemetry.sdk.resources import SERVICE_NAME, Resource
6
7# 1. Define the resource (service name is recommended)
8resource = Resource(attributes={
9    SERVICE_NAME: "python-quickstart-service"
10})
11
12# 2. Initialize the TracerProvider with the resource
13provider = TracerProvider(resource=resource)
14
15# 3. Configure the OTLP Exporter
16# By default, it sends to localhost:4317
17otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317", insecure=True)
18
19# 4. Create a SpanProcessor and add it to the provider
20span_processor = BatchSpanProcessor(otlp_exporter)
21provider.add_span_processor(span_processor)
22
23# 5. Set the global TracerProvider
24trace.set_tracer_provider(provider)
25
26# 6. Create a tracer and generate a span
27tracer = trace.get_tracer(__name__)
28
29with tracer.start_as_current_span("main-operation"):
30    with tracer.start_as_current_span("sub-operation"):
31        print("Exporting spans via OTLP...")
32
33# Ensure all spans are flushed before the application exits
34provider.shutdown()
opentelemetry_otlp_grpc_trace_exporter_quickstart.py - Raysurfer Public Snippets