Python StatsD Client
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
- breaking The PyPI package `python-statsd` has effectively been replaced by `statsd` (maintained by `jsocol/pystatsd`). While `WoLpH/python-statsd` GitHub repo lists version 2.1.0, its own documentation links point to the `statsd` package (currently 4.0.1). Installing `python-statsd` via pip today will install the `statsd` package.
- gotcha This library (`statsd` on PyPI) explicitly does not support tagged metrics (e.g., `metric:value|#tag1:foo,tag2:bar`) used by systems like Datadog, Telegraf, or Prometheus StatsD exporters. Attempting to send tags will result in data loss or incorrect metric names.
- gotcha StatsD primarily uses UDP for metric transmission, which is a 'fire-and-forget' protocol. While highly performant, it does not guarantee delivery. Packets can be silently dropped by the network or the StatsD server under heavy load or network issues.
- gotcha Several Python libraries exist on PyPI with 'statsd' in their name (e.g., `statsd`, `statsd-client`, `statsd-exporter`, `statsd-tags`). This can lead to confusion and accidentally installing a different client with a non-compatible API or missing features.
Install
-
pip install statsd
Imports
- StatsClient
from statsd import StatsClient
Quickstart
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'")