Login

SQL Log Middleware - with multiple databases

Author:
guglielmocelata
Posted:
February 3, 2011
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

This is an improvement of joshua's SQL Log Middleware.

If you have more than one database connection, then all queries are logged, grouped by connection.

If a connection has no queries, then it's not shown.

 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
from django.db import connections
from django.template import Template, Context
from django.conf import settings

#
# Log all SQL statements direct to the console (when running in DEBUG)
# Intended for use with the django development server.
#

class SQLLogToConsoleMiddleware(object):
    def process_response(self, request, response): 
      if settings.DEBUG:
        for connection_name in connections:
          connection = connections[connection_name]
          if connection.queries:
            time = sum([float(q['time']) for q in connection.queries])        
            header_t = Template("{{name}}: {{count}} quer{{count|pluralize:\"y,ies\"}} in {{time}} seconds")
            print header_t.render(Context({
              'name': connection_name, 
              'sqllog':connection.queries,
              'count':len(connection.queries),
              'time':time
            }))
            t = Template("{% for sql in sqllog %}[{{forloop.counter}}] {{sql.time}}s: {{sql.sql|safe}}{% if not forloop.last %}\n\n{% endif %}{% endfor %}")
            print t.render(Context({'sqllog':connection.queries}))                
      return response

More like this

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

Comments

Please login first before commenting.