Login

SQL Log Middleware - with multiple databases

Author:
guglielmocelata
Posted:
February 3, 2011
Language:
Python
Version:
Not specified
Tags:
sql middleware log multiple-databases
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. SQL Log Middleware by joshua 8 years ago
  2. Multi-DB Reconnecting Persistent Postgres Connection by cronosa 1 year, 8 months ago
  3. Interactive Profiling Middleware by sfllaw 4 years, 7 months ago
  4. SQL Log To Console Middleware by davepeck 5 years, 6 months ago
  5. SQL Log Middleware + duplicates by guettli 7 years, 7 months ago

Comments

Please login first before commenting.