30

Django logs SQL operations to an internal buffer (whether logging to file or not) when settings.DEBUG=True. Because I have long-running process that does a lot of DB operations, this causes my development-mode instances of the program to grow in memory consumption very quickly.

I would like to disable the internal SQL logging mechanism while leaving settings.DEBUG turned on for my development: is this possible?

Django version 1.3.0.

5 Answers 5

45

Yes, you can quiet the sql logging down by assigning a 'null handler' to the logger named 'django.db.backends'. I assume you use django's new dict-based logging setup? If so, this snippet ought to make it easy:

    ...
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class':'logging.NullHandler',
            },
    ...
    'loggers': {
        ... your regular logger 'root' or '' ....
        'django.db.backends': {
            'handlers': ['null'],  # Quiet by default!
            'propagate': False,
            'level':'DEBUG',
            },
    ...

Update: look at Brian's answer, too. I understood "logging" to mean the irritating logging of every sql statement. Brian talks about the internal memory logging of every query (and I guess he's right :-)

3
  • great answer, this is much easier and addresses the most common issue of log files in DEBUG=True mode being clogged up with SQL statements.
    – RichVel
    Commented Jan 1, 2013 at 21:10
  • The Django version I am using (1.9) - instead of 'handlers':['null'] I replaced with None so 'handlers':None Commented Jun 30, 2016 at 15:09
  • 2
    in versions of Django >= 1.9, django.utils.log.NullHandler no longer exists. Use logging.NullHandler instead.
    – lsh
    Commented Nov 25, 2016 at 10:18
25

When settings.DEBUG is True, Django uses CursorDebugWrapper instead of CursorWrapper. This is what appends the queries to connection.queries and consumes memory. I would monkey-patch the connection wrapper to always use CursorWrapper:

from django.conf import settings
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.utils import CursorWrapper

if settings.DEBUG:
    BaseDatabaseWrapper.make_debug_cursor = lambda self, cursor: CursorWrapper(cursor, self)

Place this in some file that gets imported early in your application.

Disabling logging like others suggest won't fix the problem, because CursorDebugWrapper still stores the queries in connection.queries even if logging is off.

3
  • 12
    Where does this go? If I add this to settings.py I get the following ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. when trying to execute from django.db.backends import BaseDatabaseWrapper.
    – Nathan
    Commented Jan 31, 2012 at 15:34
  • 2
    In recent versions of Django, import paths have changed: from django.db.backends.base.base import BaseDatabaseWrapper and from django.db.backends.utils import CursorWrapper
    – bbmhmmad
    Commented Nov 19, 2019 at 20:45
  • I have the same question as @Nathan. Where this configuration should be placed? Also, as bbmhmmad said, for recent versions it seems to be outdated. Commented Mar 21, 2022 at 13:35
5

This worked for me (at least for Django 1.3.1):

from django.db import connection
connection.use_debug_cursor = False

I've found that variable inspecting Django source code (it is not documented), the relevant lines are found in django/db/backends/__init__.py (BaseDatabaseWrapper class):

def cursor(self):
    if (self.use_debug_cursor or
        (self.use_debug_cursor is None and settings.DEBUG)):
        cursor = self.make_debug_cursor(self._cursor())
    else:
        cursor = util.CursorWrapper(self._cursor(), self)
    return cursor
3

If still interested in tracing SQL operations for debugging purposes, you can also clean connection.queries list periodically to reclaim memory:

from django.db import connection

for i in range(start, count, size):
    objects = MyModel.objects.order_by('pk').all()[i:i + size]
    ...
    print connection.queries
    connection.queries = []
0

Django 3.0.7

Change

def queries_logged(self):
    self.force_debug_cursor or settings.DEBUG

to

def queries_logged(self):
    return False

in django/db/backends/base/db.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.