or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-line-tools.mdconfiguration.mddogstatsd-client.mderror-handling.mdhttp-api-client.mdindex.mdthreadstats.md

configuration.mddocs/

0

# Configuration

1

2

Core initialization and configuration system for setting up API authentication, StatsD connection parameters, and global library behavior. Provides centralized configuration management for all Datadog Python library components.

3

4

## Capabilities

5

6

### Library Initialization

7

8

Configure all Datadog library components with a single initialization call, setting up API credentials, connection parameters, and behavioral options.

9

10

```python { .api }

11

def initialize(

12

api_key=None,

13

app_key=None,

14

host_name=None,

15

api_host=None,

16

statsd_host=None,

17

statsd_port=None,

18

statsd_disable_aggregation=True,

19

statsd_disable_buffering=True,

20

statsd_aggregation_flush_interval=0.3,

21

statsd_use_default_route=False,

22

statsd_socket_path=None,

23

statsd_namespace=None,

24

statsd_max_samples_per_context=0,

25

statsd_constant_tags=None,

26

return_raw_response=False,

27

hostname_from_config=True,

28

cardinality=None,

29

**kwargs

30

):

31

"""

32

Initialize and configure Datadog API and StatsD modules.

33

34

Parameters:

35

- api_key (str): Datadog API key for authentication

36

- app_key (str): Datadog application key for API access

37

- host_name (str): Override hostname for metrics and events

38

- api_host (str): Datadog API endpoint URL (default: https://api.datadoghq.com)

39

- statsd_host (str): DogStatsD server hostname (default: localhost)

40

- statsd_port (int): DogStatsD server port (default: 8125)

41

- statsd_disable_aggregation (bool): Disable client-side aggregation

42

- statsd_disable_buffering (bool): Disable metric buffering

43

- statsd_aggregation_flush_interval (float): Aggregation flush interval in seconds

44

- statsd_use_default_route (bool): Auto-detect StatsD host from default route

45

- statsd_socket_path (str): Unix Domain Socket path (overrides host/port)

46

- statsd_namespace (str): Prefix for all metric names

47

- statsd_max_samples_per_context (int): Max samples per metric context

48

- statsd_constant_tags (list): Tags applied to all metrics

49

- return_raw_response (bool): Return raw HTTP response objects

50

- hostname_from_config (bool): Get hostname from Datadog agent config

51

- cardinality (str): Global cardinality level ('none', 'low', 'orchestrator', 'high')

52

- **kwargs: Additional HTTP client configuration options

53

"""

54

```

55

56

### Environment Variable Configuration

57

58

Automatic configuration from environment variables with precedence over explicit parameters.

59

60

```python { .api }

61

# Environment variables (in order of precedence):

62

# API Authentication:

63

# DATADOG_API_KEY or DD_API_KEY

64

# DATADOG_APP_KEY or DD_APP_KEY

65

66

# API Host:

67

# DATADOG_HOST (default: https://api.datadoghq.com)

68

69

# Cardinality:

70

# DATADOG_CARDINALITY or DD_CARDINALITY

71

72

# StatsD Configuration:

73

# DD_STATSD_HOST

74

# DD_STATSD_PORT

75

# DD_STATSD_SOCKET_PATH

76

```

77

78

### HTTP Client Configuration

79

80

Advanced HTTP client settings for connection management, timeouts, retries, and proxy configuration.

81

82

```python { .api }

83

# HTTP Configuration Options (passed via **kwargs to initialize()):

84

85

# Connection Settings:

86

# - proxies (dict): Proxy configuration {'http': 'http://proxy:8080', 'https': 'https://proxy:8080'}

87

# - timeout (int): Request timeout in seconds (default: 60)

88

# - max_timeouts (int): Maximum timeout retries (default: 3)

89

# - max_retries (int): Maximum request retries (default: 3)

90

# - backoff_period (int): Backoff period between retries in seconds (default: 300)

91

92

# SSL/TLS Settings:

93

# - cacert (str|bool): Path to CA certificate file, True for system certs, False to skip verification

94

95

# Response Handling:

96

# - mute (bool): Suppress API errors and client errors (default: True)

97

# - return_raw_response (bool): Include raw response object in API returns

98

```

