Frameworks 11 min read

Django logging: the LOGGING setting, JSON logs and trace IDs

How to configure the LOGGING setting, what Django logs on its own, and how to get JSON lines with a request ID and a trace ID out of a production app. Tested with Django 6.1 and OpenTelemetry 1.45 (November 2026).

David Granzin By David Granzin

Django uses Python's standard logging module and adds two things: a LOGGING setting that it hands to logging.config.dictConfig at startup, and a set of loggers under the django name. Most problems come from how those defaults merge with your config.

New to log levels? Start with Python logging levels.

A working LOGGING config

Paste this into settings.py. It needs no extra package and prints your logs and Django's to the console in one format, with DEBUG on or off:

settings.py

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "plain": {
            "format": "{asctime} {levelname} {name} {message}",
            "style": "{",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "plain",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "INFO",
    },
    "loggers": {
        # Naming "django" drops its default handlers, so each
        # record is written once, by the root handler.
        "django": {"level": "INFO"},
        "shop": {"level": "DEBUG"},
    },
}

Replace shop with your app's package name. A request, an unhandled exception and a 404 then print:

2026-11-29 00:28:01,469 DEBUG shop.views cart loaded
2026-11-29 00:28:01,469 INFO shop.views order placed
2026-11-29 00:28:01,472 INFO django.server "GET /checkout/ HTTP/1.1" 200 24
2026-11-29 00:28:01,504 ERROR django.request Internal Server Error: /boom/
Traceback (most recent call last):
  ...
RuntimeError: unhandled
2026-11-29 00:28:01,517 WARNING django.request Not Found: /nope/

Key takeaways

  • Without a root handler, logger.info() in your app goes nowhere.
  • Always set "disable_existing_loggers": False. The default silences django.request.
  • With DEBUG = False and no LOGGING, unhandled exceptions are not printed anywhere.
  • SQL query logging needs DEBUG = True, whatever the logger level is.

What Django logs by default

With no LOGGING setting, Django applies django.utils.log.DEFAULT_LOGGING. It covers the django logger only, and it changes with DEBUG:

RecordDEBUG = TrueDEBUG = False
django.* at INFO and abovePrinted to the consoleNot printed
django.* at ERRORPrinted to the consoleEmailed to ADMINS by mail_admins
django.server request linesPrinted, but only under runserver
Your loggers, INFO and DEBUGDropped
Your loggers, WARNING and abovePrinted to stderr as the bare message, with no timestamp or level
  • Your logger.info() calls vanish. The root logger has no handler, and Python's last-resort handler prints WARNING and above only.
  • Production 500s are silent. With DEBUG = False the only handler for errors sends email, and with ADMINS empty it sends nothing. In a test, a view that raised returned a 500 and the process wrote nothing about it.

The LOGGING setting

LOGGING is a dictConfig dictionary that Django applies on top of its defaults. A record travels from the logger that created it up to the root, and every handler on the way writes it:

One handler, on the root. Each record is written once, in one format.

  • version is always 1, and it is required.
  • loggers sets a level, and optionally handlers, per logger name. Names are hierarchical: shop covers shop.views and shop.models. Records move up to each parent's handlers while propagate is true.
  • root is the parent of every logger, third-party libraries included. Its level applies to loggers that set none.
  • handlers decide where a record goes. logging.StreamHandler writes to stderr unless you pass "stream": "ext://sys.stdout". A handler can have its own level and filters.
  • formatters turn a record into text. "style": "{" selects str.format placeholders; the default is %(name)s style.
  • filters drop a record or add attributes to it, as the request ID and trace ID sections do.

Name django in loggers, even with a level only. dictConfig replaces the handlers of every logger you name and resets its children, so Django's default console and email handlers go away and django.server propagates to the root like everything else. Leave django out and the defaults stay next to your root handler, which causes duplicated lines.

For admin emails, add a handler with "class": "django.utils.log.AdminEmailHandler" at level ERROR yourself.

disable_existing_loggers

dictConfig treats a missing disable_existing_loggers as True. Every existing logger that is neither named in your config nor a child of a named logger is disabled and drops records silently. Django's own loggers exist before your config is applied.

With that key removed from a root-only config, django.request was disabled: a view raised, the client got a 500, and no traceback was logged. Under runserver the app's own loggers went silent too. Always set it to False.

Log to a file

