Django StatsD Integration
django-statsd is a Django application that integrates with Etsy's statsd service to submit query and view durations, helping monitor application performance. It's actively maintained, with minor releases typically focused on maintaining compatibility with new Django versions.
Warnings
- breaking Older versions of `django-statsd` are not compatible with newer Django versions. Specifically, versions prior to `2.7.0` lack official support for Django 4.2 and 5.0.
- gotcha The `django-statsd` library itself (version 2.7.0+) requires Python 3.8 or newer. Attempting to use it with older Python versions will result in installation or runtime errors.
- gotcha The order of middlewares is crucial. `StatsdMiddleware` should generally be placed early in your `MIDDLEWARE` list to ensure it wraps all requests, even those handled by other middlewares. `StatsdPageTimingMiddleware` should be placed later, after middlewares that might affect page rendering, to accurately measure rendering time.
- gotcha The `statsd` client for sending custom metrics (`statsd.incr()`, `statsd.timing()`, etc.) is imported directly from the `statsd` package (which is `python-statsd`), not from `django_statsd`. Incorrectly trying to import it from `django_statsd` will fail.
Install
-
pip install django-statsd
Imports
- django_statsd
INSTALLED_APPS = ['django_statsd']
- StatsdMiddleware
from django_statsd.middleware import StatsdMiddleware
- StatsdPageTimingMiddleware
from django_statsd.middleware import StatsdPageTimingMiddleware
- statsd
from statsd import statsd
Quickstart
import os
# settings.py
INSTALLED_APPS = [
# ... other apps
'django_statsd',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# Place StatsdMiddleware early to catch all requests
'django_statsd.middleware.StatsdMiddleware',
# ... other middlewares
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Place StatsdPageTimingMiddleware later to time page rendering
'django_statsd.middleware.StatsdPageTimingMiddleware',
]
STATSD_HOST = os.environ.get('STATSD_HOST', 'localhost')
STATSD_PORT = int(os.environ.get('STATSD_PORT', '8125'))
STATSD_PREFIX = os.environ.get('STATSD_PREFIX', 'myproject')
# myapp/views.py (example usage)
from django.http import HttpResponse
from statsd import statsd
def my_view(request):
statsd.incr('my_view.hits')
# Simulate some work
import time
time.sleep(0.05)
statsd.timing('my_view.processing_time', 50) # In milliseconds
return HttpResponse("Hello, Django Statsd!")