or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context.mdindex.mdlogging.mdmetrics.mdpropagation.mdtracing.md

tracing.mddocs/

0

# Distributed Tracing

1

2

Comprehensive distributed tracing capabilities for creating and managing spans across services. OpenTelemetry tracing provides the foundation for distributed system observability with support for span relationships, attributes, events, and W3C Trace Context propagation.

3

4

## Capabilities

5

6

### Tracer Creation and Management

7

8

Get tracers for creating spans with proper instrumentation scope identification.

9

10

```python { .api }

11

def get_tracer(

12

instrumenting_module_name: str,

13

instrumenting_library_version: Optional[str] = None,

14

tracer_provider: Optional[TracerProvider] = None,

15

schema_url: Optional[str] = None,

16

attributes: Optional[Attributes] = None,

17

) -> Tracer:

18

"""

19

Returns a Tracer for use by the given instrumentation library.

20

21

Parameters:

22

- instrumenting_module_name: The name of the instrumentation scope

23

- instrumenting_library_version: Optional version of the instrumentation library

24

- tracer_provider: Optional specific TracerProvider to use

25

- schema_url: Optional Schema URL of the emitted telemetry

26

- attributes: Optional attributes of the emitted telemetry

27

28

Returns:

29

Tracer instance for creating spans

30

"""

31

32

def get_tracer_provider() -> TracerProvider:

33

"""Gets the current global TracerProvider object."""

34

35

def set_tracer_provider(tracer_provider: TracerProvider) -> None:

36

"""

37

Sets the current global TracerProvider object.

38

This can only be done once, a warning will be logged if any further attempt is made.

39

"""

40

```

41

42

### Span Creation and Lifecycle

43

44

Create spans to represent operations in distributed traces with full lifecycle management.

45

46

```python { .api }

47

class Tracer(ABC):

48

def start_span(

49

self,

50

name: str,

51

context: Optional[Context] = None,

52

kind: SpanKind = SpanKind.INTERNAL,

53

attributes: Attributes = None,

54

links: Optional[Sequence[Link]] = None,

55

start_time: Optional[int] = None,

56

record_exception: bool = True,

57

set_status_on_exception: bool = True,

58

) -> Span:

59

"""

60

Starts a span.

61

62

Parameters:

63

- name: The name of the span to be created

64

- context: An optional Context containing the span's parent

65

- kind: The span's kind (relationship to parent)

66

- attributes: The span's attributes

67

- links: Links span to other spans

68

- start_time: Sets the start time of a span

69

- record_exception: Whether to record exceptions as error events

70

- set_status_on_exception: Whether to set span status on exceptions

71

72

Returns:

73

The newly-created span

74

"""

75

76

def start_as_current_span(

77

self,

78

name: str,

79

context: Optional[Context] = None,

80

kind: SpanKind = SpanKind.INTERNAL,

81

attributes: Attributes = None,

82

links: Optional[Sequence[Link]] = None,

83

start_time: Optional[int] = None,

84

record_exception: bool = True,

85

set_status_on_exception: bool = True,

86

end_on_exit: bool = True,

87

) -> Iterator[Span]:

88

"""

89

Context manager for creating a new span and set it as the current span.

90

91

Parameters:

92

- name: The name of the span to be created

93

- context: An optional Context containing the span's parent

94

- kind: The span's kind (relationship to parent)

95

- attributes: The span's attributes

96

- links: Links span to other spans

97

- start_time: Sets the start time of a span

98

- record_exception: Whether to record exceptions as error events

99

- set_status_on_exception: Whether to set span status on exceptions

100

- end_on_exit: Whether to end the span when leaving the context manager

101

102

Yields:

103

The newly-created span

104

"""

105

```

106

107

### Span Operations and Metadata

108

109

Manage span data including attributes, events, status, and relationships.

110

111