In containers, log to the console. On a server where nothing captures stderr, add a rotating file handler. A level read from the environment turns on DEBUG for one deploy without a code change:

settings.py

import os

LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "INFO")

LOGGING = {
    # version, formatters and loggers as above
    "handlers": {
        "console": {"class": "logging.StreamHandler", "formatter": "plain"},
        "file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": BASE_DIR / "logs" / "django.log",
            "maxBytes": 10 * 1024 * 1024,  # rotate at 10 MB
            "backupCount": 5,  # keep django.log.1 to django.log.5
            "formatter": "plain",
        },
    },
    "root": {"handlers": ["console", "file"], "level": LOG_LEVEL},
}
  • The directory must exist. With logs/ missing, Django refused to start with ValueError: Unable to configure handler 'file'.
  • One process per file. RotatingFileHandler is not safe when several Gunicorn workers write the same file. Log to stderr instead, or use logging.handlers.WatchedFileHandler with logrotate.

Logging from your apps

Create one logger per module with logging.getLogger(__name__). The name follows the import path, so a single "shop" entry in LOGGING controls the whole app.

shop/views.py

import logging

from django.http import JsonResponse

logger = logging.getLogger(__name__)  # "shop.views"


def checkout(request):
    logger.debug("cart loaded")
    logger.info("order placed", extra={"order_id": 1042, "total": 59.9})
    return JsonResponse({"ok": True})


def refund(request):
    try:
        charge_back()
    except PaymentError:
        # Logs at ERROR and appends the traceback.
        logger.exception("refund failed")
        raise
  • Pass values, not formatted strings. logger.info("order %s placed", order_id) formats only if a handler wants the record, and keeps the message constant for grouping.
  • Put data in extra. The keys become attributes on the record. A plain formatter ignores them; a JSON formatter writes them as fields.
  • Use logger.exception inside except. It logs at ERROR with the traceback. Logging and re-raising at every layer gives you one traceback per layer.
  • Do not call logging.basicConfig(). LOGGING owns the configuration. basicConfig adds a second root handler or does nothing, depending on import order.

Django's built-in loggers

These are the names to set levels on when you want more or less from Django itself:

LoggerWhat it logs
djangoParent of everything below. Nothing logs to it directly.
django.request5xx responses at ERROR with the traceback, 4xx responses at WARNING (Not Found: /nope/). Records carry status_code and request.
django.serverOne line per request from the development server. It does not exist under Gunicorn or uWSGI.
django.db.backendsEvery SQL statement at DEBUG, with duration, parameters and database alias.
django.security.*SuspiciousOperation errors such as DisallowedHost, and CSRF failures on django.security.csrf.
django.templateMissing template variables at DEBUG.
django.utils.autoreloadFile change detection in the development server.

Bots probing random paths produce a stream of django.request warnings and DisallowedHost errors. Quiet them per logger, for example "django.security.DisallowedHost": {"level": "CRITICAL"}, not by raising the root level.

Log SQL queries

Set django.db.backends to DEBUG:

settings.py

"loggers": {
    "django": {"level": "INFO"},
    "django.db.backends": {"level": "DEBUG"},
},
2026-11-29 00:25:37,583 DEBUG django.db.backends (0.000) SELECT COUNT(*) AS "__count" FROM "auth_user"; args=(); alias=default

This only works with DEBUG = True. Django wraps the database cursor for logging only in debug mode, so with DEBUG = False the same config printed no SQL. Logging every statement with its parameters is slow and leaks user data.

In production, set connection.force_debug_cursor = True around one code path, or use database spans from tracing, which record the statement and duration without the parameters.

JSON logs

A log pipeline parses JSON lines without a custom pattern, and a traceback stays inside one record. The usual formatter is python-json-logger:

pip install python-json-logger

