Skip to content

Instantly share code, notes, and snippets.

@mhgbrown
Created November 18, 2016 16:28
Show Gist options
  • Save mhgbrown/0da793fabe14a852414c5a6fb76da271 to your computer and use it in GitHub Desktop.
Save mhgbrown/0da793fabe14a852414c5a6fb76da271 to your computer and use it in GitHub Desktop.
Django Middleware to track request time to Mixpanel
import datetime
import uuid
from django.conf import settings
from mixpanel import Mixpanel
from mixpanel_async import AsyncBufferedConsumer
mp = Mixpanel(settings.MIXPANEL_API_TOKEN, consumer=AsyncBufferedConsumer())
class RequestTimeTrackingMiddleware(object):
"""Middleware class tracking request time to Mixpanel.
This class can be used to measure time of request processing
within Django.
Static method `track_request' may be used independently of the
middleware itself, outside of it, and even when middleware is not
listed in MIDDLEWARE_CLASSES.
Based on https://djangosnippets.org/snippets/1826/
"""
@staticmethod
def track_request(request):
"""Track request time to Mixpanel
Tracks time to complete a request to Mixpanel
Sends the following to Mixpanel
- distinct_id is the authenticated user's email or 'Anonymous'
- id is the UUID identifying request
- path is the full request path
- duration is the duration of the request in milliseconds
- environment is development if DEBUG is True, production otherwise
"""
distinct_id = 'Anonymous'
if hasattr(request, 'user') and request.user.is_authenticated():
distinct_id = request.user.email
dt = datetime.datetime.utcnow()
if not hasattr(request, '_logging_uuid'):
request._logging_uuid = uuid.uuid1()
request._logging_start_dt = dt
else:
delta = int((dt - request._logging_start_dt).total_seconds() * 1000)
mp.track(distinct_id, 'Request', {
'id': str(request._logging_uuid),
'path': request.get_full_path(),
'duration (milliseconds)': delta,
'environment': 'development' if settings.DEBUG else 'production'
})
def process_request(self, request):
self.track_request(request)
def process_response(self, request, response):
s = getattr(response, 'status_code', 0)
r = str(s)
if s in (300, 301, 302, 307):
r += ' => %s' % response.get('Location', '?')
elif response.content:
r += ' (%db)' % len(response.content)
self.track_request(request)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment