statshog
statshog is a simple Python client for emitting metrics to StatsD servers, including both Etsy's original StatsD and InfluxDB's Telegraf StatsD server. It provides functionalities for incrementing counters, recording gauges, and tracking timings. The library is currently at version 1.0.6, with a stable but infrequent release cadence, reflecting its mature and focused functionality.
Warnings
- gotcha StatsD clients, including statshog, typically use UDP for sending metrics. UDP is an unreliable protocol, meaning there is no guarantee that packets will reach the StatsD server. For critical metrics, consider the implications of potential packet loss.
- gotcha When initializing `StatsClient`, ensure `host` and `port` parameters are correctly configured for your StatsD server. The defaults (`localhost:8125`) might not match your deployment.
- gotcha Using the `telegraf=True` parameter changes the wire format for sending tags. If your StatsD server is not Telegraf-compatible (or another server that understands Telegraf's tag format), tags will likely be ignored or cause parsing errors.
Install
-
pip install statshog
Imports
- StatsClient
from statshog import StatsClient
- statsd (Django default)
from statshog.defaults.django import statsd
Quickstart
import statshog
import time
# Initialize a StatsD client (defaults to localhost:8125)
# For Telegraf's StatsD with tags, use telegraf=True
statsd = statshog.StatsClient(host='127.0.0.1', port=8125, telegraf=True)
# Increment a counter
statsd.incr('my_app.requests_total')
statsd.incr('my_app.errors', tags={'type': 'database_error'})
# Record a gauge value
statsd.gauge('my_app.cpu_usage', 55)
statsd.gauge('my_app.memory_percent', 72.5, tags={'host': 'server_a'})
# Record a timing
start_time = time.time()
time.sleep(0.05) # Simulate some work
end_time = time.time()
duration_ms = (end_time - start_time) * 1000
statsd.timing('my_app.api_response_time', duration_ms, tags={'endpoint': '/api/data'})
print('Metrics sent to StatsD.')
# In a real application, ensure your StatsD server (e.g., Telegraf) is running on 127.0.0.1:8125
# and listening for UDP packets.