or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

common.mdexporters.mdindex.mdlogging.mdmetrics-stats.mdtags-context.mdtracing.md

tracing.mddocs/

0

# Distributed Tracing

1

2

Core tracing functionality that forms the foundation of OpenCensus observability. Provides distributed tracing capabilities including span creation, context management, sampling strategies, and trace export to various backends.

3

4

## Capabilities

5

6

### Tracer Management

7

8

The `Tracer` class coordinates span creation, sampling decisions, and trace export. It serves as the main entry point for creating and managing distributed traces.

9

10

```python { .api }

11

class Tracer:

12

"""

13

Main tracing coordinator that manages span creation and export.

14

15

Parameters:

16

- span_context: SpanContext, existing trace context

17

- sampler: Sampler, sampling strategy (default: probability sampler)

18

- exporter: Exporter, trace export destination

19

- propagator: Propagator, context propagation format

20

"""

21

def __init__(self, span_context=None, sampler=None, exporter=None, propagator=None): ...

22

23

def span(self, name='span'):

24

"""

25

Create a new span as a context manager.

26

27

Parameters:

28

- name: str, span name/operation name

29

30

Returns:

31

Span context manager

32

"""

33

34

def should_sample(self):

35

"""

36

Determine if current trace should be sampled.

37

38

Returns:

39

bool: True if trace should be sampled

40

"""

41

42

def get_tracer(self):

43

"""Get the current tracer instance."""

44

45

def store_tracer(self):

46

"""Store tracer in execution context."""

47

48

def finish(self):

49

"""Finish the current trace and export data."""

50

51

def start_span(self, name='span'):

52

"""

53

Start a new span and set it as current span.

54

55

Parameters:

56

- name: str, span name/operation name

57

58

Returns:

59

Span: The created span

60

"""

61

62

def end_span(self):

63

"""

64

End the current span.

65

Update the span_id in SpanContext to the current span's parent span id;

66

Update the current span; Send the span to exporter.

67

"""

68

69

def current_span(self):

70

"""

71

Return the current span.

72

73

Returns:

74

Span: The current active span

75

"""

76

77

def add_attribute_to_current_span(self, attribute_key, attribute_value):

78

"""

79

Add attribute to current span.

80

81

Parameters:

82

- attribute_key: str, attribute name

83

- attribute_value: str, attribute value

84

"""

85

86

def trace_decorator(self):

87

"""

88

Decorator to trace a function.

89

90

Returns:

91

function: Decorator function that wraps the target function with tracing

92

"""

93

```

94

95

### Span Operations

96

97

Individual units of work in a distributed trace. Spans represent operations with timing information, attributes, annotations, and hierarchical relationships.

98

99

```python { .api }

100

class Span:

101

"""

102

Individual trace span representing a unit of work.

103

104

Parameters:

105

- name: str, span name/operation name

106

- parent_span: Span, parent span for hierarchy

107

- attributes: dict, initial span attributes

108

- start_time: datetime, span start time

109

- end_time: datetime, span end time (for completed spans)

110

- span_id: str, unique span identifier

111

- stack_trace: StackTrace, call stack capture

112

- annotations: list, time-based annotations

113

- message_events: list, message/log events

114

- links: list, links to other spans

115

- status: Status, span completion status

116

- same_process_as_parent_span: bool, process relationship

117

- context_tracer: Tracer, associated tracer

118

- span_kind: SpanKind, span type (client, server, etc.)

119

"""

120

def __init__(self, name, parent_span=None, attributes=None, start_time=None,

121

end_time=None, span_id=None, stack_trace=None, annotations=None,

122

message_events=None, links=None, status=None,

123

same_process_as_parent_span=None, context_tracer=None,

124

span_kind=SpanKind.UNSPECIFIED): ...

125

126

def add_attribute(self, key, value):

127

"""

128

Add key-value attribute to span.

129

130

Parameters:

131

- key: str, attribute name

132

- value: str/int/float/bool, attribute value

133

"""

134

135

def add_annotation(self, description, **attrs):

136

"""

137

Add time-based annotation to span.

138

139

Parameters:

140

- description: str, annotation description

141

- **attrs: additional annotation attributes

142

143

Note: Timestamp is automatically set to current UTC time

144

"""

145

146

def add_message_event(self, message_event):

147

"""

148

Add message/log event to span.

149

150

Parameters:

151

- message_event: MessageEvent, structured message

152

"""

153

154

def add_link(self, link):

155

"""

156

Add link to another span.

157

158

Parameters:

159

- link: Link, span link object

160

"""

161

162

def set_status(self, status):

163

"""

164

Set span completion status.

165

166

Parameters:

167

- status: Status, gRPC-compatible status

168

"""

169

170

def start(self):

171

"""Start the span timing."""

172

173

def finish(self):

174

"""End the span and record completion time."""

175

```

176

177

### Span Context

178

179

Represents the current trace context including trace ID, span ID, and trace options for context propagation across service boundaries.

180

181

```python { .api }

182

class SpanContext:

183

"""

184

Current trace context for propagation.

185

186

Parameters:

187

- trace_id: str, unique trace identifier (32 hex chars)

188

- span_id: str, unique span identifier (16 hex chars)

189

- trace_options: TraceOptions, trace flags and options

190

- from_header: bool, whether context came from header

191

- tracestate: str, W3C tracestate for vendor data

192

"""

193

def __init__(self, trace_id=None, span_id=None, trace_options=None,

194

tracestate=None, from_header=False): ...

195

196

@property

197

def trace_id(self):

198

"""str: Unique trace identifier"""

199

200

@property

201

def span_id(self):

202

"""str: Unique span identifier"""

203

204

@property

205

def trace_options(self):

206

"""TraceOptions: Trace configuration flags"""

207

208

@property

209

def from_header(self):

210

"""bool: Whether context originated from header"""

211

212

@property

213

def tracestate(self):

214

"""str: W3C tracestate vendor data"""

215

```

