Login

LogViewTimeMiddleware

Author:
majgis
Posted:
July 13, 2012
Language:
Python
Version:
1.4
Score:
1 (after 1 ratings)

Middleware for logging view execution time

 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
50
51
52
53
54
55
56
57
58
class LogViewTimeMiddleware(object):
  LOG_MSG = '{0}\t{1}'
 
  def process_view(self, request, view_func, view_args, view_kwargs):
    request.start_time = datetime.datetime.now()

  def process_response(self, request, response):
    
    msg = self._GetResponseTimeMsg(request)
    logger = logging.getLogger('view_time')
    logger.info(msg)
      
    return response
    
  def _GetResponseTimeMsg(self, request):
    
    msg = None
    
    if hasattr(request, 'start_time'):
      
      end_time = datetime.datetime.now()
      start_time = request.start_time
      delta_time = end_time - start_time
      request_path = request.get_full_path()
      
      msg = self.LOG_MSG.format(request_path, delta_time)
      
    return msg


#######################
# settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'date_tab_msg':{
            'format': '%(asctime)s\t%(message)s'
        }
    },
    'handlers': {
        'view_time':{
            'level':'INFO',
            'class':'logging.handlers.RotatingFileHandler',
            'formatter':'date_tab_msg',
            'filename':'view.time.log',
            'maxBytes':10**9,
            'backupCount':2
        }
    },
    'loggers': {
        'view_time':{
            'handlers':['view_time'],
            'level': 'INFO'
        }
    }
}

More like this

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

Comments

Please login first before commenting.