```python { .api }

112

class Span(ABC):

113

def get_span_context(self) -> SpanContext:

114

"""Returns the SpanContext for this span."""

115

116

def set_attribute(self, key: str, value: AttributeValue) -> None:

117

"""Sets a single attribute on the span."""

118

119

def set_attributes(self, attributes: Attributes) -> None:

120

"""Sets multiple attributes on the span."""

121

122

def add_event(

123

self,

124

name: str,

125

attributes: Attributes = None,

126

timestamp: Optional[int] = None,

127

) -> None:

128

"""

129

Adds an event to the span.

130

131

Parameters:

132

- name: Name of the event

133

- attributes: Event attributes

134

- timestamp: Optional timestamp of the event

135

"""

136

137

def update_name(self, name: str) -> None:

138

"""Updates the span name."""

139

140

def set_status(self, status: Status) -> None:

141

"""Sets the span status."""

142

143

def record_exception(

144

self,

145

exception: BaseException,

146

attributes: Attributes = None,

147

timestamp: Optional[int] = None,

148

escaped: bool = False,

149

) -> None:

150

"""

151

Records an exception as a span event.

152

153

Parameters:

154

- exception: The exception to record

155

- attributes: Additional attributes for the exception event

156

- timestamp: Optional timestamp of the exception

157

- escaped: Whether the exception escaped the span scope

158

"""

159

160

def is_recording(self) -> bool:

161

"""Returns True if the span is recording data."""

162

163

def end(self, end_time: Optional[int] = None) -> None:

164

"""Ends the span."""

165

```

166

167

### Span Context and Propagation

168

169

Access span context for propagation and parent-child relationships.

170

171

```python { .api }

172

class SpanContext:

173

"""Immutable span state for propagation."""

174

175

@property

176

def trace_id(self) -> int:

177

"""The trace ID of the span context."""

178

179

@property

180

def span_id(self) -> int:

181

"""The span ID of the span context."""

182

183

@property

184

def trace_flags(self) -> TraceFlags:

185

"""The trace flags of the span context."""

186

187

@property

188

def trace_state(self) -> TraceState:

189

"""The trace state of the span context."""

190

191

@property

192

def is_valid(self) -> bool:

193

"""Returns True if the span context is valid."""

194

195

def get_current_span(context: Optional[Context] = None) -> Span:

196

"""Returns the current span from the context."""

197

198

def set_span_in_context(span: Span, context: Optional[Context] = None) -> Context:

199

"""Returns a new context with the span set."""

200

201

def use_span(

202

span: Span,

203

end_on_exit: bool = False,

204

record_exception: bool = True,

205

set_status_on_exception: bool = True,

206

) -> Iterator[Span]:

207

"""

208

Takes a non-active span and activates it in the current context.

209

210

Parameters:

211

- span: The span that should be activated

212

- end_on_exit: Whether to end the span when leaving the context

213

- record_exception: Whether to record exceptions as error events

214

- set_status_on_exception: Whether to set span status on exceptions

215

216

Yields:

217

The activated span

218

"""

219

```

220

221

### Links and Relationships

222

223

Create relationships between spans across different traces.

224

225

```python { .api }

226

class Link:

227

"""A link to a Span. The attributes of a Link are immutable."""

228

229

def __init__(

230

self,

231

context: SpanContext,

232

attributes: Attributes = None,

233

) -> None:

234

"""

235

Parameters:

236

- context: SpanContext of the Span to link to

237

- attributes: Link's attributes

238

"""

239

240

@property

241

def context(self) -> SpanContext:

242

"""Returns the SpanContext of the linked span."""

243

244

@property

245

def attributes(self) -> Attributes:

246

"""Returns the link's attributes."""

247

248

@property

249

def dropped_attributes(self) -> int:

250

"""Returns the number of dropped attributes."""

251

```

252

253

### Status and Error Handling

254

255

Manage span status and error conditions.

256

257

```python { .api }

258

class Status:

259

"""Represents the status of a span."""

260

261

def __init__(

262

self,

263

status_code: StatusCode = StatusCode.UNSET,

264

description: Optional[str] = None,

265

) -> None:

266

"""

267

Parameters:

268

- status_code: The status code

269

- description: Optional description of the status

270

"""

271

272

@property

273

def status_code(self) -> StatusCode:

274

"""Returns the status code."""

275

276

@property

277

def description(self) -> Optional[str]:

278

"""Returns the status description."""

279

280

class StatusCode(Enum):

281

"""Represents the canonical status of a span."""

282

UNSET = 0 # Default status

283

OK = 1 # Operation completed successfully

284

ERROR = 2 # Operation contains an error

285

```

