0
# ddtrace
1
2
Datadog's APM (Application Performance Monitoring) client library for Python provides comprehensive distributed tracing, continuous profiling, error tracking, test optimization, deployment tracking, code hotspots analysis, and dynamic instrumentation. It enables deep insights into application behavior and performance bottlenecks through automatic instrumentation of popular Python frameworks and libraries, sophisticated monkey-patching system, comprehensive telemetry collection with built-in context propagation and span management, and advanced profiling capabilities including memory allocation tracking and stack sampling.
3
4
## Package Information
5
6
- **Package Name**: ddtrace
7
- **Language**: Python
8
- **Installation**: `pip install ddtrace`
9
10
## Core Imports
11
12
```python
13
import ddtrace
14
```
15
16
Common imports for tracing:
17
18
```python
19
from ddtrace import tracer
20
from ddtrace import patch, patch_all, config
21
```
22
23
For profiling:
24
25
```python
26
from ddtrace.profiling import Profiler
27
```
28
29
For OpenTelemetry compatibility:
30
31
```python
32
from ddtrace.opentelemetry import TracerProvider
33
```
34
35
## Basic Usage
36
37
```python
38
import ddtrace
39
from ddtrace import tracer, patch
40
41
# Configure basic settings
42
ddtrace.config.service = "my-python-app"
43
ddtrace.config.env = "production"
44
ddtrace.config.version = "1.0.0"
45
46
# Manual instrumentation for specific libraries
47
patch(redis=True, psycopg=True, requests=True)
48
49
# Create custom spans
50
with tracer.trace("custom-operation") as span:
51
span.set_tag("user.id", "12345")
52
span.set_tag("operation.type", "data-processing")
53
# Your application logic here
54
result = process_data()
55
span.set_tag("result.count", len(result))
56
57
# Manual span creation without context manager
58
span = tracer.trace("background-task")
59
span.set_tag("task.type", "cleanup")
60
try:
61
cleanup_operation()
62
span.set_tag("status", "success")
63
except Exception as e:
64
span.set_error(e)
65
span.set_tag("status", "error")
66
finally:
67
span.finish()
68
```
69
70
## Architecture
71
72
ddtrace uses a modular architecture with several key components:
73
74
- **Tracer**: Central coordinator for span creation, context management, and trace submission
75
- **Spans**: Individual units of work with timing, metadata, and parent-child relationships
76
- **Context**: Thread-local storage for active span state and trace propagation
77
- **Patches**: Monkey-patching system for automatic instrumentation of third-party libraries
78
- **Writers**: Backend communication layer for submitting traces to Datadog Agent
79
- **Processors**: Middleware for span enrichment, filtering, and transformation
80
- **Profiler**: Continuous profiling engine for CPU, memory, and lock contention analysis
81
82
The library integrates seamlessly with 80+ popular Python libraries through automatic instrumentation while providing manual instrumentation APIs for custom applications.
83
84
## Capabilities
85
86
### Core Tracing
87
88
Fundamental distributed tracing functionality including span creation, context management, trace filtering, and integration configuration. Provides the essential building blocks for observability.
89
90
```python { .api }
91
class Tracer:
92
def trace(self, name: str, service: str = None, resource: str = None, span_type: str = None) -> Span: ...
93
def wrap(self, name: str = None, service: str = None, resource: str = None, span_type: str = None): ...
94
95
def patch(**patch_modules: bool) -> None: ...
96
def patch_all(**patch_modules: bool) -> None: ... # DEPRECATED: Use DD_PATCH_MODULES environment variable instead
97
98
tracer: Tracer
99
config: Config
100
```
101
102
[Core Tracing](./core-tracing.md)
103
104
### Profiling
105
106
Continuous profiling capabilities for CPU usage, memory allocation, lock contention, and wall time analysis. Enables identification of performance bottlenecks and resource consumption patterns.
107
108
```python { .api }
109
class Profiler:
110
def __init__(self, service: str = None, env: str = None, version: str = None, tags: Dict[str, str] = None): ...
111
def start(self, stop_on_exit: bool = True, profile_children: bool = True) -> None: ...
112
def stop(self, flush: bool = True) -> None: ...
113
```
114
115
[Profiling](./profiling.md)
116
117
### Application Security
118
119
Application security monitoring including Interactive Application Security Testing (IAST), runtime security monitoring, and AI/LLM security features for threat detection and vulnerability identification.
120
121
```python { .api }
122
# Configuration constants
123
APPSEC_ENV: str # "DD_APPSEC_ENABLED"
124
IAST_ENV: str # "DD_IAST_ENABLED"
125
```
126
127
[Application Security](./application-security.md)
128
129
### Automatic Instrumentation
130
131
Comprehensive automatic instrumentation for web frameworks, databases, HTTP clients, message queues, AI/ML libraries, and other popular Python packages through monkey-patching.
132
133
```python { .api }
134
def patch(
135
django: bool = None,
136
flask: bool = None,
137
fastapi: bool = None,
138
psycopg: bool = None,
139
redis: bool = None,
140
requests: bool = None,
141
openai: bool = None,
142
# ... 80+ more integrations
143
raise_errors: bool = True,
144
**kwargs
145
) -> None: ...
146
```
147
148
[Automatic Instrumentation](./automatic-instrumentation.md)
149
150
### OpenTelemetry Integration
151
152
OpenTelemetry API compatibility layer enabling interoperability between ddtrace and OpenTelemetry instrumentation while maintaining Datadog-specific features and optimizations.
153
154
```python { .api }
155
class TracerProvider:
156
def get_tracer(
157
self,
158
instrumenting_module_name: str,
159
instrumenting_library_version: str = None,
160
schema_url: str = None
161
) -> Tracer: ...
162
```
163
164
[OpenTelemetry Integration](./opentelemetry-integration.md)
165
166
### Configuration and Settings
167
168
Comprehensive configuration system for service identification, sampling, trace filtering, integration settings, and environment-specific customization through environment variables and programmatic APIs.
169
170
```python { .api }
171
class Config:
172
service: str
173
env: str
174
version: str
175
tags: Dict[str, str]
176
trace_enabled: bool
177
analytics_enabled: bool
178
priority_sampling: bool
179
180
config: Config
181
```
182
183
[Configuration and Settings](./configuration-settings.md)
184
185
## Constants
186
187
```python { .api }
188
# Tag keys
189
ENV_KEY: str = "env"
190
VERSION_KEY: str = "version"
191
SERVICE_KEY: str = "service.name"
192
SERVICE_VERSION_KEY: str = "service.version"
193
SPAN_KIND: str = "span.kind"
194
195
# Error tags
196
ERROR_MSG: str = "error.message"
197
ERROR_TYPE: str = "error.type"
198
ERROR_STACK: str = "error.stack"
199
200
# Sampling decisions
201
USER_REJECT: int = -1
202
AUTO_REJECT: int = 0
203
AUTO_KEEP: int = 1
204
USER_KEEP: int = 2
205
206
# Manual sampling
207
MANUAL_DROP_KEY: str = "manual.drop"
208
MANUAL_KEEP_KEY: str = "manual.keep"
209
210
# Environment variables
211
APPSEC_ENV: str = "DD_APPSEC_ENABLED"
212
IAST_ENV: str = "DD_IAST_ENABLED"
213
214
# Process identification
215
PID: str = "process_id"
216
```
217
218
## Types
219
220
```python { .api }
221
class Span:
222
def set_tag(self, key: str, value: str) -> None: ...
223
def set_error(self, error: Exception, traceback: str = None) -> None: ...
224
def finish(self, finish_time: float = None) -> None: ...
225
def set_metric(self, key: str, value: float) -> None: ...
226
227
class Context:
228
def clone(self) -> 'Context': ...
229
230
class Pin:
231
def __init__(self, service: str = None, app: str = None, tags: Dict[str, str] = None, tracer: Tracer = None): ...
232
def onto(self, obj: object) -> Pin: ...
233
def get_from(self, obj: object) -> Pin: ...
234
235
class TraceFilter:
236
def process_trace(self, trace: List[Span]) -> List[Span]: ...
237
238
class BaseContextProvider:
239
def activate(self, span: Span) -> object: ...
240
def active(self) -> Span: ...
241
```