216

217

### Sampling Strategies

218

219

Control which traces are collected and exported to manage performance impact and storage costs.

220

221

```python { .api }

222

class Sampler:

223

"""Base class for sampling strategies."""

224

def should_sample(self, span_context):

225

"""

226

Determine if span should be sampled.

227

228

Parameters:

229

- span_context: SpanContext, current trace context

230

231

Returns:

232

bool: True if span should be sampled

233

"""

234

235

class AlwaysOnSampler(Sampler):

236

"""Samples every trace (100% sampling rate)."""

237

238

class AlwaysOffSampler(Sampler):

239

"""Samples no traces (0% sampling rate)."""

240

241

class ProbabilitySampler(Sampler):

242

"""

243

Fixed probability sampling.

244

245

Parameters:

246

- rate: float, sampling rate between 0.0 and 1.0

247

"""

248

def __init__(self, rate=None): ...

249

```

250

251

### Status and Error Handling

252

253

gRPC-compatible status codes for representing span completion states and error conditions.

254

255

```python { .api }

256

class Status:

257

"""

258

gRPC-compatible span completion status.

259

260

Parameters:

261

- code: int, status code (0=OK, non-zero=error)

262

- message: str, status message

263

- details: str, additional status details

264

"""

265

def __init__(self, code, message=None, details=None): ...

266

267

@property

268

def canonical_code(self):

269

"""int: Canonical status code"""

270

271

@property

272

def description(self):

273

"""str: Status description"""

274

275

@property

276

def is_ok(self):

277

"""bool: True if status indicates success"""

278

279

def format_status_json(self):

280

"""dict: Status as JSON-serializable dictionary"""

281

282

@classmethod

283

def from_exception(cls, exc):

284

"""

285

Create status from Python exception.

286

287

Parameters:

288

- exc: Exception, Python exception object

289

290

Returns:

291

Status: Status representing the exception

292

"""

293

294

@classmethod

295

def as_ok(cls):

296

"""

297

Create OK status.

298

299

Returns:

300

Status: Success status

301

"""

302

```

303

304

### Bounded Collections

305

306

Memory-efficient collections for span data with automatic size limits to prevent memory issues in long-running traces.

307

308

```python { .api }

309

class BoundedList:

310

"""

311

Append-only list with fixed maximum size.

312

313

Parameters:

314

- maxlen: int, maximum number of items

315

"""

316

def __init__(self, maxlen): ...

317

318

def append(self, item):

319

"""Add item, dropping oldest if at capacity."""

320

321

def extend(self, items):

322

"""Add multiple items, maintaining size limit."""

323

324

class BoundedDict:

325

"""

326

Dictionary with fixed maximum capacity.

327

328

Parameters:

329

- maxlen: int, maximum number of key-value pairs

330

"""

331

def __init__(self, maxlen): ...

332

333

def __setitem__(self, key, value):

334

"""Set value, removing oldest entries if at capacity."""

335

336

def __getitem__(self, key):

337

"""Get value by key."""

338

```

339

340

## Usage Examples

341

342

### Basic Tracing

343

344

```python

345

from opencensus.trace.tracer import Tracer

346

from opencensus.trace.samplers import ProbabilitySampler

347

from opencensus.trace import print_exporter

348

349

# Create tracer with 50% sampling

350

tracer = Tracer(

351

sampler=ProbabilitySampler(rate=0.5),

352

exporter=print_exporter.PrintExporter()

353

)

354

355

# Use span as context manager

356

with tracer.span('database_query') as span:

357

span.add_attribute('query', 'SELECT * FROM users')

358

span.add_attribute('rows_returned', 42)

359

360

# Simulate database work

361

result = query_database()

362

363

span.add_annotation('Query completed successfully')

364

span.set_status(Status.as_ok())

365

```

366

367

### Manual Span Management

368

369

```python

370

from opencensus.trace.tracer import Tracer

371

from opencensus.trace.span import Span

372

373

tracer = Tracer()

374

375

# Create and start span manually

376

span = tracer.span('http_request')

377

span.start()

378

379

try:

380

span.add_attribute('http.method', 'GET')

381

span.add_attribute('http.url', 'https://api.example.com/users')

382

383

# Make HTTP request

384

response = make_request()

385

386

span.add_attribute('http.status_code', response.status_code)

387

span.set_status(Status.as_ok())

388

389

except Exception as e:

390

span.set_status(Status.from_exception(e))

391

raise

392

finally:

393

span.finish()

394

```

395

396

### Nested Spans

397

398

```python

399

from opencensus.trace.tracer import Tracer

400

401

tracer = Tracer()

402

403

with tracer.span('process_order') as parent_span:

404

parent_span.add_attribute('order_id', '12345')

405

406

# Child span for validation

407

with tracer.span('validate_order') as child_span:

408

child_span.add_attribute('validation_rules', 5)

409

validate_order_data()

410

411

# Child span for payment

412

with tracer.span('process_payment') as child_span:

413

child_span.add_attribute('payment_method', 'credit_card')

414

process_payment()

415

416

parent_span.add_annotation('Order processing completed')

417

```