settings.py

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "json": {
            "()": "pythonjsonlogger.json.JsonFormatter",
            "format": "%(asctime)s %(levelname)s %(name)s %(message)s",
            "rename_fields": {
                "asctime": "timestamp",
                "levelname": "level",
                "name": "logger",
            },
        },
    },
    "handlers": {
        "console": {"class": "logging.StreamHandler", "formatter": "json"},
    },
    "root": {"handlers": ["console"], "level": "INFO"},
    "loggers": {
        "django": {"level": "INFO"},
    },
}
{"timestamp": "2026-11-29 00:25:46,708", "level": "INFO", "logger": "shop.views", "message": "order placed", "order_id": 1042, "total": 59.9}
{"timestamp": "2026-11-29 00:25:46,733", "level": "WARNING", "logger": "django.request", "message": "Not Found: /nope/", "request": "<WSGIRequest: GET '/nope/'>", "status_code": 404}
  • The import path moved. Use pythonjsonlogger.json.JsonFormatter. The pythonjsonlogger.jsonlogger path from older tutorials still imports but raises a DeprecationWarning.
  • "()" is a factory. dictConfig calls that class with the remaining keys as arguments.
  • format selects the standard fields. Anything passed through extra, such as order_id, is added on its own. Tracebacks land in exc_info as one string.
  • Django adds extras too, such as status_code and a stringified request on django.request lines.

Loguru also writes JSON, but Django keeps logging through the standard module, so you still need this config or an intercept handler.

Request IDs

An ID on every record lets you pull up all the lines one request produced. A middleware stores the ID in a ContextVar and a logging filter copies it onto records, so no view has to pass anything.

mysite/logctx.py

import logging
import uuid
from contextvars import ContextVar

from django.core.signals import request_finished

request_id_var: ContextVar[str] = ContextVar("request_id", default="-")


class RequestIdMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Reuse the proxy's ID when there is one.
        rid = request.headers.get("X-Request-ID") or uuid.uuid4().hex
        request_id_var.set(rid)
        response = self.get_response(request)
        response["X-Request-ID"] = rid
        return response


def clear_request_id(sender, **kwargs):
    request_id_var.set("-")


# Fires when the response is closed, after Django has logged it.
request_finished.connect(clear_request_id)


class RequestIdFilter(logging.Filter):
    def filter(self, record):
        record.request_id = request_id_var.get()
        return True

settings.py

MIDDLEWARE = [
    "mysite.logctx.RequestIdMiddleware",  # first, so it wraps everything
    "django.middleware.security.SecurityMiddleware",
    # ...
]

LOGGING = {
    # version, formatters and root as above
    "filters": {
        "request_id": {"()": "mysite.logctx.RequestIdFilter"},
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "json",
            "filters": ["request_id"],
        },
    },
}

Put the filter on the handler. A logger's filters do not run for records that propagate up from its children, so a filter on the root logger misses nearly everything. With a plain formatter, add {request_id} to the format string.

The ID is cleared on the request_finished signal, not in a finally block in the middleware, because Django and Gunicorn write two more lines after the middleware returns:

Without any reset, the ID stays on the worker thread and shows up on unrelated lines such as Worker exiting.

Trace IDs with OpenTelemetry

A trace ID does across services what a request ID does in one process, and links each line to its span. The Django instrumentation creates a span per request, and the logging instrumentation connects records to it.

pip install opentelemetry-distro opentelemetry-exporter-otlp-proto-http \
  opentelemetry-instrumentation-django opentelemetry-instrumentation-logging

To print the IDs on the console, add a filter that reads the active span. It needs only the OpenTelemetry API, so it is safe when the SDK is not running, such as in manage.py migrate:

mysite/tracectx.py

import logging

from opentelemetry import trace


class TraceContextFilter(logging.Filter):
    def filter(self, record):
        ctx = trace.get_current_span().get_span_context()
        if ctx.is_valid:
            record.trace_id = format(ctx.trace_id, "032x")
            record.span_id = format(ctx.span_id, "016x")
        return True

settings.py

"filters": {
    "request_id": {"()": "mysite.logctx.RequestIdFilter"},
    "trace_context": {"()": "mysite.tracectx.TraceContextFilter"},
},
"handlers": {
    "console": {
        "class": "logging.StreamHandler",
        "formatter": "json",
        "filters": ["request_id", "trace_context"],
    },
},

Then start the server through the agent. The same agent and env vars work for FastAPI:

export DJANGO_SETTINGS_MODULE=mysite.settings
export OTEL_SERVICE_NAME=shop
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf

opentelemetry-instrument gunicorn mysite.wsgi
{"timestamp": "2026-11-29 00:28:20,237", "level": "INFO", "logger": "shop.views", "message": "order placed", "order_id": 1042, "total": 59.9, "request_id": "23e989e477854987867275eeaac3fae8", "trace_id": "cf9a0fd1a382aeab6a1cd543e4d72cee", "span_id": "bf05db654265e1b5"}

