2018-08-30 12:20:00+00:00

Introduction

Database access is the main bottleneck of a web app.

Many infrastructure related efforts are done to improve database access, such as using in memory database or replacing storage from hard disk to SDD.

My Programmer's mistakes when coding database access also greatly contribute to the severity level of this bottleneck problem.

Logging the executed database SQL is a great tool to help checking if our code must be improved or not.

Enabling SQL Logging in Django 2

Having these setting values is enough to make SQL executions to get logged.

Set DJANGO_LOG_LEVEL environment variable:

$ export DJANGO_LOG_LEVEL=DEBUG

Set django settings values:

import os

DEBUG = True
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
    },
}

Restart the app server.

Detecting N+1 Queries Automatically in Automated Tests

In addition to configuring django.db.backends SQL logging during local debugging, use assertNumQueries in your Django test suite to guarantee that adding related records never introduces hidden N+1 ORM queries. See more in Freelance Python & Django Programmer Guide.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs