StatsD Python Client

0.6.1 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `StatsClient` and send common metric types: counters (`incr`), gauges (`gauge`), and timings (`timing`). It also shows how to use a sample rate for counters.

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.")

view raw JSON →