or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations-metadata.mdaws-services.mdconfiguration-plugins.mdcore-recording.mddatabase-integration.mdhttp-utilities.mdindex.mdlibrary-patching.mdsampling.mdweb-frameworks.md

core-recording.mddocs/

0

# Core Recording

1

2

Primary tracing functionality for creating and managing X-Ray segments and subsegments. Provides both synchronous and asynchronous recording capabilities through context managers, decorators, and manual management methods.

3

4

## Capabilities

5

6

### Global Recorder Instance

7

8

The SDK provides a global recorder instance that serves as the primary interface for X-Ray tracing operations.

9

10

```python { .api }

11

xray_recorder: AsyncAWSXRayRecorder

12

```

13

14

The global `xray_recorder` is an instance of `AsyncAWSXRayRecorder` that provides both synchronous and asynchronous tracing capabilities.

15

16

### Recorder Configuration

17

18

Configure the X-Ray recorder with sampling settings, plugins, context behavior, and daemon connection details.

19

20

```python { .api }

21

def configure(

22

sampling: bool = None,

23

plugins: tuple = None,

24

context_missing: str = None,

25

sampling_rules: str = None,

26

daemon_address: str = None,

27

service: str = None,

28

context: object = None,

29

emitter: object = None,

30

streaming: bool = None,

31

dynamic_naming: str = None,

32

streaming_threshold: int = None,

33

max_trace_back: int = None,

34

sampler: object = None,

35

stream_sql: bool = None

36

) -> None:

37

"""

38

Configure the X-Ray recorder.

39

40

Args:

41

sampling (bool): Enable/disable sampling

42

plugins (tuple): Plugin names to load ('EC2Plugin', 'ECSPlugin', 'ElasticBeanstalkPlugin')

43

context_missing (str): Behavior when no active segment ('LOG_ERROR', 'RUNTIME_ERROR', 'IGNORE_ERROR')

44

sampling_rules (str): Path to sampling rules JSON file

45

daemon_address (str): X-Ray daemon address (default: '127.0.0.1:2000')

46

service (str): Service name override

47

context (object): Context implementation for trace storage

48

emitter (object): Custom emitter for sending traces

49

streaming (bool): Enable subsegment streaming

50

dynamic_naming (str): Pattern for dynamic segment naming

51

streaming_threshold (int): Subsegment count threshold for streaming

52

max_trace_back (int): Maximum stack trace depth

53

sampler (object): Custom sampler implementation

54

stream_sql (bool): Enable SQL query streaming

55

"""

56

```

57

58

### Context Managers

59

60

#### Segment Context Managers

61

62

Create and manage segments using context managers for automatic lifecycle management.

63

64

```python { .api }

65

def in_segment(name: str, **segment_kwargs) -> SegmentContextManager:

66

"""

67

Context manager for creating and managing a segment.

68

69

Args:

70

name (str): Segment name

71

**segment_kwargs: Additional segment parameters

72

73

Returns:

74

SegmentContextManager: Context manager yielding the segment

75

76

Usage:

77

with xray_recorder.in_segment('my-segment') as segment:

78

# Traced code here

79

"""

80

81

def in_segment_async(name: str, **segment_kwargs) -> AsyncSegmentContextManager:

82

"""

83

Async context manager for creating and managing a segment.

84

85

Args:

86

name (str): Segment name

87

**segment_kwargs: Additional segment parameters

88

89

Returns:

90

AsyncSegmentContextManager: Async context manager yielding the segment

91

92

Usage:

93

async with xray_recorder.in_segment_async('my-segment') as segment:

94

# Traced async code here

95

"""

96

```

97

98

#### Subsegment Context Managers

99

100

Create and manage subsegments within segments for detailed tracing of operations.

101

102

```python { .api }

103

def in_subsegment(name: str, **subsegment_kwargs) -> SubsegmentContextManager:

104

"""

105

Context manager for creating and managing a subsegment.

106

107

Args:

108

name (str): Subsegment name

109

**subsegment_kwargs: Additional subsegment parameters

110

111

Returns:

112

SubsegmentContextManager: Context manager yielding the subsegment

113

114

Usage:

115

with xray_recorder.in_subsegment('database-query') as subsegment:

116

# Database operation here

117

"""

118

119

def in_subsegment_async(name: str, **subsegment_kwargs) -> AsyncSubsegmentContextManager:

120

"""

121

Async context manager for creating and managing a subsegment.

122

123

Args:

124

name (str): Subsegment name

125

**subsegment_kwargs: Additional subsegment parameters

126

127

Returns:

128

AsyncSubsegmentContextManager: Async context manager yielding the subsegment

129

130

Usage:

131

async with xray_recorder.in_subsegment_async('async-operation') as subsegment:

132

# Async operation here

133

"""

134

```

