fromopentelemetryimporttracefromopentelemetry.traceimportStatusCodefromopentelemetry.sdk.traceimportTracerProviderfromopentelemetry.sdk.resourcesimportResourcefromopentelemetry.sdk.trace.exportimportBatchSpanProcessorfromopentelemetry.exporter.otlp.proto.grpc.trace_exporterimport(OTLPSpanExporter,)# Creates a resource and adds it to the tracer providerresource=Resource.create({"service.name":"recording-exceptions-manual"})provider=TracerProvider(resource=resource)trace.set_tracer_provider(provider)# Adds span processor with the OTLP exporter to the tracer providerprovider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4317",insecure=True)))tracer=trace.get_tracer(__name__)defprocess_order(order_id:str,amount:float,will_fail:bool=False,)->str:""" Processes an order. If will_fail=True, simulates a downstream exception. Returns "OK" on success; on failure, it raises the exception. """withtracer.start_as_current_span("process_order")asspan:span.set_attribute("order.id",order_id)span.set_attribute("order.amount",amount)span.add_event("Begin processing order")try:# deterministic “failure”ifwill_fail:raiseConnectionError("Simulated payment failure")# success pathspan.add_event("Payment succeeded")return"OK"exceptExceptionasexc:# record and mark errorspan.record_exception(exc,{"error.type":type(exc).__name__,"error.stage":"payment processing",},)span.set_status(StatusCode.ERROR,f"Payment error: {exc}")returnf"Failed to process order {order_id}: {exc}"# deterministic runs:process_order("ORD-1001",120.0,will_fail=False)process_order("ORD-1002",55.5,will_fail=True)
Run this Python snippet
uv run https://emdneto.github.io/opentelemetry-by-example/python/exceptions/snippet_manual.py
fromopentelemetryimporttracefromopentelemetry.sdk.traceimportTracerProviderfromopentelemetry.sdk.resourcesimportResourcefromopentelemetry.sdk.trace.exportimportBatchSpanProcessorfromopentelemetry.exporter.otlp.proto.grpc.trace_exporterimport(OTLPSpanExporter,)# Creates a resource and adds it to the tracer providerresource=Resource.create({"service.name":"recording-exceptions-contextmanager"})provider=TracerProvider(resource=resource)trace.set_tracer_provider(provider)# Adds span processor with the OTLP exporter to the tracer providerprovider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4317",insecure=True)))tracer=trace.get_tracer(__name__)# Simulates an operation that fail to demonstrate how to record exceptionswithtracer.start_as_current_span("risky_operation_grpc")asspan:try:raiseValueError("Something went wrong in gRPC operation!")exceptExceptionase:pass
Run this Python snippet
uv run https://emdneto.github.io/opentelemetry-by-example/python/exceptions/snippet_contextmanager.py