Django SQL Tracing Middleware

here are a number of tools within the Django framework itself as well as he community for inspecting all of the SQL [Django]( is executing. The [Debug Toolbar]( has be come the defacto standard in that respect. However, most all, if not all of the usual suspects are relying on template tags and rendered html templates / javascript to read the debug information. All fine and good, unless you are building an ajax application that never renders html or makes use of the template hooks.

The simple solution to this problem is to write a middleware class to spit out the sql generated by the database connection for the current request. And of course some color coding to make it look a little easier to read.

from django.db import connection 
from django.conf import settings
from sys import stdout

# mapping of ansi escape sequences

# the middleware class
class TerminalLoggingMiddleware:
    def process_response(self, request, response):
        if settings.DEBUG and stdout.isatty():
            for query in connection.queries :
                _sql = query["sql"]
                _sql = [ KEYWORDS["time"] % query["time"] ] + _sql.split( )
                for index, item in enumerate( _sql ):
                    if KEYWORDS.has_key( item ):
                         _sql[index] = KEYWORDS[item] % item
                         _sql[index] = KEYWORDS["text"] % item
                print u" ".join( _sql)
        return response

Obviously a pretty quick and dirty solution. It will only print out to the terminal if Django is in DEBUG mode and python has detected a device that supports terminal output. I was having a bit of trouble with string formatting and the ANSI escape chars and unicode - so keyword mapping just seemed to be the most simple and direct route. Quick, Dirty, and Insanely helpful.

django ansi tracing middleware sql