StatsD Client
The `statsd` library is a simple Python client for the StatsD daemon, used for sending various types of metrics (counters, timers, gauges, sets) to monitoring systems like Graphite, Datadog, and Telegraf. It is actively maintained, with the current version being 4.0.1.
Warnings
- breaking Version 4.0.0 dropped support for Python 2. All users must be on Python 3.7 or newer to use `statsd` v4.x.
- breaking The global `statsd` object (e.g., `from statsd import statsd`) was removed in version 3.0. This old pattern implicitly picked up configuration.
- gotcha The `statsd` client library does not natively support tagged metrics (e.g., `metric_name#tag:value`) used by some backends like Datadog or Telegraf in the same way as traditional StatsD. Sending tagged metrics without careful naming will result in data loss or misinterpretation.
- gotcha StatsD typically uses UDP port 8125 by default. Firewalls or security settings often block this port, preventing metrics from reaching the StatsD server.
- gotcha Incorrect hostname or port in the `StatsClient` configuration is a common cause of metrics not being received.
- gotcha The `timing` decorator on `async` functions was broken in versions prior to 4.0.0, incorrectly measuring execution time immediately instead of awaiting the function.
Install
-
pip install statsd
Imports
- StatsClient
from statsd import StatsClient
Quickstart
import statsd
import time
import os
# Configure connection to StatsD server
# Default StatsD port is 8125
# Replace 'localhost' with your StatsD server's hostname or IP if different
statsd_host = os.environ.get('STATSD_HOST', 'localhost')
statsd_port = int(os.environ.get('STATSD_PORT', 8125))
# Instantiate the StatsClient
c = statsd.StatsClient(statsd_host, statsd_port, prefix='my_app')
# Increment a counter
c.incr('page_views')
print(f"Incremented 'my_app.page_views' counter.")
# Record a timing (in milliseconds)
start_time = time.time()
time.sleep(0.05) # Simulate some work
end_time = time.time()
delta_ms = int((end_time - start_time) * 1000)
c.timing('response_time', delta_ms)
print(f"Recorded 'my_app.response_time' timing: {delta_ms}ms.")
# Set a gauge value
c.gauge('active_users', 15)
print(f"Set 'my_app.active_users' gauge to 15.")
# Using a timing decorator
@c.timer('decorated_function_time')
def my_function():
time.sleep(0.02) # Simulate work
my_function()
print(f"'my_app.decorated_function_time' recorded using decorator.")