SQL Log Middleware - with multiple databases

 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 7 years, 1 month ago
  2. Multi-DB Reconnecting Persistent Postgres Connection by cronosa 10 months ago
  3. Interactive Profiling Middleware by sfllaw 3 years, 9 months ago
  4. SQL Log To Console Middleware by davepeck 4 years, 8 months ago
  5. SQL Log Middleware + duplicates by guettli 6 years, 9 months ago

Comments

(Forgotten your password?)