286

287

### Provider Implementations

288

289

Provider classes for different deployment scenarios.

290

291

```python { .api }

292

class TracerProvider(ABC):

293

"""Abstract base class for tracer providers."""

294

295

def get_tracer(

296

self,

297

instrumenting_module_name: str,

298

instrumenting_library_version: Optional[str] = None,

299

schema_url: Optional[str] = None,

300

attributes: Optional[Attributes] = None,

301

) -> Tracer:

302

"""Returns a Tracer for use by the given instrumentation library."""

303

304

class NoOpTracerProvider(TracerProvider):

305

"""The default TracerProvider, used when no implementation is available."""

306

307

def get_tracer(

308

self,

309

instrumenting_module_name: str,

310

instrumenting_library_version: Optional[str] = None,

311

schema_url: Optional[str] = None,

312

attributes: Optional[Attributes] = None,

313

) -> Tracer:

314

"""Returns a no-op tracer."""

315

316

class ProxyTracerProvider(TracerProvider):

317

"""Proxy tracer provider for late binding of real providers."""

318

319

def get_tracer(

320

self,

321

instrumenting_module_name: str,

322

instrumenting_library_version: Optional[str] = None,

323

schema_url: Optional[str] = None,

324

attributes: Optional[Attributes] = None,

325

) -> Tracer:

326

"""Returns a tracer from the real provider or proxy tracer."""

327

```

328

329

## Usage Examples

330

331

### Basic Span Creation

332

333

```python

334

from opentelemetry import trace

335

336

# Get a tracer

337

tracer = trace.get_tracer(__name__)

338

339

# Create a simple span

340

with tracer.start_as_current_span("my-operation") as span:

341

span.set_attribute("user.id", "12345")

342

span.add_event("Processing started")

343

344

# Do work

345

result = process_data()

346

347

span.set_attribute("result.count", len(result))

348

span.add_event("Processing completed")

349

```

350

351

### Parent-Child Span Relationships

352

353

```python

354

from opentelemetry import trace

355

from opentelemetry.trace import SpanKind

356

357

tracer = trace.get_tracer(__name__)

358

359

# Parent span representing an HTTP request

360

with tracer.start_as_current_span("handle-request", kind=SpanKind.SERVER) as parent:

361

parent.set_attribute("http.method", "GET")

362

parent.set_attribute("http.url", "/api/users")

363

364

# Child span for database operation

365

with tracer.start_as_current_span("query-database", kind=SpanKind.CLIENT) as child:

366

child.set_attribute("db.system", "postgresql")

367

child.set_attribute("db.statement", "SELECT * FROM users")

368

369

# Another child span for cache check

370

with tracer.start_as_current_span("check-cache") as cache_span:

371

cache_span.set_attribute("cache.hit", True)

372

```

373

374

### Error Handling and Status

375

376

```python

377

from opentelemetry import trace

378

from opentelemetry.trace import Status, StatusCode

379

380

tracer = trace.get_tracer(__name__)

381

382

with tracer.start_as_current_span("risky-operation") as span:

383

try:

384

result = perform_risky_operation()

385

span.set_status(Status(StatusCode.OK))

386

except ValueError as e:

387

span.record_exception(e)

388

span.set_status(Status(StatusCode.ERROR, str(e)))

389

span.set_attribute("error.type", "ValueError")

390

raise

391

```

392

393

## Constants

394

395

```python { .api }

396

# Default values

397

DEFAULT_TRACE_OPTIONS: TraceFlags

398

DEFAULT_TRACE_STATE: TraceState

399

400

# Invalid constants for no-op scenarios

401

INVALID_SPAN: Span

402

INVALID_SPAN_CONTEXT: SpanContext

403

INVALID_SPAN_ID: int

404

INVALID_TRACE_ID: int

405

406

# Utility functions

407

def format_span_id(span_id: int) -> str:

408

"""Format span ID as hex string."""

409

410

def format_trace_id(trace_id: int) -> str:

411

"""Format trace ID as hex string."""

412

```