135

136

### Decorators

137

138

#### Function Tracing Decorators

139

140

Automatically trace function execution using decorators.

141

142

```python { .api }

143

def capture(name: str) -> Callable:

144

"""

145

Decorator for automatic function tracing in a subsegment.

146

147

Args:

148

name (str): Subsegment name for the traced function

149

150

Returns:

151

Callable: Decorated function

152

153

Usage:

154

@xray_recorder.capture('process-data')

155

def process_data(data):

156

return processed_data

157

"""

158

159

def capture_async(name: str) -> Callable:

160

"""

161

Decorator for automatic async function tracing in a subsegment.

162

163

Args:

164

name (str): Subsegment name for the traced async function

165

166

Returns:

167

Callable: Decorated async function

168

169

Usage:

170

@xray_recorder.capture_async('async-process')

171

async def async_process_data(data):

172

return await process_async(data)

173

"""

174

```

175

176

### Manual Segment Management

177

178

#### Segment Control

179

180

Manually create and manage segments for fine-grained control over trace lifecycle.

181

182

```python { .api }

183

def begin_segment(

184

name: str,

185

traceid: str = None,

186

parent_id: str = None,

187

sampling: int = None

188

) -> Segment:

189

"""

190

Begin a new segment.

191

192

Args:

193

name (str): Segment name

194

traceid (str): Optional trace ID (auto-generated if not provided)

195

parent_id (str): Optional parent segment ID

196

sampling (int): Sampling decision (1=sampled, 0=not sampled)

197

198

Returns:

199

Segment: The created segment

200

"""

201

202

def end_segment(end_time: float = None) -> None:

203

"""

204

End the current segment.

205

206

Args:

207

end_time (float): Optional end timestamp (defaults to current time)

208

"""

209

210

def current_segment() -> Segment:

211

"""

212

Get the current active segment.

213

214

Returns:

215

Segment: Current active segment

216

217

Raises:

218

SegmentNotFoundException: If no segment is active

219

"""

220

```

221

222

#### Subsegment Control

223

224

Manually create and manage subsegments within segments.

225

226

```python { .api }

227

def begin_subsegment(name: str, namespace: str = None) -> Subsegment:

228

"""

229

Begin a new subsegment under the current segment.

230

231

Args:

232

name (str): Subsegment name

233

namespace (str): Optional namespace for categorization

234

235

Returns:

236

Subsegment: The created subsegment

237

"""

238

239

def begin_subsegment_without_sampling(name: str) -> Subsegment:

240

"""

241

Begin a new unsampled subsegment under the current segment.

242

243

Args:

244

name (str): Subsegment name

245

246

Returns:

247

Subsegment: The created unsampled subsegment

248

"""

249

250

def end_subsegment(end_time: float = None) -> None:

251

"""

252

End the current subsegment.

253

254

Args:

255

end_time (float): Optional end timestamp (defaults to current time)

256

"""

257

258

def current_subsegment() -> Subsegment:

259

"""

260

Get the current active subsegment.

261

262

Returns:

263

Subsegment: Current active subsegment

264

265

Raises:

266

SegmentNotFoundException: If no subsegment is active

267

"""

268

```

269

270

### Trace Entity Management

271

272

Control the current trace context and entity hierarchy.

273

274

```python { .api }

275

def get_trace_entity() -> Union[Segment, Subsegment]:

276

"""

277

Get the current active trace entity (segment or subsegment).

278

279

Returns:

280

Union[Segment, Subsegment]: Current active trace entity

281

"""

282

283

def set_trace_entity(trace_entity: Union[Segment, Subsegment]) -> None:

284

"""

285

Set the current active trace entity.

286

287

Args:

288

trace_entity (Union[Segment, Subsegment]): Trace entity to set as active

289

"""

290

291

def clear_trace_entities() -> None:

292

"""

293

Clear all trace entities from the current context.

294

Useful for preventing thread pollution in multi-threaded applications.

295

"""

296

```

297

298

### Streaming Control

299

300

Manage subsegment streaming for large traces.

301

302

```python { .api }

303

def stream_subsegments() -> None:

304

"""

305

Stream closed subsegments to reduce memory usage.

306

Automatically called when streaming is enabled and thresholds are met.

307

"""

308

```

309

310

### Advanced Recording

311

312

Low-level recording functionality for custom integrations.

313

314

