Login

another request logging middleware with request time and extra info

Author:
yoav
Posted:
December 11, 2011
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

Simple logging middleware that captures the following: * remote address (whether proxied or direct) * if authenticated, then user email address * request method (GET/POST etc) * request full path * response status code (200, 404 etc) * content length * request process time * If DEBUG=True, also logs SQL query information - number of queries and how long they took

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import logging

class LoggingMiddleware(object):
    
    def process_request(self, request):
        self.start_time = time.time()

    def process_response(self, request, response):
        try:    
            remote_addr = request.META.get('REMOTE_ADDR')    
            if remote_addr in getattr(settings, 'INTERNAL_IPS', []):
                remote_addr = request.META.get('HTTP_X_FORWARDED_FOR') or remote_addr
            user_email = "-" 
            extra_log = ""
            if hasattr(request,'user'):
                user_email = getattr(request.user, 'email', '-')
            req_time = time.time() - self.start_time
            content_len = len(response.content)
            if settings.DEBUG:
                sql_time = sum(float(q['time']) for q in connection.queries) * 1000
                extra_log += " (%s SQL queries, %s ms)" % (len(connection.queries), sql_time)
            logging.info("%s %s %s %s %s %s (%.02f seconds)%s" % (remote_addr, user_email, request.method, request.get_full_path(), response.status_code, content_len, req_time, extra_log))
        except Exception, e:
            logging.error("LoggingMiddleware Error: %s" % e)
        return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

pflanno (on July 30, 2012):

needs following imports

from django.conf import settings
from django.db import connection

import logging
import time

#

juliocesar (on January 8, 2018):

This need to uprade in order to work in new Django versions https://docs.djangoproject.com/en/1.11/topics/http/middleware/#upgrading-middleware

#

Please login first before commenting.