99

100

### StatsD Client Configuration

101

102

Detailed configuration options for the DogStatsD client behavior, transport, and performance optimization.

103

104

```python { .api }

105

# StatsD Configuration Parameters:

106

107

# Connection:

108

# - statsd_host (str): DogStatsD server hostname

109

# - statsd_port (int): DogStatsD server port

110

# - statsd_socket_path (str): Unix Domain Socket path (preferred over UDP)

111

# - statsd_use_default_route (bool): Dynamically resolve host from default route

112

113

# Performance:

114

# - statsd_disable_buffering (bool): Disable UDP packet buffering

115

# - statsd_disable_aggregation (bool): Disable client-side metric aggregation

116

# - statsd_aggregation_flush_interval (float): Aggregation flush interval

117

# - statsd_max_samples_per_context (int): Maximum samples per metric context

118

119

# Metadata:

120

# - statsd_namespace (str): Prefix added to all metric names

121

# - statsd_constant_tags (list): Tags applied to all metrics

122

# - cardinality (str): Cardinality level for all metrics

123

```

124

125

### Global Configuration State

126

127

Access and modify global configuration state for runtime adjustments and debugging.

128

129

```python { .api }

130

# Global configuration variables (datadog.api module):

131

132

# API Settings:

133

# api._api_key - Current API key

134

# api._application_key - Current application key

135

# api._api_host - Current API endpoint

136

# api._host_name - Current hostname

137

# api._api_version - API version (default: "v1")

138

139

# HTTP Settings:

140

# api._proxies - Proxy configuration

141

# api._timeout - Request timeout

142

# api._max_retries - Maximum retries

143

# api._mute - Error suppression setting

144

# api._return_raw_response - Raw response setting

145

146

# StatsD Global Instance:

147

# statsd - Global DogStatsd instance configured by initialize()

148

```

149

150

## Usage Examples

151

152

### Basic Configuration

153

154

```python

155

from datadog import initialize

156

157

# Simple configuration with API keys

158

initialize(

159

api_key="your-datadog-api-key",

160

app_key="your-datadog-app-key"

161

)

162

163

# Configuration with custom API host (for EU instance)

164

initialize(

165

api_key="your-api-key",

166

app_key="your-app-key",

167

api_host="https://api.datadoghq.eu"

168

)

169

```

170

171

### Environment Variable Configuration

172

173

```python

174

import os

175

from datadog import initialize

176

177

# Set environment variables

178

os.environ['DATADOG_API_KEY'] = 'your-api-key'

179

os.environ['DATADOG_APP_KEY'] = 'your-app-key'

180

os.environ['DATADOG_HOST'] = 'https://api.datadoghq.eu'

181

182

# Initialize without parameters - uses environment variables

183

initialize()

184

185

# Override environment variables with explicit parameters

186

initialize(

187

api_key="different-api-key", # Overrides DATADOG_API_KEY

188

statsd_host="custom-statsd-host"

189

)

190

```

191

192

### StatsD Configuration

193

194

```python

195

from datadog import initialize

196

197

# Configure StatsD with custom settings

198

initialize(

199

api_key="your-api-key",

200

app_key="your-app-key",

201

statsd_host="statsd.internal.com",

202

statsd_port=8125,

203

statsd_namespace="myapp",

204

statsd_constant_tags=["env:production", "service:web"],

205

statsd_disable_aggregation=False, # Enable aggregation

206

statsd_aggregation_flush_interval=1.0, # Flush every second

207

statsd_max_samples_per_context=100

208

)

209

```

210

211

### Unix Domain Socket Configuration

212

213

```python

214

from datadog import initialize

215

216

# Use Unix Domain Socket for better performance

217

initialize(

218

api_key="your-api-key",

219

app_key="your-app-key",

220

statsd_socket_path="/var/run/datadog/dsd.socket",

221

statsd_constant_tags=["transport:uds"]

222

)

223

```

224

225

### Container and Kubernetes Configuration

226

227

