OpenTelemetry (OTEL) provides support for adding Events, Exceptions, and Status into spans.

Overview

  • Basic Event Logging in OpenTelemetry: Captures significant events during a code path’s execution within a trace span, offering insights into specific actions in your application’s workflow.

  • Handling Errors with Span Status in OpenTelemetry: Assigns an error status to a trace span when an exception arises, helpful in the identify and troubleshoot issues in distributed systems.

  • Recording Errors and Exceptions in OpenTelemetry: Updates a span’s status to reflect errors and logs detailed exception information, providing a comprehensive view of failures for enhanced debugging.

Adding Events

Events are readable messages that signify “something happening” at a specific moment during a span’s lifecycle. They can be considered as basic logs.

from opentelemetry import trace

current_span = trace.get_current_span()

current_span.add_event("Attempting the operation!")

# Execute the operation

current_span.add_event("Operation completed!")

Define Span Status

Span status is used to indicate the success or failure of the code executed within the span.

from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

current_span = trace.get_current_span()

try:
    # operation that might fail
except:
    current_span.set_status(Status(StatusCode.ERROR))

Log Exceptions in Spans

Recording exceptions when they occur is advisable. This should be done alongside setting the span status.

from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

current_span = trace.get_current_span()

try:
    # operation that might fail

# Consider catching a more specific exception in your code
except Exception as ex:
    current_span.set_status(Status(StatusCode.ERROR))
    current_span.record_exception(ex)