pythonsqldjangologgingdjango-database

How to log all sql queries in Django?


How can I log all SQL queries that my django application performed?

I want to log everything, including SQLs from admin site. I saw this question and a FAQ answer but I still can't figure out where should I put

from django.db import connection
connection.queries

to log everything to one file?

So my question is - what should I do to have a file (say all-sql.log) where all SQL statements are logged?


Solution

  • Maybe check out https://github.com/django-debug-toolbar/django-debug-toolbar

    It'll let you see all the queries generated by a given page. As well as stacktraces of where they occur etc.

    EDIT: to log all SQL queries to a file etc, then you will want to create some middleware. Middleware gets run on every request. There are several Django snippets out there for this sort of thing:

    Those are concerned with printing to the terminal, but it wouldn't be hard to adapt them to use python's logging library.