Log Django SQL Queries to Terminal

Sometimes you might need to be able to log Django SQL queries. You might want to print them to the terminal or send them to a remote logging system. In this example I show you how to create Django middleware which logs the SQL queries executed by HTTP session to the terminal.

db_sql_terminal_logging_middleware.py
 1from logging import getLogger
 2from system import stdout
 3
 4from django.conf import settings
 5from django.db import connection
 6
 7class SqlTerminalLogging:
 8    def __init__(self, get_reponse):
 9        self.logger = getLogger(__name__)
10        self.get_response = get_reponse
11
12    def __call__(self, request):
13        response = self.get_response(request)
14        if getattr(settings, "SQL_TERMINAL_LOGGING_SQL", settings.DEBUG):
15            self._log_queries()
16        return response
17
18    def _log_queries(self):
19        if stdout.isatty():
20            for query in connection.queries:
21                sql_str = " ".join(query["sql"].split())
22                self.logger.debug(
23                    f"\033[1;31m[{query['time']}s]\033[0m \033[1m{sql_str}\033[0m"
24                )

You can download the source from here.