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 silencesdjango.request. - With
DEBUG = Falseand noLOGGING, 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:
| Record | DEBUG = True | DEBUG = False |
|---|---|---|
django.* at INFO and above | Printed to the console | Not printed |
django.* at ERROR | Printed to the console | Emailed to ADMINS by mail_admins |
django.server request lines | Printed, but only under runserver | |
| Your loggers, INFO and DEBUG | Dropped | |
| Your loggers, WARNING and above | Printed 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 = Falsethe only handler for errors sends email, and withADMINSempty 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.
versionis always1, and it is required.loggerssets a level, and optionally handlers, per logger name. Names are hierarchical:shopcoversshop.viewsandshop.models. Records move up to each parent's handlers whilepropagateis true.rootis the parent of every logger, third-party libraries included. Its level applies to loggers that set none.handlersdecide where a record goes.logging.StreamHandlerwrites to stderr unless you pass"stream": "ext://sys.stdout". A handler can have its ownlevelandfilters.formattersturn a record into text."style": "{"selectsstr.formatplaceholders; the default is%(name)sstyle.filtersdrop 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 withValueError: Unable to configure handler 'file'. - One process per file.
RotatingFileHandleris not safe when several Gunicorn workers write the same file. Log to stderr instead, or uselogging.handlers.WatchedFileHandlerwithlogrotate.
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.exceptioninsideexcept. 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().LOGGINGowns the configuration.basicConfigadds 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:
| Logger | What it logs |
|---|---|
django | Parent of everything below. Nothing logs to it directly. |
django.request | 5xx responses at ERROR with the traceback, 4xx responses at WARNING (Not Found: /nope/). Records carry status_code and request. |
django.server | One line per request from the development server. It does not exist under Gunicorn or uWSGI. |
django.db.backends | Every 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.template | Missing template variables at DEBUG. |
django.utils.autoreload | File 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. Thepythonjsonlogger.jsonloggerpath from older tutorials still imports but raises aDeprecationWarning. "()"is a factory.dictConfigcalls that class with the remaining keys as arguments.formatselects the standard fields. Anything passed throughextra, such asorder_id, is added on its own. Tracebacks land inexc_infoas one string.- Django adds extras too, such as
status_codeand a stringifiedrequestondjango.requestlines.
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 beforemanage.pyorwsgi.pysets the variable. Without itrunserverfailed withYou must set settings.ALLOWED_HOSTS if DEBUG is False. runserverworks with its autoreloader. Older guides pass--noreload. With 0.66b2, plainmanage.py runserverproduced spans and exported logs from the reloaded child process.- The handler survives your
LOGGING. The instrumentation wrapsdictConfigand adds its handler back afterwards. - Silence one warning.
django.requestrecords carry the request object, so the exporter warnsInvalid type WSGIRequest for attribute value. Add"opentelemetry.attributes": {"level": "ERROR"}tologgers. - Export less than you print.
OTEL_PYTHON_LOG_HANDLER_LEVEL=warningexports 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_idfield 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.errorwrites startup, worker lifecycle and worker crash messages to stderr. Despite the name, most of it is INFO.gunicorn.accesswrites one line per request, and is off until you pass--access-logfile -. Sincedjango.serveronly exists inrunserver, 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_dictingunicorn.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.wsgithe SDK restarts its export threads in each forked worker. That held with--preloadand 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:
- No handler. Without a
rootentry, INFO records are dropped. - Level too high. A record must pass the logger's level and then the handler's level. A root level of
WARNINGhideslogger.info()even with a DEBUG handler. disable_existing_loggersis missing orTrue. Check withlogging.getLogger("django.request").disabledinmanage.py shell.- The name does not match.
getLogger(__name__)inshop/views.pyisshop.views. A config entry formyproject.shopdoes not cover it. - A typo in the config.
dictConfigraises 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"
service.name you set.