StatsD Python Client
The `statsd-python` library (version 0.6.1) provides a simple Python client for sending metrics to a StatsD server via UDP. It supports incrementing counters, setting gauges, and recording timings. The library has a stable API and sees infrequent updates, making it a reliable choice for basic StatsD integration.
Common errors
-
ModuleNotFoundError: No module named 'statsd'
cause The `statsd-python` package was not installed in the current Python environment or is not in the Python path.fix`pip install statsd-python` -
AttributeError: module 'statsd' has no attribute 'StatsClient'
cause This usually indicates that a different `statsd` library (not `statsd-python` by lirsacc) is installed, or a misimport. Some older `statsd` packages might expose the client directly as `statsd.statsd` or have no `StatsClient` attribute.fixEnsure `pip show statsd-python` confirms you have the correct library installed. If other `statsd` packages are present (`pip freeze | grep statsd`), try uninstalling them (`pip uninstall <conflicting-package-name>`) and then reinstall `statsd-python`. Also, ensure you are importing `import statsd` and then using `statsd.StatsClient`.
Warnings
- gotcha Metrics are not visible in monitoring tools or appear inconsistent.
- gotcha Name collision with other 'statsd' or 'pystatsd' libraries.
Install
-
pip install statsd-python
Imports
- StatsClient
from statsd import StatsClient
import statsd c = statsd.StatsClient(...)
Quickstart
import statsd
import time
import os
# Configure StatsD client
# Default StatsD host is usually 'localhost', port 8125
# Replace with your StatsD server's host and port if different
statsd_host = os.environ.get('STATSD_HOST', 'localhost')
statsd_port = int(os.environ.get('STATSD_PORT', '8125'))
c = statsd.StatsClient(statsd_host, statsd_port)
print(f"Sending metrics to StatsD server at {statsd_host}:{statsd_port}...")
# Increment a counter
c.incr('my_app.requests_total')
print("Incremented 'my_app.requests_total'")
# Set a gauge value
c.gauge('my_app.active_users', 15)
c.gauge('my_app.memory_usage_mb', 256.7)
print("Set gauges for 'my_app.active_users' and 'my_app.memory_usage_mb'")
# Record a timing (in milliseconds)
start_time = time.time()
time.sleep(0.05) # Simulate some work
end_time = time.time()
duration_ms = (end_time - start_time) * 1000
c.timing('my_app.process_duration_ms', duration_ms)
print(f"Recorded timing for 'my_app.process_duration_ms': {duration_ms:.2f}ms")
# Send with a sample rate (e.g., send only 50% of the time)
c.incr('my_app.sampled_events', rate=0.5)
print("Incremented 'my_app.sampled_events' with a 50% sample rate")
print("Metrics sent. Check your StatsD server for reception.")