Django middlewares to monitor your application with Prometheus.io
—
Comprehensive monitoring of HTTP requests, responses, exceptions, and latencies through Django middleware. The middleware system provides detailed metrics on web application performance and usage patterns.
Monitors early request/response lifecycle events and measures total latency including middleware processing time.
class PrometheusBeforeMiddleware(MiddlewareMixin):
"""
Monitoring middleware that should run before other middlewares.
Measures total request latency including middleware processing time.
"""
metrics_cls = Metrics
def __init__(self, *args, **kwargs):
"""
Initialize middleware with metrics instance.
Parameters:
- *args, **kwargs: Arguments passed to MiddlewareMixin
"""
def process_request(self, request):
"""
Records request start time and increments request counter.
Parameters:
- request: Django HttpRequest object
"""
def process_response(self, request, response):
"""
Records response and measures total latency including middlewares.
Parameters:
- request: Django HttpRequest object
- response: Django HttpResponse object
Returns:
HttpResponse object (passed through)
"""Provides detailed monitoring of request characteristics, view processing, template usage, response details, and exception handling.
class PrometheusAfterMiddleware(MiddlewareMixin):
"""
Monitoring middleware that should run after other middlewares.
Provides detailed metrics on request/response characteristics.
"""
metrics_cls = Metrics
def __init__(self, *args, **kwargs):
"""
Initialize middleware with metrics instance.
Parameters:
- *args, **kwargs: Arguments passed to MiddlewareMixin
"""
def process_request(self, request):
"""
Records request method, transport, AJAX status, and body size.
Parameters:
- request: Django HttpRequest object
"""
def process_view(self, request, view_func, *view_args, **view_kwargs):
"""
Records view-specific metrics including view name and routing info.
Parameters:
- request: Django HttpRequest object
- view_func: View function being called
- view_args: Positional arguments to view
- view_kwargs: Keyword arguments to view
"""
def process_template_response(self, request, response):
"""
Records template name usage for template-based responses.
Parameters:
- request: Django HttpRequest object
- response: Django TemplateResponse object
Returns:
TemplateResponse object (passed through)
"""
def process_response(self, request, response):
"""
Records response status, charset, streaming status, body size, and view latency.
Parameters:
- request: Django HttpRequest object
- response: Django HttpResponse object
Returns:
HttpResponse object (passed through)
"""
def process_exception(self, request, exception):
"""
Records exception metrics by type and view when exceptions occur.
Parameters:
- request: Django HttpRequest object
- exception: Exception instance that was raised
"""
def label_metric(self, metric, request, response=None, **labels):
"""
Helper method to apply labels to metrics.
Parameters:
- metric: Prometheus metric object
- request: Django HttpRequest object
- response: Optional Django HttpResponse object
- **labels: Label key-value pairs
Returns:
Labeled metric object
"""Singleton class managing all HTTP monitoring metrics with proper metric registration and initialization.
class Metrics:
"""
Singleton class that registers and manages all HTTP monitoring metrics.
"""
@classmethod
def get_instance(cls):
"""
Returns singleton instance of Metrics class.
Returns:
Metrics instance
"""
def register_metric(self, metric_cls, name: str, documentation: str, labelnames=(), **kwargs):
"""
Registers a Prometheus metric with proper naming and labeling.
Parameters:
- metric_cls: Prometheus metric class (Counter, Histogram, etc.)
- name: str, metric name
- documentation: str, metric documentation
- labelnames: tuple, label names for the metric
- **kwargs: Additional metric configuration
Returns:
Registered metric instance
"""
def register(self):
"""Registers all HTTP monitoring metrics."""django_http_requests_before_middlewares_total: Total requests before middleware processingdjango_http_requests_total_by_method: Requests by HTTP method (GET, POST, etc.)django_http_requests_total_by_transport: Requests by transport (http, https)django_http_requests_total_by_view_transport_method: Requests by view, transport, and methoddjango_http_ajax_requests_total: AJAX request countdjango_http_requests_body_total_bytes: Request body size histogramdjango_http_responses_before_middlewares_total: Total responses before middleware processingdjango_http_responses_total_by_status: Responses by HTTP status codedjango_http_responses_total_by_status_view_method: Responses by status, view, and methoddjango_http_responses_total_by_charset: Responses by character encodingdjango_http_responses_total_by_templatename: Responses by template namedjango_http_responses_streaming_total: Streaming response countdjango_http_responses_body_total_bytes: Response body size histogramdjango_http_requests_latency_including_middlewares_seconds: Request latency including middleware timedjango_http_requests_latency_seconds_by_view_method: Request latency by view and methoddjango_http_requests_unknown_latency_including_middlewares_total: Requests with unknown middleware latencydjango_http_requests_unknown_latency_total: Requests with unknown processing latencydjango_http_exceptions_total_by_type: Exceptions by exception class namedjango_http_exceptions_total_by_view: Exceptions by view name# settings.py
MIDDLEWARE = [
'django_prometheus.middleware.PrometheusBeforeMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# ... other middleware
'django_prometheus.middleware.PrometheusAfterMiddleware',
]
# Optional configuration
PROMETHEUS_METRIC_NAMESPACE = 'myapp'
PROMETHEUS_LATENCY_BUCKETS = (0.1, 0.5, 1.0, 2.5, 5.0, 10.0, float('inf'))Install with Tessl CLI
npx tessl i tessl/pypi-django-prometheus