Python StatsD Client

4.0.1 · active · verified Sun Apr 12

python-statsd is a Python client for the StatsD daemon, a front-end/proxy for Graphite's stats collection and graphing server. While the user-provided slug is 'python-statsd' (version 2.1.0), this PyPI project typically redirects to 'statsd' (currently 4.0.1). This entry reflects the features and usage of the actively maintained 'statsd' package on PyPI, which is the direct successor and most commonly used client. It allows applications to send various metrics like counters, timers, and gauges over UDP (or TCP) for aggregation and monitoring. The library generally follows a stable release cadence for minor bug fixes and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a StatsD client and send common metric types: counters, timers, and gauges. It uses environment variables for host and port for easy configuration, defaulting to localhost:8125. A prefix is added to all metrics for better organization.

import statsd
import os

# Configure StatsD client, typically pointing to a local StatsD agent
# Default host is 'localhost', default port is 8125
# You can override with environment variables or direct arguments
statsd_host = os.environ.get('STATSD_HOST', 'localhost')
statsd_port = int(os.environ.get('STATSD_PORT', 8125))

c = statsd.StatsClient(host=statsd_host, port=statsd_port, prefix='my_app')

# Increment a counter
c.incr('page_views')
c.incr('successful_requests', 5)

# Record a timing (in milliseconds)
import time
start_time = time.time()
time.sleep(0.05) # Simulate work
duration_ms = (time.time() - start_time) * 1000
c.timing('api_response_time', duration_ms)

# Set a gauge value
c.gauge('current_users', 150)

print(f"Sent metrics to StatsD at {statsd_host}:{statsd_port}")
print("Check your StatsD server/Graphite for 'my_app.page_views', 'my_app.successful_requests', 'my_app.api_response_time', 'my_app.current_users'")

view raw JSON →