0
# Configuration and Settings
1
2
Comprehensive configuration system for service identification, sampling, trace filtering, integration settings, and environment-specific customization through environment variables and programmatic APIs. This enables fine-tuned control over tracing behavior, performance optimization, and operational requirements.
3
4
## Capabilities
5
6
### Global Configuration
7
8
The main configuration object provides centralized control over ddtrace behavior and settings.
9
10
```python { .api }
11
class Config:
12
# Service identification
13
service: str # Service name
14
env: str # Environment (prod, staging, dev)
15
version: str # Application version
16
tags: Dict[str, str] # Global tags applied to all spans
17
18
# Tracing behavior
19
trace_enabled: bool # Enable/disable tracing
20
analytics_enabled: bool # Enable trace analytics
21
priority_sampling: bool # Use priority sampling
22
23
# Performance settings
24
trace_sample_rate: float # Global sampling rate (0.0-1.0)
25
trace_rate_limit: int # Traces per second rate limit
26
27
# Backend configuration
28
agent_hostname: str # Datadog Agent hostname
29
agent_port: int # Datadog Agent port
30
agent_url: str # Full Agent URL
31
32
# Integration settings
33
service_mapping: Dict[str, str] # Map integration names to service names
34
35
# Advanced options
36
report_hostname: bool # Include hostname in traces
37
health_metrics_enabled: bool # Enable health metrics
38
runtime_metrics_enabled: bool # Enable runtime metrics
39
40
config: Config # Global configuration object
41
```
42
43
Usage examples:
44
45
```python
46
from ddtrace import config
47
48
# Basic service configuration
49
config.service = "my-python-app"
50
config.env = "production"
51
config.version = "2.1.0"
52
53
# Global tags applied to all spans
54
config.tags = {
55
"team": "backend",
56
"region": "us-east-1",
57
"datacenter": "aws-east"
58
}
59
60
# Sampling configuration
61
config.trace_sample_rate = 0.1 # Sample 10% of traces
62
config.priority_sampling = True # Use intelligent sampling
63
64
# Agent configuration
65
config.agent_hostname = "datadog-agent.internal"
66
config.agent_port = 8126
67
68
# Service name mapping for integrations
69
config.service_mapping = {
70
"psycopg": "postgres-primary",
71
"redis": "redis-cache",
72
"requests": "external-apis"
73
}
74
```
75
76
### Environment Variable Configuration
77
78
Configure ddtrace through environment variables for deployment flexibility and containerized environments.
79
80
```python
81
import os
82
83
# Service identification
84
os.environ["DD_SERVICE"] = "my-python-app"
85
os.environ["DD_ENV"] = "production"
86
os.environ["DD_VERSION"] = "2.1.0"
87
88
# Global tags (comma-separated key:value pairs)
89
os.environ["DD_TAGS"] = "team:backend,region:us-east-1,cost-center:engineering"
90
91
# Tracing configuration
92
os.environ["DD_TRACE_ENABLED"] = "true"
93
os.environ["DD_TRACE_SAMPLE_RATE"] = "0.1" # 10% sampling
94
os.environ["DD_TRACE_RATE_LIMIT"] = "100" # Max 100 traces/second
95
96
# Agent configuration
97
os.environ["DD_AGENT_HOST"] = "datadog-agent"
98
os.environ["DD_TRACE_AGENT_PORT"] = "8126"
99
os.environ["DD_TRACE_AGENT_URL"] = "http://datadog-agent:8126"
100
101
# Integration configuration
102
os.environ["DD_SERVICE_MAPPING"] = "psycopg:postgres,redis:cache"
103
104
# Feature flags
105
os.environ["DD_TRACE_ANALYTICS_ENABLED"] = "true"
106
os.environ["DD_RUNTIME_METRICS_ENABLED"] = "true"
107
os.environ["DD_PROFILING_ENABLED"] = "true"
108
109
# Import ddtrace to apply environment configuration
110
import ddtrace
111
```
112
113
### Per-Integration Configuration
114
115
Fine-tune settings for specific integrations and libraries.
116
117
```python
118
from ddtrace import config
119
120
# Django configuration
121
config.django.service_name = "web-frontend"
122
config.django.cache_service_name = "django-cache"
123
config.django.database_service_name = "django-db"
124
config.django.distributed_tracing_enabled = True
125
config.django.analytics_enabled = True
126
config.django.analytics_sample_rate = 1.0
127
128
# Flask configuration
129
config.flask.service_name = "api-backend"
130
config.flask.analytics_enabled = True
131
config.flask.template_name_as_resource = True
132
config.flask.trace_query_string = True
133
134
# Database configurations
135
config.psycopg.service_name = "postgres-primary"
136
config.psycopg.analytics_enabled = True
137
138
config.redis.service_name = "redis-cache"
139
config.redis.analytics_enabled = False # High volume, disable analytics
140
141
config.requests.service_name = "external-apis"
142
config.requests.analytics_enabled = True
143
config.requests.analytics_sample_rate = 0.5 # Sample 50% of HTTP requests
144
145
# AI/ML integrations
146
config.openai.service_name = "openai-integration"
147
config.openai.analytics_enabled = True
148
config.openai.log_prompt_completion_sample_rate = 0.1 # Log 10% of completions
149
150
config.langchain.service_name = "langchain-workflows"
151
config.langchain.analytics_enabled = True
152
```
153
154
### Sampling Configuration
155
156
Control which traces are collected and submitted to optimize performance and costs.
157
158
```python
159
from ddtrace import config
160
161
# Global sampling rate (applies to all traces)
162
config.trace_sample_rate = 0.1 # Sample 10% of traces
163
164
# Priority sampling (intelligent sampling based on trace characteristics)
165
config.priority_sampling = True
166
167
# Rate limiting (maximum traces per second)
168
config.trace_rate_limit = 100
169
170
# Analytics sampling (for APM analytics features)
171
config.analytics_enabled = True
172
173
# Per-integration analytics sampling
174
config.django.analytics_sample_rate = 1.0 # 100% for web requests
175
config.psycopg.analytics_sample_rate = 0.1 # 10% for database queries
176
config.requests.analytics_sample_rate = 0.5 # 50% for external HTTP calls
177
178
# Environment-based sampling
179
if config.env == "production":
180
config.trace_sample_rate = 0.05 # Lower sampling in production
181
elif config.env == "staging":
182
config.trace_sample_rate = 0.25 # Medium sampling in staging
183
else:
184
config.trace_sample_rate = 1.0 # Full sampling in development
185
```
186
187
### Advanced Configuration Options
188
189
#### Writer and Backend Configuration
190
191
```python
192
from ddtrace import config
193
194
# Agent writer configuration
195
config._trace_writer_buffer_size = 1000 # Buffer size for trace batching
196
config._trace_writer_interval_seconds = 1 # Flush interval
197
config._trace_writer_connection_timeout = 2.0 # Connection timeout
198
config._trace_writer_max_payload_size = 8 << 20 # 8MB max payload
199
200
# Alternative: API key-based submission (bypassing agent)
201
config._dd_api_key = "your-datadog-api-key"
202
config._trace_writer_hostname = "intake.datadoghq.com"
203
config._trace_writer_port = 443
204
```
205
206
#### Debug and Development Configuration
207
208
```python
209
from ddtrace import config
210
211
# Debug mode for development
212
config._debug_mode = True # Enable debug logging
213
config._startup_logs_enabled = True # Log startup information
214
215
# Health check endpoint
216
config._health_metrics_enabled = True
217
218
# Detailed error reporting
219
config._raise_on_error = True # Raise exceptions instead of logging
220
221
# Trace filtering for debugging
222
config._trace_remove_integration_service_names_enabled = False
223
```
224
225
#### Security and Privacy Configuration
226
227
```python
228
from ddtrace import config
229
230
# Obfuscate sensitive data
231
config._obfuscation_query_string_pattern = r"password|token|secret"
232
config._trace_query_string_obfuscation_disabled = False
233
234
# HTTP header filtering
235
config._trace_header_tags = {
236
"user-agent": "http.user_agent",
237
"content-type": "http.content_type"
238
}
239
240
# Remove PII from traces
241
config._trace_remove_integration_service_names_enabled = True
242
```
243
244
### Runtime Configuration Changes
245
246
Modify configuration during application runtime for dynamic behavior adjustment.
247
248
```python
249
from ddtrace import config, tracer
250
251
def configure_for_high_traffic():
252
"""Reduce sampling during high traffic periods"""
253
config.trace_sample_rate = 0.01 # 1% sampling
254
config.trace_rate_limit = 50 # Lower rate limit
255
config.analytics_enabled = False # Disable analytics
256
257
def configure_for_debugging():
258
"""Increase observability for debugging"""
259
config.trace_sample_rate = 1.0 # 100% sampling
260
config.analytics_enabled = True # Enable analytics
261
config._debug_mode = True # Enable debug logging
262
263
# Dynamic configuration based on conditions
264
if is_high_traffic_period():
265
configure_for_high_traffic()
266
elif is_debugging_session():
267
configure_for_debugging()
268
269
# Runtime service mapping updates
270
config.service_mapping["new-integration"] = "new-service-name"
271
```
272
273
### Configuration Validation and Diagnostics
274
275
```python
276
from ddtrace import config
277
from ddtrace.internal.diagnostics import health
278
279
# Validate configuration
280
def validate_config():
281
"""Validate current ddtrace configuration"""
282
issues = []
283
284
if not config.service:
285
issues.append("Service name not set")
286
287
if not config.env:
288
issues.append("Environment not set")
289
290
if config.trace_sample_rate < 0 or config.trace_sample_rate > 1:
291
issues.append("Invalid sample rate")
292
293
if config.trace_rate_limit <= 0:
294
issues.append("Invalid rate limit")
295
296
return issues
297
298
# Health check
299
def check_agent_connectivity():
300
"""Check if Datadog Agent is reachable"""
301
return health.agent_health_check()
302
303
# Diagnostic information
304
def get_diagnostic_info():
305
"""Get current configuration and health status"""
306
return {
307
"service": config.service,
308
"env": config.env,
309
"version": config.version,
310
"sampling_rate": config.trace_sample_rate,
311
"agent_reachable": check_agent_connectivity(),
312
"config_issues": validate_config()
313
}
314
315
# Usage
316
diagnostics = get_diagnostic_info()
317
print(f"Service: {diagnostics['service']}")
318
print(f"Environment: {diagnostics['env']}")
319
print(f"Agent reachable: {diagnostics['agent_reachable']}")
320
```
321
322
### Container and Kubernetes Configuration
323
324
Optimize ddtrace configuration for containerized environments.
325
326
```python
327
import os
328
329
# Kubernetes service discovery
330
os.environ["DD_AGENT_HOST"] = os.environ.get("DD_AGENT_SERVICE_HOST", "datadog-agent")
331
os.environ["DD_TRACE_AGENT_PORT"] = os.environ.get("DD_AGENT_SERVICE_PORT", "8126")
332
333
# Container-specific tags
334
os.environ["DD_TAGS"] = f"pod_name:{os.environ.get('HOSTNAME', 'unknown')}"
335
336
# Resource-aware configuration
337
cpu_limit = float(os.environ.get("CPU_LIMIT", "1.0"))
338
memory_limit = int(os.environ.get("MEMORY_LIMIT", "512")) * 1024 * 1024 # Convert MB to bytes
339
340
# Adjust sampling based on resources
341
if cpu_limit < 0.5:
342
os.environ["DD_TRACE_SAMPLE_RATE"] = "0.05" # Low sampling for resource-constrained containers
343
elif cpu_limit >= 2.0:
344
os.environ["DD_TRACE_SAMPLE_RATE"] = "0.2" # Higher sampling for powerful containers
345
```
346
347
### Configuration Best Practices
348
349
#### Production Configuration
350
351
```python
352
from ddtrace import config
353
354
# Production-optimized settings
355
config.service = "production-api"
356
config.env = "production"
357
config.version = get_application_version()
358
359
# Performance optimization
360
config.trace_sample_rate = 0.05 # 5% sampling for high-volume production
361
config.trace_rate_limit = 200 # Reasonable rate limit
362
config.priority_sampling = True # Use intelligent sampling
363
config.analytics_enabled = False # Disable if not needed for performance
364
365
# Reliability settings
366
config._trace_writer_buffer_size = 1000
367
config._trace_writer_interval_seconds = 2
368
config.health_metrics_enabled = True
369
370
# Security
371
config._obfuscation_query_string_pattern = r"password|token|secret|key"
372
```
373
374
#### Development Configuration
375
376
```python
377
from ddtrace import config
378
379
# Development-friendly settings
380
config.service = "dev-api"
381
config.env = "development"
382
config.version = "dev"
383
384
# Full observability
385
config.trace_sample_rate = 1.0 # 100% sampling for debugging
386
config.analytics_enabled = True # Enable analytics
387
config._debug_mode = True # Enable debug logging
388
config._startup_logs_enabled = True
389
390
# Fast feedback
391
config._trace_writer_interval_seconds = 0.5 # Faster flush for immediate feedback
392
```
393
394
#### Staging Configuration
395
396
```python
397
from ddtrace import config
398
399
# Staging environment (production-like with more observability)
400
config.service = "staging-api"
401
config.env = "staging"
402
config.version = get_staging_version()
403
404
# Balanced sampling
405
config.trace_sample_rate = 0.25 # 25% sampling
406
config.analytics_enabled = True # Enable analytics for testing
407
config.priority_sampling = True # Test priority sampling behavior
408
409
# Monitoring
410
config.health_metrics_enabled = True
411
config.runtime_metrics_enabled = True
412
```
413
414
## Environment Variables Reference
415
416
Complete list of key ddtrace environment variables:
417
418
### Core Configuration
419
- `DD_SERVICE` - Service name
420
- `DD_ENV` - Environment name
421
- `DD_VERSION` - Application version
422
- `DD_TAGS` - Global tags (comma-separated key:value pairs)
423
424
### Tracing
425
- `DD_TRACE_ENABLED` - Enable/disable tracing
426
- `DD_TRACE_SAMPLE_RATE` - Global sampling rate (0.0-1.0)
427
- `DD_TRACE_RATE_LIMIT` - Traces per second limit
428
- `DD_TRACE_ANALYTICS_ENABLED` - Enable trace analytics
429
430
### Agent
431
- `DD_AGENT_HOST` - Agent hostname
432
- `DD_TRACE_AGENT_PORT` - Agent port
433
- `DD_TRACE_AGENT_URL` - Full agent URL
434
435
### Features
436
- `DD_PROFILING_ENABLED` - Enable continuous profiling
437
- `DD_APPSEC_ENABLED` - Enable application security
438
- `DD_RUNTIME_METRICS_ENABLED` - Enable runtime metrics
439
440
### Integrations
441
- `DD_SERVICE_MAPPING` - Service name mapping
442
- `DD_PATCH_MODULES` - Module patching configuration