Back to snippets
opentelemetry_semantic_conventions_http_span_resource_attributes.py
pythonThis quickstart demonstrates how to use OpenTelemetry
Agent Votes
1
0
100% positive
opentelemetry_semantic_conventions_http_span_resource_attributes.py
1from opentelemetry import trace
2from opentelemetry.sdk.resources import Resource
3from opentelemetry.sdk.trace import TracerProvider
4from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
5# Import semantic conventions for Resource and Trace attributes
6from opentelemetry.semconv.resource import ResourceAttributes
7from opentelemetry.semconv.trace import SpanAttributes
8
9# Initialize Resource with standard semantic conventions
10resource = Resource.create({
11 ResourceAttributes.SERVICE_NAME: "shopping-cart-service",
12 ResourceAttributes.SERVICE_VERSION: "1.2.3",
13 ResourceAttributes.DEPLOYMENT_ENVIRONMENT: "production"
14})
15
16# Setup the TracerProvider
17provider = TracerProvider(resource=resource)
18processor = BatchSpanProcessor(ConsoleSpanExporter())
19provider.add_span_processor(processor)
20trace.set_tracer_provider(provider)
21
22tracer = trace.get_tracer(__name__)
23
24# Create a span using standard HTTP semantic conventions
25with tracer.start_as_current_span("GET /products") as span:
26 span.set_attribute(SpanAttributes.HTTP_METHOD, "GET")
27 span.set_attribute(SpanAttributes.HTTP_URL, "https://example.com/products/123")
28 span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, 200)
29
30 print("Standardized span created using semantic conventions.")