```python { .api }

315

def record_subsegment(

316

wrapped: Callable,

317

instance: object,

318

args: tuple,

319

kwargs: dict,

320

name: str,

321

namespace: str = None,

322

meta_processor: Callable = None

323

) -> Any:

324

"""

325

Record function execution in a subsegment with metadata processing.

326

327

Args:

328

wrapped (Callable): Function to wrap and trace

329

instance (object): Instance object for method calls

330

args (tuple): Function arguments

331

kwargs (dict): Function keyword arguments

332

name (str): Subsegment name

333

namespace (str): Optional namespace

334

meta_processor (Callable): Optional metadata processor function

335

336

Returns:

337

Any: Function result

338

"""

339

340

def record_subsegment_async(

341

wrapped: Callable,

342

instance: object,

343

args: tuple,

344

kwargs: dict,

345

name: str,

346

namespace: str = None,

347

meta_processor: Callable = None

348

) -> Any:

349

"""

350

Record async function execution in a subsegment with metadata processing.

351

352

Args:

353

wrapped (Callable): Async function to wrap and trace

354

instance (object): Instance object for method calls

355

args (tuple): Function arguments

356

kwargs (dict): Function keyword arguments

357

name (str): Subsegment name

358

namespace (str): Optional namespace

359

meta_processor (Callable): Optional metadata processor function

360

361

Returns:

362

Any: Function result

363

"""

364

```

365

366

## Usage Examples

367

368

### Basic Segment and Subsegment Usage

369

370

```python

371

from aws_xray_sdk.core import xray_recorder

372

373

# Configure the recorder

374

xray_recorder.configure(

375

sampling=False,

376

context_missing='LOG_ERROR'

377

)

378

379

# Using context managers

380

with xray_recorder.in_segment('web-request') as segment:

381

segment.put_annotation('user_id', '12345')

382

segment.put_metadata('request_info', {'method': 'GET', 'path': '/api/data'})

383

384

with xray_recorder.in_subsegment('database-query') as subsegment:

385

subsegment.put_annotation('table', 'users')

386

# Database query here

387

388

with xray_recorder.in_subsegment('external-api-call') as subsegment:

389

subsegment.put_annotation('service', 'payment-api')

390

# External API call here

391

```

392

393

### Async Usage

394

395

```python

396

import asyncio

397

from aws_xray_sdk.core import xray_recorder

398

399

async def async_operation():

400

async with xray_recorder.in_segment_async('async-request') as segment:

401

segment.put_annotation('operation', 'data-processing')

402

403

async with xray_recorder.in_subsegment_async('async-db-query') as subsegment:

404

# Async database operation

405

await asyncio.sleep(0.1) # Simulate async work

406

407

async with xray_recorder.in_subsegment_async('async-computation') as subsegment:

408

# Async computation

409

await asyncio.sleep(0.2) # Simulate async work

410

```

411

412

### Decorator Usage

413

414

```python

415

from aws_xray_sdk.core import xray_recorder

416

417

@xray_recorder.capture('data-processing')

418

def process_user_data(user_id, data):

419

# Add annotations within the traced function

420

xray_recorder.put_annotation('user_id', user_id)

421

xray_recorder.put_metadata('data_size', len(data))

422

423

# Process data

424

return processed_data

425

426

@xray_recorder.capture_async('async-data-processing')

427

async def async_process_user_data(user_id, data):

428

# Async processing with automatic tracing

429

xray_recorder.put_annotation('user_id', user_id)

430

result = await process_async(data)

431

return result

432

```

433

434

### Manual Management

435

436

```python

437

from aws_xray_sdk.core import xray_recorder

438

439

# Manual segment management

440

segment = xray_recorder.begin_segment('manual-segment')

441

segment.put_annotation('type', 'manual')

442

443

try:

444

# Start subsegment

445

subsegment = xray_recorder.begin_subsegment('manual-subsegment')

446

subsegment.put_metadata('operation', 'manual-process')

447

448

# Your traced code here

449

result = perform_operation()

450

451

except Exception as e:

452

# Exception will be automatically captured

453

raise

454

finally:

455

# Clean up

456

xray_recorder.end_subsegment()

457

xray_recorder.end_segment()

458

```

459

460

### Thread Management

461

462

```python

463

import concurrent.futures

464

from aws_xray_sdk.core import xray_recorder

465

466

def worker_function(data, trace_entity):

467

# Set the trace entity for the worker thread

468

xray_recorder.set_trace_entity(trace_entity)

469

470

try:

471

with xray_recorder.in_subsegment('worker-operation') as subsegment:

472

# Process data in worker thread

473

result = process_data(data)

474

return result

475

finally:

476

# Prevent thread pollution

477

xray_recorder.clear_trace_entities()

478

479

# Main thread

480

with xray_recorder.in_segment('threaded-operation') as segment:

481

current_entity = xray_recorder.get_trace_entity()

482

483

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:

484

futures = [

485

executor.submit(worker_function, data, current_entity)

486

for data in data_list

487

]

488

489

results = [future.result() for future in futures]

490

```