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_DIRorDjangoConfig(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_FORMAToverrides - Your
LOGGINGwins — django-cfg only generates theLOGGINGdict; override it in the project as usual - Sanitized extra context — reserved
LogRecordattributes inextra={}are prefixed withctx_
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*andgunicorn*lose their own handlers and propagate to it, so one record is one line, in one format, underrunserver, gunicorn, uvicorn and workers. (djangokeeps Django’smail_adminshandler; a file handler exists only when you setlogging.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: threeNot Found: %swarnings for three paths are three lines, and a rate-limit warning keeps its address. For a line whose arguments are noise (a retry counter) passextra={"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 thetrythat 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.icodo not reachuvicorn.access,gunicorn.accessordjango.serveroutput; a failing health check (status 400 or more) still prints. Change the list withlogging.access_ignore_paths([]keeps everything). - Quiet third parties.
httpx,httpcore,urllib3,asyncio,rq,botocore,PIL,django.db.backendsanddjango.requestsit atWARNING; override one withlogging.log_levels={"httpx": "INFO"}. - Secrets masked. Values of
extrakeys (and monitor events) namedpassword,token,secret,authorization,cookie,set-cookie,api_keyare written as***, recursing into dicts and lists. Whole key segments only:access_tokenis masked,max_tokensis not. Add names withlogging.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) setsrequest_id: theX-Request-IDheader 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 theX-Request-IDresponse header. An RQ job carries the id of the request that enqueued it (job.meta["request_id"]) and logs it, withjob_id, when it runs. With an active OpenTelemetry span the lines carrytrace_id/span_idand 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 set | Result |
|---|---|
| nothing | General 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/myapp | also 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
)| Field | Type | Default | Env | Description |
|---|---|---|---|---|
dir | str | None | None | DJANGO_CFG_LOG_DIR | Log directory (adds django.log, hosts the monitor file) |
level | str | None | None | DJANGO_CFG_LOG_LEVEL | Level of the django_cfg loggers |
format | "text" | "json" | json off a terminal | DJANGO_CFG_LOG_FORMAT | json is one object per line |
rotate_mb | int | 10 | DJANGO_CFG_LOG_ROTATE_MB | Size at which a django-cfg log file rotates; 0 = never |
backups | int | 5 | DJANGO_CFG_LOG_BACKUPS | Rotated files kept per log (.1 … .N) |
retain_days | int | 14 | DJANGO_CFG_LOG_RETAIN_DAYS | Boot prune: rotated files older than this are deleted |
collapse | CollapseConfig | on (off in tests) | enabled, window_seconds (60), max_keys (1000) | |
log_levels | dict[str, str] | {} | Per-logger levels over the third-party table | |
access_ignore_paths | list[str] | None | built-in list | Health/static prefixes dropped from access logs | |
redact_keys | list[str] | [] | Extra key names masked in log fields |
Other environment variables
| Variable | Meaning |
|---|---|
DJANGO_CFG_LOG_DIR_MAX_BYTES | Boot 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_PRUNE | 0 = no boot prune |
DJANGO_LOG_TO_TMP | Deprecated 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 --applyRemoved 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
- Without
logging.dir/DJANGO_CFG_LOG_DIRthere is nodjango.logby design; general logs are on stdout (docker compose logs). Only the monitor filedjangocfg/monitor.logis written by default. - If even
monitor.logis 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 configureddirthat cannot be written logscannot write to the configured log directoryand 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]- Fix: give the app user a writable directory and point to it, e.g.
DJANGO_CFG_LOG_DIR=/var/log/myappwithchownto 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 onlySee Also
- Logging in production — containers, aggregation, troubleshooting
- Monitor Module — Error tracking and Telegram alerts built on this logging pipeline
- Telegram Module — Telegram alert notifications