StatsD Client

4.0.1 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `StatsClient` and send common metric types: counters, timings, and gauges. It also shows how to use the timing decorator. Ensure a StatsD server is running and accessible at the specified host and port.

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

view raw JSON →