0
# OpenTelemetry API
1
2
The 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.
3
4
## Package Information
5
6
- **Package Name**: opentelemetry-api
7
- **Language**: Python
8
- **Installation**: `pip install opentelemetry-api`
9
- **Version**: 1.36.0
10
11
## Core Imports
12
13
```python
14
import opentelemetry
15
```
16
17
Common patterns for different observability signals:
18
19
```python
20
# Tracing
21
from opentelemetry import trace
22
from opentelemetry.trace import Tracer, Span, SpanKind, Status, StatusCode
23
24
# Metrics
25
from opentelemetry import metrics
26
from opentelemetry.metrics import Meter, Counter, Histogram, _Gauge
27
28
# Context and Baggage
29
from opentelemetry import context, baggage
30
from opentelemetry.context import Context
31
32
# Propagation
33
from opentelemetry import propagate
34
```
35
36
## Basic Usage
37
38
```python
39
from opentelemetry import trace, metrics, context, baggage
40
41
# Set up tracing
42
tracer = trace.get_tracer(__name__)
43
44
# Create spans for distributed tracing
45
with tracer.start_as_current_span("my-operation") as span:
46
span.set_attribute("service.version", "1.0.0")
47
48
# Add baggage for cross-service context
49
ctx = baggage.set_baggage("user.id", "12345")
50
51
# Use metrics to record measurements
52
meter = metrics.get_meter(__name__)
53
counter = meter.create_counter("requests_total")
54
counter.add(1, {"method": "GET", "endpoint": "/api/data"})
55
56
# Perform work with full observability
57
do_business_logic()
58
```
59
60
## Architecture
61
62
OpenTelemetry API follows a provider-based architecture that enables pluggable implementations:
63
64
- **Providers**: Factory objects that create tracers, meters, and loggers (TracerProvider, MeterProvider, LoggerProvider)
65
- **Instruments**: Create observability signals (Tracer creates spans, Meter creates measurement instruments)
66
- **Context System**: Immutable context propagation with copy-on-write semantics for cross-cutting concerns
67
- **Propagators**: Extract and inject context across service boundaries using standard formats (W3C Trace Context, W3C Baggage)
68
- **No-Op Implementations**: Complete no-op implementations allow using the API without a backing implementation
69
70
This design enables applications to use OpenTelemetry APIs without vendor lock-in while supporting extensive configurability through environment variables and programmatic setup.
71
72
## Capabilities
73
74
### Distributed Tracing
75
76
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.
77
78
```python { .api }
79
class Tracer(ABC):
80
def start_span(self, name: str, context: Optional[Context] = None,
81
kind: SpanKind = SpanKind.INTERNAL, **kwargs) -> Span: ...
82
def start_as_current_span(self, name: str, **kwargs) -> Iterator[Span]: ...
83
84
def get_tracer(instrumenting_module_name: str,
85
instrumenting_library_version: Optional[str] = None) -> Tracer: ...
86
def get_tracer_provider() -> TracerProvider: ...
87
def set_tracer_provider(tracer_provider: TracerProvider) -> None: ...
88
```
89
90
[Distributed Tracing](./tracing.md)
91
92
### Metrics Collection
93
94
Record measurements using counters, gauges, histograms, and observable instruments. Supports both synchronous recording and asynchronous callback-based collection with rich attribute dimensions.
95
96
```python { .api }
97
class Meter(ABC):
98
def create_counter(self, name: str, **kwargs) -> Counter: ...
99
def create_histogram(self, name: str, **kwargs) -> Histogram: ...
100
def create_gauge(self, name: str, **kwargs) -> Gauge: ...
101
def create_observable_counter(self, name: str, **kwargs) -> ObservableCounter: ...
102
103
def get_meter(instrumenting_module_name: str,
104
instrumenting_library_version: Optional[str] = None) -> Meter: ...
105
def get_meter_provider() -> MeterProvider: ...
106
def set_meter_provider(meter_provider: MeterProvider) -> None: ...
107
```
108
109
[Metrics Collection](./metrics.md)
110
111
### Context Management
112
113
Manage execution context with immutable context objects and runtime context propagation. Enables cross-cutting concerns like trace correlation, baggage propagation, and instrumentation suppression.
114
115
```python { .api }
116
class Context:
117
def get(self, key: str) -> object: ...
118
def copy(self) -> Dict[str, object]: ...
119
120
def create_key(keyname: str) -> str: ...
121
def get_value(key: str, context: Optional[Context] = None) -> object: ...
122
def set_value(key: str, value: object, context: Optional[Context] = None) -> Context: ...
123
def get_current() -> Context: ...
124
def attach(context: Context) -> Token[Context]: ...
125
def detach(token: Token[Context]) -> None: ...
126
```
127
128
[Context Management](./context.md)
129
130
### Cross-Service Propagation
131
132
Extract and inject observability context across service boundaries using standard HTTP headers. Supports W3C Trace Context and W3C Baggage propagation with pluggable propagator implementations.
133
134
```python { .api }
135
def extract(carrier: CarrierT, context: Optional[Context] = None,
136
getter: Getter[CarrierT] = default_getter) -> Context: ...
137
def inject(carrier: CarrierT, context: Optional[Context] = None,
138
setter: Setter[CarrierT] = default_setter) -> None: ...
139
def get_global_textmap() -> TextMapPropagator: ...
140
def set_global_textmap(http_text_format: TextMapPropagator) -> None: ...
141
```
142
143
[Cross-Service Propagation](./propagation.md)
144
145
### Logging and Events
146
147
Structured logging and event recording with severity levels, attributes, and integration with the OpenTelemetry context system for trace correlation.
148
149
```python { .api }
150
class Logger(ABC):
151
def emit(self, log_record: LogRecord) -> None: ...
152
153
class EventLogger(ABC):
154
def emit(self, event: Event) -> None: ...
155
156
def get_logger(instrumenting_module_name: str) -> Logger: ...
157
def get_logger_provider() -> LoggerProvider: ...
158
def set_logger_provider(logger_provider: LoggerProvider) -> None: ...
159
```
160
161
[Logging and Events](./logging.md)
162
163
## Types
164
165
```python { .api }
166
# Core attribute types
167
AttributeValue = Union[str, bool, int, float, Sequence[str], Sequence[bool],
168
Sequence[int], Sequence[float]]
169
Attributes = Optional[Mapping[str, AttributeValue]]
170
171
# Extended attribute type for logs (includes bytes, nested mappings, sequences)
172
AnyValue = Union[str, bool, int, float, bytes, Sequence["AnyValue"],
173
Mapping[str, "AnyValue"], None]
174
175
# Span types
176
class SpanKind(Enum):
177
INTERNAL = 0
178
SERVER = 1
179
CLIENT = 2
180
PRODUCER = 3
181
CONSUMER = 4
182
183
class StatusCode(Enum):
184
UNSET = 0
185
OK = 1
186
ERROR = 2
187
188
# Severity levels for logging
189
class SeverityNumber(Enum):
190
TRACE = 1
191
DEBUG = 5
192
INFO = 9
193
WARN = 13
194
ERROR = 17
195
FATAL = 21
196
```