The agent also adds its own handler to the root logger, which exports every record over OTLP. One record now takes two paths:

Both handlers sit on the root logger, so a logger with "propagate": False reaches neither.

Printed with the console exporter (OTEL_LOGS_EXPORTER=console), the exported record looks like this:

{
    "body": "order placed",
    "severity_number": 9,
    "severity_text": "INFO",
    "attributes": {
        "order_id": 1042,
        "total": 59.9,
        "request_id": "23e989e477854987867275eeaac3fae8"
    },
    "timestamp": "2026-11-29T00:28:20.237739Z",
    "trace_id": "0xcf9a0fd1a382aeab6a1cd543e4d72cee",
    "span_id": "0xbf05db654265e1b5",
    "trace_flags": 3,
    "resource": {
        "attributes": {
            "service.name": "shop"
        }
    }
}

What is specific to Django:

  • Export DJANGO_SETTINGS_MODULE. The agent reads your middleware list before manage.py or wsgi.py sets the variable. Without it runserver failed with You must set settings.ALLOWED_HOSTS if DEBUG is False.
  • runserver works with its autoreloader. Older guides pass --noreload. With 0.66b2, plain manage.py runserver produced spans and exported logs from the reloaded child process.
  • The handler survives your LOGGING. The instrumentation wraps dictConfig and adds its handler back afterwards.
  • Silence one warning. django.request records carry the request object, so the exporter warns Invalid type WSGIRequest for attribute value. Add "opentelemetry.attributes": {"level": "ERROR"} to loggers.
  • Export less than you print. OTEL_PYTHON_LOG_HANDLER_LEVEL=warning exports WARNING and above while the console keeps INFO.

As of November 2026 the instrumentation no longer stamps otelTraceID and otelSpanID on records by default. OTEL_PYTHON_LOG_CORRELATION=true turns that on, but it also calls logging.basicConfig(), so the filter above is the more predictable choice in a Django project.

  • Sampling does not drop logs. A record from an unsampled request is still exported, with a trace ID that has no stored trace. See sampling.
  • Traces cross services through a header. The caller has to send traceparent. See context propagation.
  • A Collector can do the export. Log JSON to stdout and let an OpenTelemetry Collector parse it. The trace_id field makes the join work.

Gunicorn

Gunicorn has two loggers of its own, each with a handler and propagate off, so your Django config does not touch them unless you name them:

  • gunicorn.error writes startup, worker lifecycle and worker crash messages to stderr. Despite the name, most of it is INFO.
  • gunicorn.access writes one line per request, and is off until you pass --access-logfile -. Since django.server only exists in runserver, this is your only per-request line in production.

Your app's logs need no Gunicorn setting. To get the Gunicorn lines in the same JSON format, name both loggers in LOGGING:

settings.py

"loggers": {
    "django": {"level": "INFO"},
    "gunicorn.error": {"handlers": ["console"], "level": "INFO", "propagate": False},
    "gunicorn.access": {"handlers": ["console"], "level": "INFO", "propagate": False},
},
[2026-11-29 01:27:07 +0100] [71390] [INFO] Listening at: http://127.0.0.1:8000 (71390)
[2026-11-29 01:27:07 +0100] [71392] [INFO] Booting worker with pid: 71392
{"timestamp": "2026-11-29 00:27:10,987", "level": "INFO", "logger": "shop.views", "message": "order placed", "order_id": 1042, "total": 59.9, "request_id": "req-abc123"}
{"timestamp": "2026-11-29 00:27:10,988", "level": "INFO", "logger": "gunicorn.access", "message": "127.0.0.1 - - [29/Nov/2026:00:27:10 +0000] \"GET /checkout/ HTTP/1.1\" 200 24 \"-\" \"curl/8.7.1\"", "request_id": "req-abc123"}
  • Master lines keep Gunicorn's format. Django's settings load in the workers. If every line has to be JSON, configure Gunicorn itself with logconfig_dict in gunicorn.conf.py.
  • The access line carries the request ID. The worker logs it on the request's thread before the response is closed.
  • Forking needs no hook. Under opentelemetry-instrument gunicorn mysite.wsgi the SDK restarts its export threads in each forked worker. That held with --preload and two workers.
  • SIGTERM flushes. A request made 0.3 seconds before the signal still had its span and log exported, although the batch delay is 5 seconds. A worker killed with SIGKILL, for example after --graceful-timeout, loses its last batch.