```python

228

from datadog import initialize

229

230

# Configuration for containerized environments

231

initialize(

232

api_key="your-api-key",

233

app_key="your-app-key",

234

statsd_use_default_route=True, # Auto-detect StatsD host

235

statsd_constant_tags=[

236

"container_name:web-server",

237

"k8s_namespace:production",

238

"k8s_pod_name:web-server-abc123"

239

],

240

hostname_from_config=False, # Don't use agent config in containers

241

host_name="web-server-pod-1" # Explicit hostname

242

)

243

```

244

245

### HTTP Client Advanced Configuration

246

247

```python

248

from datadog import initialize

249

250

# Advanced HTTP client configuration

251

initialize(

252

api_key="your-api-key",

253

app_key="your-app-key",

254

255

# Proxy configuration

256

proxies={

257

'http': 'http://proxy.company.com:8080',

258

'https': 'https://proxy.company.com:8080'

259

},

260

261

# Timeout and retry settings

262

timeout=30,

263

max_retries=5,

264

max_timeouts=2,

265

backoff_period=60,

266

267

# SSL configuration

268

cacert="/path/to/ca-certificates.pem",

269

270

# Response handling

271

mute=False, # Don't suppress errors

272

return_raw_response=True # Include raw HTTP response

273

)

274

```

275

276

### High Cardinality Configuration

277

278

```python

279

from datadog import initialize

280

281

# Configure for high cardinality metrics

282

initialize(

283

api_key="your-api-key",

284

app_key="your-app-key",

285

cardinality="high", # Enable high cardinality

286

statsd_constant_tags=[

287

"service:microservice-a",

288

"version:1.2.3",

289

"datacenter:us-east-1"

290

]

291

)

292

```

293

294

### Development vs Production Configuration

295

296

```python

297

from datadog import initialize

298

import os

299

300

def configure_datadog():

301

"""Configure Datadog based on environment."""

302

303

environment = os.environ.get('ENVIRONMENT', 'development')

304

305

if environment == 'production':

306

# Production configuration

307

initialize(

308

api_key=os.environ['DATADOG_API_KEY'],

309

app_key=os.environ['DATADOG_APP_KEY'],

310

api_host="https://api.datadoghq.com",

311

statsd_host="datadog-agent.monitoring.svc.cluster.local",

312

statsd_constant_tags=["env:production"],

313

cardinality="orchestrator",

314

statsd_disable_aggregation=False,

315

mute=True # Suppress errors in production

316

)

317

else:

318

# Development configuration

319

initialize(

320

api_key=os.environ.get('DATADOG_API_KEY', 'dummy-key'),

321

app_key=os.environ.get('DATADOG_APP_KEY', 'dummy-key'),

322

statsd_host="localhost",

323

statsd_constant_tags=["env:development"],

324

mute=False, # Show errors in development

325

return_raw_response=True # Debug HTTP responses

326

)

327

328

configure_datadog()

329

```

330

331

### Runtime Configuration Updates

332

333

```python

334

from datadog import initialize, api, statsd

335

336

# Initial configuration

337

initialize(api_key="initial-key", app_key="initial-app-key")

338

339

# Update API configuration at runtime

340

api._api_key = "new-api-key"

341

api._application_key = "new-app-key"

342

api._timeout = 30

343

344

# Update StatsD configuration at runtime

345

statsd.host = "new-statsd-host"

346

statsd.port = 8126

347

statsd.namespace = "updated_namespace"

348

statsd.constant_tags = ["updated:true"]

349

350

# Close and reconnect with new settings

351

statsd.close_socket()

352

```

353

354

### Configuration Validation

355

356

```python

357

from datadog import initialize, api

358

import sys

359

360

def validate_configuration():

361

"""Validate Datadog configuration before use."""

362

363

if not api._api_key:

364

print("ERROR: Datadog API key not configured")

365

sys.exit(1)

366

367

if not api._application_key:

368

print("ERROR: Datadog application key not configured")

369

sys.exit(1)

370

371

print(f"Datadog configured:")

372

print(f" API Host: {api._api_host}")

373

print(f" Hostname: {api._host_name}")

374

print(f" StatsD: {statsd.host}:{statsd.port}")

375

print(f" Namespace: {statsd.namespace}")

376

print(f" Constant Tags: {statsd.constant_tags}")

377

378

# Configure and validate

379

initialize(

380

api_key="your-api-key",

381

app_key="your-app-key",

382

statsd_namespace="myapp",

383

statsd_constant_tags=["service:web"]

384

)

385

386

validate_configuration()

387

```

388

389

### Multi-Environment Configuration Class

390

391

```python

392

from datadog import initialize

393

import os

394

from typing import Optional, List, Dict

395

396

class DatadogConfig:

397

"""Centralized Datadog configuration management."""

398

399

def __init__(

400

self,

401

environment: str,

402

api_key: Optional[str] = None,

403

app_key: Optional[str] = None,

404

service_name: str = "unknown-service",

405

version: str = "1.0.0"

406

):

407

self.environment = environment

408

self.api_key = api_key or os.environ.get('DATADOG_API_KEY')

409

self.app_key = app_key or os.environ.get('DATADOG_APP_KEY')

410

self.service_name = service_name

411

self.version = version

412

413

def get_statsd_config(self) -> Dict:

414

"""Get StatsD configuration for environment."""

415

416

base_tags = [

417

f"env:{self.environment}",

418

f"service:{self.service_name}",

419

f"version:{self.version}"

420

]

421

422

if self.environment == 'production':

423

return {

424

'statsd_host': 'datadog-agent.monitoring',

425

'statsd_port': 8125,

426

'statsd_constant_tags': base_tags + ['tier:production'],

427

'statsd_disable_aggregation': False,

428

'cardinality': 'orchestrator'

429

}

430

elif self.environment == 'staging':

431

return {

432

'statsd_host': 'datadog-agent.staging',

433

'statsd_port': 8125,

434

'statsd_constant_tags': base_tags + ['tier:staging'],

435

'cardinality': 'low'

436

}

437

else: # development/local

438

return {

439

'statsd_host': 'localhost',

440

'statsd_port': 8125,

441

'statsd_constant_tags': base_tags + ['tier:development'],

442

'cardinality': 'none'

443

}

444

445

def initialize_datadog(self):

446

"""Initialize Datadog with environment-specific configuration."""

447

448

statsd_config = self.get_statsd_config()

449

450

initialize(

451

api_key=self.api_key,

452

app_key=self.app_key,

453

**statsd_config

454

)

455

456

# Usage

457

config = DatadogConfig(

458

environment=os.environ.get('ENVIRONMENT', 'development'),

459

service_name='user-service',

460

version='2.1.0'

461

)

462

463

config.initialize_datadog()

464

```

465

466

## Configuration Best Practices

467

468

### Security

469

470

```python

471

# Good: Use environment variables for sensitive data

472

import os

473

from datadog import initialize

474

475

initialize(

476

api_key=os.environ['DATADOG_API_KEY'],

477

app_key=os.environ['DATADOG_APP_KEY']

478

)

479

480

# Avoid: Hardcoding credentials in source code

481

initialize(

482

api_key="abc123...", # Don't do this

483

app_key="def456..." # Don't do this

484

)

485

```

486

487

### Performance Optimization

488

489

```python

490

# For high-throughput applications

491

initialize(

492

api_key=os.environ['DATADOG_API_KEY'],

493

app_key=os.environ['DATADOG_APP_KEY'],

494

495

# Enable aggregation to reduce network traffic

496

statsd_disable_aggregation=False,

497

statsd_aggregation_flush_interval=1.0,

498

499

# Use Unix Domain Socket for better performance

500

statsd_socket_path="/var/run/datadog/dsd.socket",

501

502

# Batch metrics for efficiency

503

statsd_max_samples_per_context=1000

504

)

505

```

506

507

### Consistent Tagging Strategy

508

509

```python

510

# Establish consistent tagging across all metrics

511

initialize(

512

api_key=os.environ['DATADOG_API_KEY'],

513

app_key=os.environ['DATADOG_APP_KEY'],

514

statsd_constant_tags=[

515

f"env:{os.environ.get('ENVIRONMENT', 'development')}",

516

f"service:{os.environ.get('SERVICE_NAME', 'unknown')}",

517

f"version:{os.environ.get('SERVICE_VERSION', '1.0.0')}",

518

f"region:{os.environ.get('AWS_REGION', 'us-east-1')}",

519

f"instance_type:{os.environ.get('INSTANCE_TYPE', 'unknown')}"

520

]

521

)

522

```