"""Checkouts application middleware"""

import logging

logger = logging.getLogger('analytics')

class Analytics():
    """Tracks request details useful for analysis of usage patterns.
    
    To ensure that the name of the logged in user can be accessed, this
    middleware should come after Django's built-in AuthenticationMiddleware
    in the project settings.
    """
    
    def process_request(self, request):
        """Organizes info from each request and saves it to a log."""
        context = {
            'ip':        request.META['REMOTE_ADDR'],
            'method':    request.method,
            'path':      request.path,
            'user':      request.user.username,
            'useragent': request.META['HTTP_USER_AGENT'],
        }
        
        # Fall-back if the user is not recognized
        if not request.user.is_authenticated():
            context['user'] = 'anonymous'
        
        template = "%(user)s@%(ip)s: %(method)s %(path)s \"%(useragent)s\""
        logger.info(template % context)

@@ -47,16 +47,28 @@
  logging
+%0Aimport time
 %0A%0Alogger
@@ -397,23 +397,23 @@
 def 
-process
+collect
 _request
 (sel
@@ -408,16 +408,24 @@
 _request
+_details
 (self, r
@@ -448,32 +448,48 @@
  %22%22%22
-Organizes info
+Gathers information of interest
  from 
-each
+the
  req
@@ -501,25 +501,28 @@
 and 
-saves it to a log
+returns a dictionary
 .%22%22%22
@@ -942,32 +942,772 @@
 ymous'%0A        %0A
+        return context%0A    %0A    def process_request(self, request):%0A        %22%22%22Captures the current time and saves it to the request object.%22%22%22%0A        request._analytics_start_time = time.time()%0A    %0A    def process_response(self, request, response):%0A        %22%22%22Organizes info from each request/response and saves it to a log.%22%22%22%0A        context = self.collect_request_details(request)%0A        context%5B'status'%5D = response.status_code%0A        %0A        if not request._analytics_start_time:%0A            logger.error(%22Unable to provide timing data for request%22)%0A            context%5B'elapsed'%5D = -1.0%0A        else:%0A            elapsed = (time.time() - request._analytics_start_time) * 1000.0%0A            context%5B'elapsed'%5D = elapsed%0A        %0A
         template
@@ -1747,16 +1747,41 @@
 (path)s 
+%25(elapsed)fms %25(status)s 
 %5C%22%25(user
@@ -1831,8 +1831,41 @@
 ontext)%0A
+        %0A        return response%0A

Enhance analytics with timing and status code info