Skip to Content
FeaturesModulesLogging

Django Logging

Django-CFG logs the Django / 12-factor way: records go to stdout/stderr and the platform routes them (Docker, systemd, your terminal). The app does not manage log files unless you ask for one. Importing django_cfg creates no directories, writes no files and does not touch your root handlers.

Features

  • stdout by default — no logs/ folder in the project tree
  • File is opt-in — DJANGO_CFG_LOG_DIR or DjangoConfig(logging=...); size-rotated with a bounded backup count, safe with several workers, and pruned at boot
  • JSON off a terminal — one object per line when stderr is not a terminal (a container, systemd, a pipe), text at your terminal; DJANGO_CFG_LOG_FORMAT overrides
  • Your LOGGING wins — django-cfg only generates the LOGGING dict; override it in the project as usual
  • Sanitized extra context — reserved LogRecord attributes in extra={} are prefixed with ctx_

Quick Start

django-cfg has no logger wrapper. Use the standard library:

import logging logger = logging.getLogger(__name__) logger.debug("Processing started") logger.info("User created", extra={"user_id": 42}) logger.warning("Rate limit approaching", extra={"endpoint": "/api/users"}) logger.error("Payment failed", extra={"order_id": "ORD-123"})

Loggers named under django_cfg (every django-cfg module uses __name__) get the handlers and level from the generated LOGGING dict; your own loggers follow your project’s LOGGING.

Migration: get_logger (from django_cfg, django_cfg.utils and django_cfg.modules.django_logging) and DjangoLogger were removed with no alias. Replace get_logger(name) with logging.getLogger(name) (or logging.getLogger(__name__)) and drop the import. The old helper rewrote short names to django_cfg.<path>; a plain name is now used as given.

One path, no duplicates, no junk

A project writes no logging config and keeps calling logging.getLogger(__name__). The generated LOGGING dict is one complete path:

  • One handler on root. django.server, uvicorn* and gunicorn* lose their own handlers and propagate to it, so one record is one line, in one format, under runserver, gunicorn, uvicorn and workers. (django keeps Django’s mail_admins handler; a file handler exists only when you set logging.dir.)
  • Repeats collapse. The first record of a key always prints; repeats inside 60 s are counted and one line ... (repeated N times in 60s, pid P) follows. The key is the logger, level, call site and the formatted message, so only an identical line repeats: three Not Found: %s warnings for three paths are three lines, and a rate-limit warning keeps its address. For a line whose arguments are noise (a retry counter) pass extra={"collapse_key": "retry"} to fold them. For a record with an exception the key is the message template, the exception type and the innermost traceback frame (where it was raised, not the try that caught it), so a new traceback always prints. ERROR and above are never collapsed, nor are access-log lines and monitor events; extra={"no_collapse": True} opts any record out. State is per process (N workers can print N first lines). Off in the test environment.
  • Access-log junk dropped. Successful requests to /healthz, /health, /ready, /live, /ping, /static/ and /favicon.ico do not reach uvicorn.access, gunicorn.access or django.server output; a failing health check (status 400 or more) still prints. Change the list with logging.access_ignore_paths ([] keeps everything).
  • Quiet third parties. httpx, httpcore, urllib3, asyncio, rq, botocore, PIL, django.db.backends and django.request sit at WARNING; override one with logging.log_levels={"httpx": "INFO"}.
  • Secrets masked. Values of extra keys (and monitor events) named password, token, secret, authorization, cookie, set-cookie, api_key are written as ***, recursing into dicts and lists. Whole key segments only: access_token is masked, max_tokens is not. Add names with logging.redact_keys. A secret inside the message text is not found: do not log payloads.
  • Request id on every line. RequestIdMiddleware (added right after the real-IP middleware) sets request_id: the X-Request-ID header when the peer is a private or loopback address (a reverse proxy) and the value is well-formed, else a generated id; it is echoed as the X-Request-ID response header. An RQ job carries the id of the request that enqueued it (job.meta["request_id"]) and logs it, with job_id, when it runs. With an active OpenTelemetry span the lines carry trace_id / span_id and no id is invented. The id is a log label, never an authority.
logging=DjangoLoggingConfig( collapse=CollapseConfig(window_seconds=60, max_keys=1000), # enabled=None: on except in tests log_levels={"httpx": "INFO"}, access_ignore_paths=["/healthz", "/internal/ping"], redact_keys=["ssn"], )

Diagnose a noisy service: docker logs <container> 2>&1 | python manage.py log_noise --stdin groups lines by normalised message and prints the top repeats with counts and no raw ids. Counters of the collapse are in django_cfg.modules.django_logging.collapse.collapse_stats().

Where logs go

django-cfg decides this itself; a project that sets nothing gets a sane result.

You setResult
nothingGeneral logs: stdout/stderr (JSON off a terminal), django_cfg at WARNING (INFO on a development runserver; DEBUG only when asked with level / DJANGO_CFG_LOG_LEVEL). Monitor events also go to a small rotating file djangocfg/monitor.log (10 MB x 5) in /var/log/<app> if writable, else the per-user state dir (~/.local/state/<app>/log on Linux, ~/Library/Logs/<app> on macOS). If neither is writable: no file, events on stdout only, one warning
logging.dir or DJANGO_CFG_LOG_DIR=/var/log/myappalso django.log there, and djangocfg/monitor.log in that directory (monitor events only in monitor.log, not twice)

The directory is created when the first record is written, not at import. If it cannot be written, django-cfg logs one warning and keeps logging to stdout. Nothing is ever written inside the project tree, and <cwd>/logs is not used.

Precedence for every setting: explicit config (logging.*), then the env var, then the built-in default. <app> is the top package of DJANGO_SETTINGS_MODULE, else the working directory name, so projects on one machine do not share state.

Configuration

from django_cfg import DjangoConfig, DjangoLoggingConfig class Config(DjangoConfig): logging: DjangoLoggingConfig = DjangoLoggingConfig( dir="/var/log/myapp", # None = no general file; the monitor file uses the default chain level="INFO", # django_cfg loggers; default WARNING (INFO on a development runserver); DEBUG only here rotate_mb=10, # rotate a file at this size; 0 = never (leave it to logrotate) backups=5, # rotated files kept per log retain_days=14, # boot prune: age of rotated files )
FieldTypeDefaultEnvDescription
dirstr | NoneNoneDJANGO_CFG_LOG_DIRLog directory (adds django.log, hosts the monitor file)
levelstr | NoneNoneDJANGO_CFG_LOG_LEVELLevel of the django_cfg loggers
format"text" | "json"json off a terminalDJANGO_CFG_LOG_FORMATjson is one object per line
rotate_mbint10DJANGO_CFG_LOG_ROTATE_MBSize at which a django-cfg log file rotates; 0 = never
backupsint5DJANGO_CFG_LOG_BACKUPSRotated files kept per log (.1 … .N)
retain_daysint14DJANGO_CFG_LOG_RETAIN_DAYSBoot prune: rotated files older than this are deleted
collapseCollapseConfigon (off in tests)enabled, window_seconds (60), max_keys (1000)
log_levelsdict[str, str]{}Per-logger levels over the third-party table
access_ignore_pathslist[str] | Nonebuilt-in listHealth/static prefixes dropped from access logs
redact_keyslist[str][]Extra key names masked in log fields

Other environment variables

VariableMeaning
DJANGO_CFG_LOG_DIR_MAX_BYTESBoot prune: the oldest rotated files go until the directory is under this. Default 500 MB; one warning if it is still over
DJANGO_CFG_LOG_PRUNE0 = no boot prune
DJANGO_LOG_TO_TMPDeprecated and ignored. Logs one warning. The /tmp/djangocfg/debug.log mirror is gone

DJANGO_CFG_LOG_FILE, DJANGO_CFG_LOG_ROTATE, DJANGO_CFG_LOG_MAX_BYTES and DJANGO_CFG_LOG_KEEP_DAYS no longer exist (use DJANGO_CFG_LOG_DIR, ..._ROTATE_MB, ..._RETAIN_DAYS). The config field log_dir is now dir.

Rotation is by size and is safe with several workers: the rename happens under a file lock and only if the file is still over the limit, so one worker rotates and the others reopen. If logrotate already owns the file, set rotate_mb=0.

Pruning

At boot, in a background thread and at most once a day per directory, django-cfg deletes rotated files it wrote (django.log.*, djangocfg/*, and leftovers such as apps.log) that are older than 14 days or beyond the backup count, then the oldest until the directory is under 500 MB. A live file is never deleted. It never delays boot. If the directory is still over the cap you get one warning naming the directory. By hand:

python manage.py log_prune # dry run: lists files and sizes python manage.py log_prune --apply # deletes python manage.py log_prune --dir /var/log/myapp --days 7 --keep 3 --max-mb 200 --apply

Removed fields

enabled, file_enabled and file_rotation_days were never read. DjangoLoggingConfig still accepts them (and ignores them with one warning) for one release. django_cfg.LoggingConfig is a deprecated no-op shim, removed in the next release.

Upgrading from the logs/ folder

django-cfg no longer writes to ./logs and has no fallback or warning for it. A host that bind-mounts /app/logs can drop the mount: general logs are on stdout, and monitor events are in the per-user or /var/log/<app> file. To keep files in a known place, set logging.dir or DJANGO_CFG_LOG_DIR (outside the project tree). python manage.py log_prune --dir /app/logs --apply clears old dated files. See the CHANGELOG  for the full note.

Public API

There is no logger factory; the module exports two plain functions and a constant.

sanitize_extra(extra)

Prefixes any key in extra that conflicts with Python’s reserved LogRecord attributes (e.g., module, message, name) with ctx_ to prevent KeyError.

from django_cfg.modules.django_logging import sanitize_extra safe = sanitize_extra({"module": "myapp", "user_id": 42}) # {"ctx_module": "myapp", "user_id": 42} logger.info("Event", extra=safe)

clean_old_logs(days=30, logs_dir=None)

Deletes log files older than days from the log directory (default: the resolved one). Returns {"deleted": 0, "bytes": 0, "error": ...} when there is no log directory. Rotation and the boot prune already do this for django-cfg’s own files; prefer manage.py log_prune.

from django_cfg.modules.django_logging import clean_old_logs stats = clean_old_logs(days=7) # {"deleted": 12, "bytes": 45678, "human_readable": "0.04 MB"}

Troubleshooting

No log file is created

  1. Without logging.dir / DJANGO_CFG_LOG_DIR there is no django.log by design; general logs are on stdout (docker compose logs). Only the monitor file djangocfg/monitor.log is written by default.
  2. If even monitor.log is missing, django-cfg found no writable directory (logging.dir/env, /var/log/<app>, the per-user state dir) and logged one warning: django-cfg found no writable directory for the monitor event log .... Monitor events are then on stdout only. A configured dir that cannot be written logs cannot write to the configured log directory and falls back to the defaults.

In a container the monitor events live in stdout only (the file is usually not written and docker logs holds them). Read them with the pipe form of monitor_tail, which skips banners, tracebacks and other loggers:

docker logs <container> 2>&1 | python manage.py monitor_tail --stdin [-n N] [--frontend] [--user ID] [--fingerprint HEX] [--session ID]
  1. Fix: give the app user a writable directory and point to it, e.g. DJANGO_CFG_LOG_DIR=/var/log/myapp with chown to the container user, or mount a volume there. A default inside the project tree is never used.
from django_cfg.core.utils.runtime_paths import resolve_log_dir, resolve_monitor_log_dir print(resolve_log_dir()) # None = no django.log print(resolve_monitor_log_dir()) # None = nothing writable, stdout only

See Also

Last updated on