diff --git a/InvenTree/InvenTree/middleware.py b/InvenTree/InvenTree/middleware.py index 3a5c4f059f..c31a6e2b6d 100644 --- a/InvenTree/InvenTree/middleware.py +++ b/InvenTree/InvenTree/middleware.py @@ -1,5 +1,9 @@ from django.shortcuts import HttpResponseRedirect from django.urls import reverse_lazy +from django.db import connection +import logging + +logger = logging.getLogger(__name__) class AuthRequiredMiddleware(object): @@ -24,3 +28,40 @@ class AuthRequiredMiddleware(object): # the view is called. return response + + +class QueryCountMiddleware(object): + """ + This middleware will log the number of queries run + and the total time taken for each request (with a + status code of 200). It does not currently support + multi-db setups. + + Reference: https://www.dabapps.com/blog/logging-sql-queries-django-13/ + """ + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + + response = self.get_response(request) + + if response.status_code == 200: + total_time = 0 + + if len(connection.queries) > 0: + + for query in connection.queries: + query_time = query.get('time') + if query_time is None: + # django-debug-toolbar monkeypatches the connection + # cursor wrapper and adds extra information in each + # item in connection.queries. The query time is stored + # under the key "duration" rather than "time" and is + # in milliseconds, not seconds. + query_time = query.get('duration', 0) / 1000 + total_time += float(query_time) + + logger.debug('%s queries run, total %s seconds' % (len(connection.queries), total_time)) + return response diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index 164050d5ca..c6b8e88131 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -86,6 +86,9 @@ MIDDLEWARE = [ 'InvenTree.middleware.AuthRequiredMiddleware' ] +if DEBUG: + MIDDLEWARE.append('InvenTree.middleware.QueryCountMiddleware') + ROOT_URLCONF = 'InvenTree.urls' TEMPLATES = [ diff --git a/InvenTree/part/templates/part/part_base.html b/InvenTree/part/templates/part/part_base.html index 5e4f85d238..8470677487 100644 --- a/InvenTree/part/templates/part/part_base.html +++ b/InvenTree/part/templates/part/part_base.html @@ -85,25 +85,6 @@