SQL Log Middleware w/query count & exec time

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.db import connection
from django.template import Template, Context

class SQLLogMiddleware:

    def process_response ( self, request, response ): 
        time = 0.0
        for q in connection.queries:
		time += float(q['time'])
        
        t = Template('''
            <p><em>Total query count:</em> {{ count }}<br/>
            <em>Total execution time:</em> {{ time }}</p>
            <ul class="sqllog">
                {% for sql in sqllog %}
                    <li>{{ sql.time }}: {{ sql.sql }}</li>
                {% endfor %}
            </ul>
        ''')

        response.content = "%s%s" % ( response.content, t.render(Context({'sqllog':connection.queries,'count':len(connection.queries),'time':time})))
        return response

More like this

  1. SQLLoggerMidleware + infobar by robvdl 5 years, 5 months ago
  2. SQL Log Middleware by joshua 6 years, 3 months ago
  3. DebugFooter middleware with textmate links by crucialfelix 4 years, 9 months ago
  4. DebugFooter middleware by simon 5 years ago
  5. DebugMiddleware footer with links to quick open file/line# in TextMate on local machine by felix_the_third 3 years, 5 months ago

Comments

Baxter (on May 21, 2007):

Is there some trick or dependency to this? Returns 0 for me. 0 queries, 0 seconds.

#

guettli (on July 27, 2007):

If you see no queries:

You must set DEBUG=True in settings.py

#

guettli (on July 27, 2007):

I improved this snippet in Snippet 344.

It counts duplicated SQL queries.

#

alexkoval (on January 24, 2008):

Since Unicode branch I've changed code at bottom to:

content = response.content.decode('utf-8')
content += t.render(Context({'sqllog':connection.queries,'count':len(connection.queries),'time':time}))
response.content = content.encode('utf-8')
return response

#

parxier (on March 21, 2009):

more pythonic time calculation:

time = sum([float(q['time']) for q in connection.queries])

also this snippet doesn't work with JSON response content out of the box

#

davepeck (on August 6, 2009):

I made a variation on this that logs to console, rather than appending SQL queries to the response. My snippet uses 'print' so it is only really useful when running manage.py runserver.

It is Snippet 1672.

#

(Forgotten your password?)