or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-security.mdautomatic-instrumentation.mdconfiguration-settings.mdcore-tracing.mdindex.mdopentelemetry-integration.mdprofiling.md

core-tracing.mddocs/

0

# Core Tracing

1

2

The core tracing functionality provides the fundamental building blocks for distributed tracing in ddtrace. This includes span creation, context management, trace filtering, and integration configuration that forms the foundation of all observability features.

3

4

## Capabilities

5

6

### Tracer Operations

7

8

The main Tracer class provides the primary interface for creating spans and managing trace state. It handles span lifecycle, context propagation, and trace submission to the Datadog backend.

9

10

```python { .api }

11

class Tracer:

12

def trace(

13

self,

14

name: str,

15

service: str = None,

16

resource: str = None,

17

span_type: str = None

18

) -> Span:

19

"""

20

Create a new span and return it as a context manager.

21

22

Parameters:

23

- name: The span name/operation name

24

- service: Service name override (defaults to global service)

25

- resource: Resource being operated on (e.g., SQL query, HTTP endpoint)

26

- span_type: Type of span (web, db, cache, custom, etc.)

27

28

Returns:

29

Span object that can be used as a context manager

30

"""

31

32

def wrap(

33

self,

34

name: str = None,

35

service: str = None,

36

resource: str = None,

37

span_type: str = None

38

):

39

"""

40

Decorator for wrapping functions with tracing.

41

42

Parameters:

43

- name: Span name (defaults to function name)

44

- service: Service name override

45

- resource: Resource name

46

- span_type: Type of span

47

48

Returns:

49

Decorator function

50

"""

51

```

52

53

Usage examples:

54

55

```python

56

from ddtrace import tracer

57

58

# Context manager usage (recommended)

59

with tracer.trace("database-query") as span:

60

span.set_tag("db.statement", "SELECT * FROM users")

61

span.set_tag("db.type", "postgresql")

62

result = execute_query()

63

span.set_tag("db.rows", len(result))

64

65

# Manual span management

66

span = tracer.start_span("background-task")

67

try:

68

span.set_tag("task.type", "data-processing")

69

process_data()

70

except Exception as e:

71

span.set_error(e)

72

finally:

73

span.finish()

74

75

# Decorator usage

76

@tracer.wrap("user-validation", service="auth-service")

77

def validate_user(user_id):

78

return check_user_permissions(user_id)

79

```

80

81

### Span Operations

82

83

Individual spans represent units of work in a distributed trace. They capture timing information, metadata through tags, and error states.

84

85

```python { .api }

86

class Span:

87

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

88

"""

89

Set a tag on the span.

90

91

Parameters:

92

- key: Tag key

93

- value: Tag value (will be converted to string)

94

"""

95

96

def set_tags(self, tags: Dict[str, str]) -> None:

97

"""

98

Set multiple tags at once.

99

100

Parameters:

101

- tags: Dictionary of key-value pairs

102

"""

103

104

def set_metric(self, key: str, value: float) -> None:

105

"""

106

Set a numeric metric on the span.

107

108

Parameters:

109

- key: Metric key

110

- value: Numeric value

111

"""

112

113

def set_error(self, error: Exception = None, traceback: str = None) -> None:

114

"""

115

Mark the span as having an error.

116

117

Parameters:

118

- error: Exception object (optional)

119

- traceback: Custom traceback string (optional)

120

"""

121

122

def finish(self, finish_time: float = None) -> None:

123

"""

124

Finish the span and record its completion time.

125

126

Parameters:

127

- finish_time: Custom finish time (defaults to current time)

128

"""

129

130

@property

131

def trace_id(self) -> int:

132

"""Get the trace ID."""

133

134

@property

135

def span_id(self) -> int:

136

"""Get the span ID."""

137

138

@property

139

def parent_id(self) -> int:

140

"""Get the parent span ID."""

141

```

142

143

### Context Management

144

145

Context objects manage the active span state and enable trace propagation across execution contexts.

146

147

```python { .api }

148

class Context:

149

def clone(self) -> 'Context':

150

"""

151

Create a copy of the context.

152

153

Returns:

154

New Context object with the same state

155

"""

156

157

@property

158

def trace_id(self) -> int:

159

"""Get the trace ID from context."""

160

161

@property

162

def span_id(self) -> int:

163

"""Get the current span ID from context."""

164

```

165

166

### Pin Configuration

167

168

Pin objects provide a way to configure tracing behavior for specific objects or modules, commonly used in automatic instrumentation.

169

170

```python { .api }

171

class Pin:

172

def __init__(

173

self,

174

service: str = None,

175

app: str = None,

176

tags: Dict[str, str] = None,

177

tracer: Tracer = None

178

):

179

"""

180

Create a Pin configuration object.

181

182

Parameters:

183

- service: Service name

184

- app: Application name

185

- tags: Default tags to apply

186

- tracer: Tracer instance to use

187

"""

188

189

def onto(self, obj: object) -> 'Pin':

190

"""

191

Attach this Pin to an object.

192

193

Parameters:

194

- obj: Object to attach Pin to

195

196

Returns:

197

The Pin instance for chaining

198

"""

199

200

@classmethod

201

def get_from(cls, obj: object) -> 'Pin':

202

"""

203

Get Pin configuration from an object.

204

205

Parameters:

206

- obj: Object to get Pin from

207

208

Returns:

209

Pin object or None if not found

210

"""

211

212

def clone(self, **kwargs) -> 'Pin':

213

"""

214

Create a copy of this Pin with optional overrides.

215

216

Parameters:

217

- **kwargs: Attributes to override

218

219

Returns:

220

New Pin object

221

"""

222

```

223

224

### Trace Filtering

225

226

TraceFilter enables custom filtering and modification of complete traces before they are submitted.

227

228

```python { .api }

229

class TraceFilter:

230

def process_trace(self, trace: List[Span]) -> List[Span]:

231

"""

232

Process a complete trace and return the filtered trace.

233

234

Parameters:

235

- trace: List of spans in the trace

236

237

Returns:

238

List of spans (potentially modified or filtered)

239

"""

240

```

241

242

### Context Providers

243

244

Context providers manage span activation and storage across different execution contexts (threads, async tasks, etc.).

245

246

```python { .api }

247

class BaseContextProvider:

248

def activate(self, span: Span) -> object:

249

"""

250

Activate a span in the current context.

251

252

Parameters:

253

- span: Span to activate

254

255

Returns:

256

Token or context object for deactivation

257

"""

258

259

def active(self) -> Span:

260

"""

261

Get the currently active span.

262

263

Returns:

264

Active Span or None

265

"""

266

```

267

268

### Global Tracer Instance

269

270

ddtrace provides a global tracer instance that is automatically configured and ready to use.

271

272

```python { .api }

273

tracer: Tracer # Global tracer instance

274

```

275

276

Usage:

277

278

```python

279

from ddtrace import tracer

280

281

# Use the global tracer directly

282

with tracer.trace("operation") as span:

283

span.set_tag("component", "business-logic")

284

do_work()

285

```

286

287

### Manual Instrumentation Helpers

288

289

Helper functions for manually instrumenting specific libraries or code sections.

290

291

```python { .api }

292

def patch(**patch_modules: bool) -> None:

293

"""

294

Manually patch specific modules for automatic instrumentation.

295

296

Parameters:

297

- **patch_modules: Boolean flags for each module to patch

298

- raise_errors: Whether to raise errors if patching fails (default: True)

299

300

Example:

301

patch(redis=True, psycopg=True, requests=False)

302

"""

303

304

def patch_all(**patch_modules: bool) -> None:

305

"""

306

Automatically patch all supported modules (deprecated).

307

308

Parameters:

309

- **patch_modules: Override flags for specific modules

310

311

Note: This function is deprecated in favor of patch() and DD_PATCH_MODULES

312

"""

313

```

314

315

## Error Handling

316

317

Spans can capture error information automatically or manually:

318

319

```python

320

# Automatic error capture with context manager

321

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

322

span.set_tag("operation.type", "file-processing")

323

# If this raises an exception, it's automatically captured

324

process_file(filename)

325

326

# Manual error capture

327

span = tracer.start_span("custom-operation")

328

try:

329

risky_operation()

330

except ValueError as e:

331

span.set_error(e) # Captures exception details

332

span.set_tag("error.handled", "true")

333

handle_error(e)

334

except Exception as e:

335

span.set_error(e)

336

span.set_tag("error.handled", "false")

337

raise

338

finally:

339

span.finish()

340

```

341

342

## Advanced Usage

343

344

### Custom Service Configuration

345

346

```python

347

from ddtrace import tracer

348

349

# Configure service information

350

tracer.set_service_info(

351

service="payment-processor",

352

app="ecommerce-backend",

353

app_type="web"

354

)

355

356

# Per-span service override

357

with tracer.trace("external-api-call", service="third-party-service") as span:

358

response = call_external_api()

359

span.set_tag("http.status_code", response.status_code)

360

```

361

362

### Complex Trace Relationships

363

364

```python

365

# Create parent span

366

with tracer.trace("batch-processing") as parent_span:

367

parent_span.set_tag("batch.size", len(items))

368

369

for i, item in enumerate(items):

370

# Child spans inherit context automatically

371

with tracer.trace("process-item") as child_span:

372

child_span.set_tag("item.id", item.id)

373

child_span.set_tag("item.index", i)

374

process_single_item(item)

375

376

parent_span.set_tag("batch.status", "completed")

377

```