OpenTelemetry Python API providing core abstractions for distributed tracing, metrics collection, and context propagation
npx @tessl/cli install tessl/pypi-opentelemetry-api@1.36.0The core OpenTelemetry Python API that provides fundamental abstractions and interfaces for observability instrumentation. This library enables developers to instrument their applications with vendor-neutral distributed tracing, metrics collection, logging, and context propagation capabilities that integrate with any OpenTelemetry-compatible backend system.
pip install opentelemetry-apiimport opentelemetryCommon patterns for different observability signals:
# Tracing
from opentelemetry import trace
from opentelemetry.trace import Tracer, Span, SpanKind, Status, StatusCode
# Metrics
from opentelemetry import metrics
from opentelemetry.metrics import Meter, Counter, Histogram, _Gauge
# Context and Baggage
from opentelemetry import context, baggage
from opentelemetry.context import Context
# Propagation
from opentelemetry import propagatefrom opentelemetry import trace, metrics, context, baggage
# Set up tracing
tracer = trace.get_tracer(__name__)
# Create spans for distributed tracing
with tracer.start_as_current_span("my-operation") as span:
span.set_attribute("service.version", "1.0.0")
# Add baggage for cross-service context
ctx = baggage.set_baggage("user.id", "12345")
# Use metrics to record measurements
meter = metrics.get_meter(__name__)
counter = meter.create_counter("requests_total")
counter.add(1, {"method": "GET", "endpoint": "/api/data"})
# Perform work with full observability
do_business_logic()OpenTelemetry API follows a provider-based architecture that enables pluggable implementations:
This design enables applications to use OpenTelemetry APIs without vendor lock-in while supporting extensive configurability through environment variables and programmatic setup.
Create and manage distributed traces with spans representing operations across services. Supports span relationships, attributes, events, links, and status reporting with W3C Trace Context propagation.
class Tracer(ABC):
def start_span(self, name: str, context: Optional[Context] = None,
kind: SpanKind = SpanKind.INTERNAL, **kwargs) -> Span: ...
def start_as_current_span(self, name: str, **kwargs) -> Iterator[Span]: ...
def get_tracer(instrumenting_module_name: str,
instrumenting_library_version: Optional[str] = None) -> Tracer: ...
def get_tracer_provider() -> TracerProvider: ...
def set_tracer_provider(tracer_provider: TracerProvider) -> None: ...Record measurements using counters, gauges, histograms, and observable instruments. Supports both synchronous recording and asynchronous callback-based collection with rich attribute dimensions.
class Meter(ABC):
def create_counter(self, name: str, **kwargs) -> Counter: ...
def create_histogram(self, name: str, **kwargs) -> Histogram: ...
def create_gauge(self, name: str, **kwargs) -> Gauge: ...
def create_observable_counter(self, name: str, **kwargs) -> ObservableCounter: ...
def get_meter(instrumenting_module_name: str,
instrumenting_library_version: Optional[str] = None) -> Meter: ...
def get_meter_provider() -> MeterProvider: ...
def set_meter_provider(meter_provider: MeterProvider) -> None: ...Manage execution context with immutable context objects and runtime context propagation. Enables cross-cutting concerns like trace correlation, baggage propagation, and instrumentation suppression.
class Context:
def get(self, key: str) -> object: ...
def copy(self) -> Dict[str, object]: ...
def create_key(keyname: str) -> str: ...
def get_value(key: str, context: Optional[Context] = None) -> object: ...
def set_value(key: str, value: object, context: Optional[Context] = None) -> Context: ...
def get_current() -> Context: ...
def attach(context: Context) -> Token[Context]: ...
def detach(token: Token[Context]) -> None: ...Extract and inject observability context across service boundaries using standard HTTP headers. Supports W3C Trace Context and W3C Baggage propagation with pluggable propagator implementations.
def extract(carrier: CarrierT, context: Optional[Context] = None,
getter: Getter[CarrierT] = default_getter) -> Context: ...
def inject(carrier: CarrierT, context: Optional[Context] = None,
setter: Setter[CarrierT] = default_setter) -> None: ...
def get_global_textmap() -> TextMapPropagator: ...
def set_global_textmap(http_text_format: TextMapPropagator) -> None: ...Structured logging and event recording with severity levels, attributes, and integration with the OpenTelemetry context system for trace correlation.
class Logger(ABC):
def emit(self, log_record: LogRecord) -> None: ...
class EventLogger(ABC):
def emit(self, event: Event) -> None: ...
def get_logger(instrumenting_module_name: str) -> Logger: ...
def get_logger_provider() -> LoggerProvider: ...
def set_logger_provider(logger_provider: LoggerProvider) -> None: ...# Core attribute types
AttributeValue = Union[str, bool, int, float, Sequence[str], Sequence[bool],
Sequence[int], Sequence[float]]
Attributes = Optional[Mapping[str, AttributeValue]]
# Extended attribute type for logs (includes bytes, nested mappings, sequences)
AnyValue = Union[str, bool, int, float, bytes, Sequence["AnyValue"],
Mapping[str, "AnyValue"], None]
# Span types
class SpanKind(Enum):
INTERNAL = 0
SERVER = 1
CLIENT = 2
PRODUCER = 3
CONSUMER = 4
class StatusCode(Enum):
UNSET = 0
OK = 1
ERROR = 2
# Severity levels for logging
class SeverityNumber(Enum):
TRACE = 1
DEBUG = 5
INFO = 9
WARN = 13
ERROR = 17
FATAL = 21