Login

logging tastypie middleware

Author:
lalutium
Posted:
November 7, 2014
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

This middleware logs request made through tastypie "/api" endpoints

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# coding=utf-8

import datetime
import logging
logger = logging.getLogger('backend')

from django.views.debug import CLEANSED_SUBSTITUTE
from django.conf import settings
from django.db import connection
from tastypie.serializers import Serializer

import time

class ResponseLoggingMiddleware(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)

            if request.path.startswith('/api/'):
                try:
                    s = Serializer()
                    if request.method == 'POST':
                        body = s.deserialize(request.body, 'application/json')
                    elif request.method == 'PUT':
                        body = s.deserialize(request.body, 'application/json')
                    elif request.method == 'GET':
                        body = ""
                except Exception, e:
                    logging.error("Deserialization error: %s" % e)
            else:
                body = ""
            logger.info("%s %s %s %s %s %s %s (%.02f seconds)%s" % (remote_addr, user_email, request.method, request.get_full_path(), body, response.status_code, content_len, req_time, extra_log))
        except Exception, e:
            logger.error("LoggingMiddleware Error: %s" % e)
        return response

More like this

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

Comments

Please login first before commenting.