← Back to Django, page 4

django-0066 · Easy fresher

How do you configure logging in Django with the LOGGING setting, and which loggers does Django itself use?

Django uses Python's logging module and applies the LOGGING dictionary (dictConfig format) at startup. A configuration names formatters, handlers (where records go), and loggers (which code emits them, with levels). Django emits to loggers such as django.request (4xx and 5xx), django.db.backends (SQL, DEBUG only) and django.security, and your code should use logging.getLogger(__name__).

Full answer

Four ideas: logger (named source), level (DEBUG, INFO, WARNING, ERROR, CRITICAL), handler (destination: console, file, email, external service) and formatter (layout).

python
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {"plain": {"format": "{levelname} {name} {message}", "style": "{"}},
    "handlers": {"console": {"class": "logging.StreamHandler", "formatter": "plain"}},
    "loggers": {"school": {"handlers": ["console"], "level": "INFO"}},
    "root": {"handlers": ["console"], "level": "WARNING"},
}

Key points:

  • Always "version": 1 and, normally, "disable_existing_loggers": False (otherwise libraries' loggers go silent).
  • In modules: logger = logging.getLogger(__name__) and logger.info("Fee paid", extra=...). Use lazy formatting (logger.info("paid %s", amount)), and logger.exception("...") inside except to include the traceback.
  • Django loggers: django (parent), django.request (a warning for 4xx, an error for 5xx), django.server (runserver lines), django.template, django.db.backends (every query at DEBUG, only when DEBUG=True), django.security.*.
  • By default Django sends error logs to admins by email with AdminEmailHandler only when DEBUG=False, and to the console when DEBUG=True.
  • In containers write to stdout and let the platform collect it; use structured (JSON) formatters for searching.
  • Never log passwords, tokens or full personal records.
  • Set levels by environment through the settings, e.g. os.environ.get("LOG_LEVEL", "INFO").
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    LOGGING={
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {"plain": {"format": "{levelname} {name}: {message}", "style": "{"}},
        "handlers": {"console": {"class": "logging.StreamHandler", "stream": "ext://sys.stdout", "formatter": "plain"}},
        "loggers": {"school": {"handlers": ["console"], "level": "INFO"},
                    "django.request": {"handlers": ["console"], "level": "WARNING", "propagate": False}},
    },
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import logging

from django.http import HttpResponse
from django.test import Client
from django.urls import path

logger = logging.getLogger("school.fees")


def pay(request):
    logger.info("Fee received for %s", request.GET.get("roll_no"))
    logger.debug("this DEBUG line is below the INFO threshold")
    try:
        1 / 0
    except ZeroDivisionError:
        logger.warning("Could not compute late fee", exc_info=False)
    return HttpResponse("ok")


urlpatterns = [path("pay/", pay)]

c = Client()
c.get("/pay/?roll_no=BCA-17")
c.get("/missing/")                                       # django.request logs the 404 as a warning

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): INFO school.fees: Fee received for BCA-17 WARNING school.fees: Could not compute late fee WARNING django.request: Not Found: /missing/

Key points

  • LOGGING is dictConfig: formatters, handlers, loggers
  • Use getLogger(__name__) in your modules
  • disable_existing_loggers should normally be False
  • django.request logs 4xx and 5xx responses
  • Log to stdout in containers; never log secrets

Common mistakes

  • Leaving disable_existing_loggers at its default of True
  • Using print() instead of logging in server code
  • Formatting messages with f-strings that run even when the level is disabled
  • Logging secrets, tokens or full request bodies

Follow-ups

  • How do you add a request ID to every log line?
  • How do you send errors to Sentry or a similar tool?
  • What does django.db.backends log, and when?

Tips

  • Define logger, handler, formatter
  • Name the Django loggers
  • Mention stdout in containers