Common problems

Four symptoms, each with the cause found in the test project.

Logs not showing

Check in this order:

  1. No handler. Without a root entry, INFO records are dropped.
  2. Level too high. A record must pass the logger's level and then the handler's level. A root level of WARNING hides logger.info() even with a DEBUG handler.
  3. disable_existing_loggers is missing or True. Check with logging.getLogger("django.request").disabled in manage.py shell.
  4. The name does not match. getLogger(__name__) in shop/views.py is shop.views. A config entry for myproject.shop does not cover it.
  5. A typo in the config. dictConfig raises on unknown handler or formatter names, but an unknown logger name is accepted and never used.

Duplicated lines

A record reached two handlers that write to the same place. With a root handler and no django entry, Django's default console handler stays attached in debug mode, and a 404 prints twice:

Not Found: /nope/
2026-11-29 00:25:28,412 WARNING django.request Not Found: /nope/

The other cause is the same handler on a logger and on the root. "shop": {"handlers": ["console"]} plus a root console handler printed every shop.views line twice. Attach handlers at the root only, or set "propagate": False on the logger that has its own.

SQL logs missing

django.db.backends at DEBUG prints nothing when DEBUG = False. See Log SQL queries.

Errors missing in production

A 500 with no traceback means django.request has no working handler: there is no LOGGING, or disable_existing_loggers disabled the logger. The config at the top fixes both. For per-request lines, turn on the Gunicorn access log.

Send it to Maple

The setup from the trace ID section works with the endpoint and header changed. Logs arrive with their trace and span IDs and open next to the request's trace. The Python instrumentation guide covers the rest.

export OTEL_SERVICE_NAME="shop"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
The Logs page in Maple filtered to WARN: a list of payment-svc log lines reading pool exhausted, with severity and service filters beside the list.
Exported Django records land here, filterable by severity and by the service.name you set.

Sources and further reading

FAQ

Common questions

What is the best way to log in Django?
Create one logger per module with logging.getLogger(__name__) and configure everything in the LOGGING setting. Put a single console handler on the root logger, set disable_existing_loggers to False, and name the django logger with a level only so each record is written once. In production, switch the formatter to JSON and add a request ID or trace ID through a logging filter.
How do I log to a file in Django?
Add a handler with the class logging.handlers.RotatingFileHandler to LOGGING, give it a filename, maxBytes and backupCount, and list it on the root logger. The directory must already exist, or Django fails at startup with ValueError: Unable to configure handler. With several Gunicorn workers, log to stderr or use WatchedFileHandler with logrotate, because RotatingFileHandler is not safe across processes.
Where do Django logs go by default?
To the console (stderr), and only partly. With DEBUG = True, Django prints records from the django logger at INFO and above. With DEBUG = False it prints nothing from django and instead emails ERROR records to ADMINS, which does nothing unless ADMINS and an email backend are set. Your own loggers have no handler until you add one in LOGGING.
How do I configure logging in Django settings.py?
Set LOGGING to a dictConfig dictionary: version 1, disable_existing_loggers False, a formatter, a console handler, and a root logger with that handler at INFO. Django passes the dictionary to logging.config.dictConfig when it starts.
Why are my Django logs not showing up?
Usually no handler receives them. Without a root handler in LOGGING, logger.info() from your app is dropped and only WARNING and above reach stderr. The other common causes are disable_existing_loggers left at its default of True, and a logger level higher than the level you are logging at.
How do I log SQL queries in Django?
Set the django.db.backends logger to DEBUG. It only produces records when DEBUG = True, or when you set connection.force_debug_cursor = True, because Django only wraps the database cursor for logging in those cases.
Should disable_existing_loggers be True or False in Django?
False. With True, which is the dictConfig default when the key is missing, every logger that exists and is not named in your config is disabled. That includes django.request, so unhandled exceptions stop being logged.
How do I get JSON logs from Django?
Install python-json-logger and point a formatter at pythonjsonlogger.json.JsonFormatter using the "()" key in LOGGING. Fields passed with extra= become JSON keys. The older import path pythonjsonlogger.jsonlogger still works but emits a deprecation warning.

See your first trace today.

Add the SDK, point your OTLP exporter at Maple, and traces arrive.

maple.dev: observability on OpenTelemetry