Skip to content

Instantly share code, notes, and snippets.

@daniestrella1
Forked from j4mie/middleware.py
Created November 13, 2017 22:04
Show Gist options
  • Save daniestrella1/869b664b08e11615f542814f39ca6f15 to your computer and use it in GitHub Desktop.
Save daniestrella1/869b664b08e11615f542814f39ca6f15 to your computer and use it in GitHub Desktop.
Django middleware to log the total number of queries run and query time for every request
from django.db import connection
import logging
logger = logging.getLogger(__name__)
class QueryCountDebugMiddleware(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.
"""
def process_response(self, request, response):
if response.status_code == 200:
total_time = 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
# Should be the first item in MIDDLEWARE_CLASSES.
# Only works in development.
# Try something like this in your settings.py:
if DEBUG:
MIDDLEWARE_CLASSES = ('path.to.middleware.QueryCountDebugMiddleware',) + MIDDLEWARE_CLASSES
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment