The Datadog Python library provides tools for interacting with Datadog's monitoring platform through HTTP API client functionality, DogStatsD metrics client, and command-line tools.
npx @tessl/cli install tessl/pypi-datadog@0.52.00
# Datadog
1
2
The Datadog Python Library is a comprehensive collection of tools for interacting with Datadog's monitoring and analytics platform. It provides HTTP API client functionality for managing Datadog resources, DogStatsD client capabilities for efficient real-time metrics aggregation, thread-safe metrics collection, and command-line tools for DevOps workflows.
3
4
## Package Information
5
6
- **Package Name**: datadog
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install datadog`
10
- **Version**: 0.52.1
11
12
## Core Imports
13
14
```python
15
import datadog
16
```
17
18
For API functionality:
19
20
```python
21
from datadog import initialize, api
22
```
23
24
For metrics collection:
25
26
```python
27
from datadog import DogStatsd, statsd, ThreadStats
28
```
29
30
For command-line tools:
31
32
```python
33
from datadog.dogshell import main
34
```
35
36
## Basic Usage
37
38
```python
39
from datadog import initialize, api
40
41
# Configure the library with your credentials
42
options = {
43
"api_key": "<YOUR_API_KEY>",
44
"app_key": "<YOUR_APP_KEY>",
45
}
46
47
initialize(**options)
48
49
# Submit an event
50
title = "Application deployment successful"
51
text = "Version 1.2.3 deployed to production"
52
tags = ["version:1.2.3", "environment:production"]
53
54
api.Event.create(title=title, text=text, tags=tags)
55
56
# Submit metrics using DogStatsD
57
from datadog import statsd
58
59
statsd.increment('web.requests', tags=['endpoint:api'])
60
statsd.gauge('system.cpu.usage', 75.5, tags=['host:web01'])
61
statsd.timing('db.query.duration', 245, tags=['table:users'])
62
```
63
64
## Architecture
65
66
The Datadog Python Library is organized into several key modules:
67
68
- **datadog.api**: REST API client providing full access to Datadog's HTTP API endpoints
69
- **datadog.dogstatsd**: StatsD client for efficient real-time metrics submission to DogStatsD
70
- **datadog.threadstats**: Thread-safe alternative for metrics collection without performance impact
71
- **datadog.dogshell**: Command-line interface tools wrapping the API functionality
72
- **datadog.util**: Shared utilities for hostname resolution, formatting, and compatibility
73
74
The library supports multiple transport protocols (UDP, UDS), includes automatic telemetry injection, comprehensive error handling, and both high-level abstractions and low-level control over Datadog's platform.
75
76
## Capabilities
77
78
### Library Configuration
79
80
Core initialization and configuration for API authentication, StatsD connection settings, and global library behavior.
81
82
```python { .api }
83
def initialize(
84
api_key=None,
85
app_key=None,
86
host_name=None,
87
api_host=None,
88
statsd_host=None,
89
statsd_port=None,
90
statsd_disable_aggregation=True,
91
statsd_disable_buffering=True,
92
statsd_aggregation_flush_interval=0.3,
93
statsd_use_default_route=False,
94
statsd_socket_path=None,
95
statsd_namespace=None,
96
statsd_max_samples_per_context=0,
97
statsd_constant_tags=None,
98
return_raw_response=False,
99
hostname_from_config=True,
100
cardinality=None,
101
**kwargs
102
):
103
"""
104
Initialize and configure Datadog API and StatsD modules.
105
106
Parameters:
107
- api_key (str): Datadog API key
108
- app_key (str): Datadog application key
109
- host_name (str): Specific hostname override
110
- api_host (str): Datadog API endpoint URL
111
- statsd_host (str): Host of DogStatsD server
112
- statsd_port (int): Port of DogStatsD server
113
- statsd_disable_aggregation (bool): Disable client-side aggregation (default: True)
114
- statsd_disable_buffering (bool): Disable metric buffering (default: True)
115
- statsd_aggregation_flush_interval (float): Aggregation flush interval in seconds (default: 0.3)
116
- statsd_use_default_route (bool): Auto-detect StatsD host from default route (default: False)
117
- statsd_socket_path (str): Path to DogStatsD UNIX socket
118
- statsd_namespace (str): Prefix for all metric names
119
- statsd_max_samples_per_context (int): Max samples per metric context (default: 0)
120
- statsd_constant_tags (list): Tags applied to all metrics
121
- return_raw_response (bool): Return raw HTTP response objects (default: False)
122
- hostname_from_config (bool): Get hostname from Datadog agent config (default: True)
123
- cardinality (str): Global cardinality level ('none', 'low', 'orchestrator', 'high')
124
- **kwargs: Additional configuration options
125
"""
126
```
127
128
[Configuration](./configuration.md)
129
130
### HTTP API Client
131
132
Complete REST API client providing access to all Datadog HTTP endpoints for managing events, metrics, monitors, dashboards, infrastructure, integrations, users, and more.
133
134
```python { .api }
135
# Event management
136
api.Event.create(title, text, **kwargs)
137
api.Event.query(**kwargs)
138
api.Event.get(event_id)
139
140
# Metrics querying and submission
141
api.Metric.query(**kwargs)
142
api.Metric.send(**kwargs)
143
api.Metric.list()
144
145
# Monitor management
146
api.Monitor.create(type, query, **kwargs)
147
api.Monitor.get_all(**kwargs)
148
api.Monitor.get(monitor_id)
149
api.Monitor.update(monitor_id, **kwargs)
150
api.Monitor.delete(monitor_id)
151
api.Monitor.mute_all()
152
api.Monitor.unmute_all()
153
api.Monitor.search(**kwargs)
154
```
155
156
[HTTP API Client](./http-api-client.md)
157
158
### DogStatsD Metrics Client
159
160
High-performance StatsD client for submitting metrics, events, and service checks to DogStatsD with support for buffering, aggregation, and multiple transport protocols.
161
162
```python { .api }
163
class DogStatsd:
164
def gauge(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
165
def gauge_with_timestamp(self, metric, value, timestamp, tags=None, sample_rate=None, cardinality=None): ...
166
def increment(self, metric, value=1, tags=None, sample_rate=None, cardinality=None): ...
167
def decrement(self, metric, value=1, tags=None, sample_rate=None, cardinality=None): ...
168
def count(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
169
def histogram(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
170
def distribution(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
171
def timing(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
172
def set(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
173
def event(self, title, text, **kwargs): ...
174
def service_check(self, check_name, status, **kwargs): ...
175
176
# Default instance
177
statsd = DogStatsd()
178
```
179
180
[DogStatsD Client](./dogstatsd-client.md)
181
182
### ThreadStats Metrics Collection
183
184
Thread-safe metrics collection system that aggregates metrics in background threads without hindering application performance, ideal for high-throughput applications.
185
186
```python { .api }
187
class ThreadStats:
188
def start(self): ...
189
def stop(self): ...
190
def gauge(self, metric, value, tags=None, sample_rate=1): ...
191
def increment(self, metric, value=1, tags=None, sample_rate=1): ...
192
def histogram(self, metric, value, tags=None, sample_rate=1): ...
193
def timing(self, metric, value, tags=None, sample_rate=1): ...
194
def timer(self): ... # Context manager
195
def timed(self): ... # Decorator
196
def flush(self): ...
197
```
198
199
[ThreadStats](./threadstats.md)
200
201
### Command-Line Tools
202
203
Comprehensive command-line interface providing access to all Datadog functionality through shell commands, supporting automation, scripting, and DevOps workflows.
204
205
```python { .api }
206
def main():
207
"""Main entry point for dogshell CLI commands."""
208
209
# Available commands via console scripts:
210
# - dogshell: Main CLI command
211
# - dog: Legacy CLI command (deprecated)
212
# - dogwrap: Command wrapper for metrics
213
# - dogshellwrap: Shell wrapper for metrics
214
```
215
216
[Command-Line Tools](./command-line-tools.md)
217
218
### Error Handling
219
220
Comprehensive exception hierarchy for handling API errors, network issues, authentication problems, and client-side errors with appropriate retry and recovery strategies.
221
222
```python { .api }
223
class DatadogException(Exception): ...
224
class ApiError(DatadogException): ...
225
class ClientError(DatadogException): ...
226
class HttpTimeout(ClientError): ...
227
class HttpBackoff(ClientError): ...
228
class HTTPError(ClientError): ...
229
class ProxyError(ClientError): ...
230
class ApiNotInitialized(ApiError): ...
231
```
232
233
[Error Handling](./error-handling.md)
234
235
## Constants
236
237
### Service Check Status
238
239
```python { .api }
240
OK = 0
241
WARNING = 1
242
CRITICAL = 2
243
UNKNOWN = 3
244
```
245
246
### Cardinality Levels
247
248
```python { .api }
249
CARDINALITY_NONE = "none"
250
CARDINALITY_LOW = "low"
251
CARDINALITY_ORCHESTRATOR = "orchestrator"
252
CARDINALITY_HIGH = "high"
253
```
254
255
## Types
256
257
```python { .api }
258
# Metric value types
259
MetricValue = Union[int, float]
260
261
# Tag format
262
Tag = str # Format: "key:value" or "key"
263
Tags = List[Tag]
264
265
# Timestamp format
266
Timestamp = Union[int, float] # Unix timestamp
267
268
# Service check status
269
ServiceCheckStatus = Literal[0, 1, 2, 3] # OK, WARNING, CRITICAL, UNKNOWN
270
271
# Monitor types (constants from MonitorType class)
272
QUERY_ALERT = "query alert"
273
COMPOSITE = "composite"
274
SERVICE_CHECK = "service check"
275
PROCESS_ALERT = "process alert"
276
LOG_ALERT = "log alert"
277
METRIC_ALERT = "metric alert"
278
RUM_ALERT = "rum alert"
279
EVENT_ALERT = "event alert"
280
SYNTHETICS_ALERT = "synthetics alert"
281
TRACE_ANALYTICS = "trace-analytics alert"
282
```