Django StatsD Integration

2.7.0 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

Configure `django-statsd` by adding it to `INSTALLED_APPS` and integrating its middlewares into your `MIDDLEWARE` list in `settings.py`. Define `STATSD_HOST`, `STATSD_PORT`, and `STATSD_PREFIX` for your StatsD server. For custom metrics, import the `statsd` client directly from the `statsd` library and use its methods (e.g., `incr`, `timing`) within your application code, such as views or services.

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

view raw JSON →