Login

SQL Log Middleware w/query count & exec time

Author:
tobias
Posted:
April 7, 2007
Language:
Python
Version:
.96
Tags:
sql middleware log
Score:
6 (after 7 ratings)

This middleware will add a log of the SQL queries executed at the bottom of every page. It also includes a query count and total and per-query execution times.

 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

Comments

Baxter (on May 21, 2007):
<p>Is there some trick or dependency to this? Returns 0 for me. 0 queries, 0 seconds.</p>

#

guettli (on July 27, 2007):
<p>If you see no queries:</p> <p>You must set DEBUG=True in settings.py</p>

#

guettli (on July 27, 2007):
<p>I improved this snippet in Snippet 344.</p> <p>It counts duplicated SQL queries.</p>

#

alexkoval (on January 24, 2008):
<p>Since Unicode branch I've changed code at bottom to:</p> <pre>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 </pre>

#

parxier (on March 21, 2009):
<p>more pythonic time calculation:</p> <pre>time = sum([float(q['time']) for q in connection.queries]) </pre> <p>also this snippet doesn't work with JSON response content out of the box</p>

#

Please login first before commenting.