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.0The 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.
pip install datadogimport datadogFor API functionality:
from datadog import initialize, apiFor metrics collection:
from datadog import DogStatsd, statsd, ThreadStatsFor command-line tools:
from datadog.dogshell import mainfrom datadog import initialize, api
# Configure the library with your credentials
options = {
"api_key": "<YOUR_API_KEY>",
"app_key": "<YOUR_APP_KEY>",
}
initialize(**options)
# Submit an event
title = "Application deployment successful"
text = "Version 1.2.3 deployed to production"
tags = ["version:1.2.3", "environment:production"]
api.Event.create(title=title, text=text, tags=tags)
# Submit metrics using DogStatsD
from datadog import statsd
statsd.increment('web.requests', tags=['endpoint:api'])
statsd.gauge('system.cpu.usage', 75.5, tags=['host:web01'])
statsd.timing('db.query.duration', 245, tags=['table:users'])The Datadog Python Library is organized into several key modules:
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.
Core initialization and configuration for API authentication, StatsD connection settings, and global library behavior.
def initialize(
api_key=None,
app_key=None,
host_name=None,
api_host=None,
statsd_host=None,
statsd_port=None,
statsd_disable_aggregation=True,
statsd_disable_buffering=True,
statsd_aggregation_flush_interval=0.3,
statsd_use_default_route=False,
statsd_socket_path=None,
statsd_namespace=None,
statsd_max_samples_per_context=0,
statsd_constant_tags=None,
return_raw_response=False,
hostname_from_config=True,
cardinality=None,
**kwargs
):
"""
Initialize and configure Datadog API and StatsD modules.
Parameters:
- api_key (str): Datadog API key
- app_key (str): Datadog application key
- host_name (str): Specific hostname override
- api_host (str): Datadog API endpoint URL
- statsd_host (str): Host of DogStatsD server
- statsd_port (int): Port of DogStatsD server
- statsd_disable_aggregation (bool): Disable client-side aggregation (default: True)
- statsd_disable_buffering (bool): Disable metric buffering (default: True)
- statsd_aggregation_flush_interval (float): Aggregation flush interval in seconds (default: 0.3)
- statsd_use_default_route (bool): Auto-detect StatsD host from default route (default: False)
- statsd_socket_path (str): Path to DogStatsD UNIX socket
- statsd_namespace (str): Prefix for all metric names
- statsd_max_samples_per_context (int): Max samples per metric context (default: 0)
- statsd_constant_tags (list): Tags applied to all metrics
- return_raw_response (bool): Return raw HTTP response objects (default: False)
- hostname_from_config (bool): Get hostname from Datadog agent config (default: True)
- cardinality (str): Global cardinality level ('none', 'low', 'orchestrator', 'high')
- **kwargs: Additional configuration options
"""Complete REST API client providing access to all Datadog HTTP endpoints for managing events, metrics, monitors, dashboards, infrastructure, integrations, users, and more.
# Event management
api.Event.create(title, text, **kwargs)
api.Event.query(**kwargs)
api.Event.get(event_id)
# Metrics querying and submission
api.Metric.query(**kwargs)
api.Metric.send(**kwargs)
api.Metric.list()
# Monitor management
api.Monitor.create(type, query, **kwargs)
api.Monitor.get_all(**kwargs)
api.Monitor.get(monitor_id)
api.Monitor.update(monitor_id, **kwargs)
api.Monitor.delete(monitor_id)
api.Monitor.mute_all()
api.Monitor.unmute_all()
api.Monitor.search(**kwargs)High-performance StatsD client for submitting metrics, events, and service checks to DogStatsD with support for buffering, aggregation, and multiple transport protocols.
class DogStatsd:
def gauge(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
def gauge_with_timestamp(self, metric, value, timestamp, tags=None, sample_rate=None, cardinality=None): ...
def increment(self, metric, value=1, tags=None, sample_rate=None, cardinality=None): ...
def decrement(self, metric, value=1, tags=None, sample_rate=None, cardinality=None): ...
def count(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
def histogram(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
def distribution(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
def timing(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
def set(self, metric, value, tags=None, sample_rate=None, cardinality=None): ...
def event(self, title, text, **kwargs): ...
def service_check(self, check_name, status, **kwargs): ...
# Default instance
statsd = DogStatsd()Thread-safe metrics collection system that aggregates metrics in background threads without hindering application performance, ideal for high-throughput applications.
class ThreadStats:
def start(self): ...
def stop(self): ...
def gauge(self, metric, value, tags=None, sample_rate=1): ...
def increment(self, metric, value=1, tags=None, sample_rate=1): ...
def histogram(self, metric, value, tags=None, sample_rate=1): ...
def timing(self, metric, value, tags=None, sample_rate=1): ...
def timer(self): ... # Context manager
def timed(self): ... # Decorator
def flush(self): ...Comprehensive command-line interface providing access to all Datadog functionality through shell commands, supporting automation, scripting, and DevOps workflows.
def main():
"""Main entry point for dogshell CLI commands."""
# Available commands via console scripts:
# - dogshell: Main CLI command
# - dog: Legacy CLI command (deprecated)
# - dogwrap: Command wrapper for metrics
# - dogshellwrap: Shell wrapper for metricsComprehensive exception hierarchy for handling API errors, network issues, authentication problems, and client-side errors with appropriate retry and recovery strategies.
class DatadogException(Exception): ...
class ApiError(DatadogException): ...
class ClientError(DatadogException): ...
class HttpTimeout(ClientError): ...
class HttpBackoff(ClientError): ...
class HTTPError(ClientError): ...
class ProxyError(ClientError): ...
class ApiNotInitialized(ApiError): ...OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3CARDINALITY_NONE = "none"
CARDINALITY_LOW = "low"
CARDINALITY_ORCHESTRATOR = "orchestrator"
CARDINALITY_HIGH = "high"# Metric value types
MetricValue = Union[int, float]
# Tag format
Tag = str # Format: "key:value" or "key"
Tags = List[Tag]
# Timestamp format
Timestamp = Union[int, float] # Unix timestamp
# Service check status
ServiceCheckStatus = Literal[0, 1, 2, 3] # OK, WARNING, CRITICAL, UNKNOWN
# Monitor types (constants from MonitorType class)
QUERY_ALERT = "query alert"
COMPOSITE = "composite"
SERVICE_CHECK = "service check"
PROCESS_ALERT = "process alert"
LOG_ALERT = "log alert"
METRIC_ALERT = "metric alert"
RUM_ALERT = "rum alert"
EVENT_ALERT = "event alert"
SYNTHETICS_ALERT = "synthetics alert"
TRACE_ANALYTICS = "trace-analytics alert"