Skip to Content
DeploymentLogging

Logging in production

Django-CFG generates the whole logging path. A project writes no logging config and keeps calling logging.getLogger(__name__); it gets one stream (JSON off a terminal, short text on one), no duplicate lines, repeated lines collapsed, health-check noise dropped, chatty libraries quiet, secrets masked and a request id on every line. What each rule does and how to tune it: Django Logging.

import logging logger = logging.getLogger(__name__) logger.warning("Cache miss for %s", key) # lazy arguments, never an f-string

Defaults by environment:

  • Development server (runserver): short readable lines, INFO
  • Everything else (production, tests, shell, migrate, workers): WARNING and above, JSON off a terminal
  • DEBUG only when you ask for it (DJANGO_CFG_LOG_LEVEL=DEBUG)

Find what is noisy with docker logs <container> 2>&1 | python manage.py log_noise --stdin.


Where Logs Go

Logging follows 12-factor: stdout/stderr by default, a file only when you ask. Importing django_cfg never creates logs/ and never touches your root handlers; the LOGGING dict is generated from DjangoConfig and your own LOGGING overrides it.

ModeConsoleFile
Defaultdjango_cfg at WARNING (INFO on a development runserver)none
debug=Truesame as default: Django DEBUG does not raise the levelnone
DJANGO_CFG_LOG_LEVEL=DEBUGdjango_cfg at DEBUGnone
logging.dir / DJANGO_CFG_LOG_DIR=/var/log/appas abovedjango.log, djangocfg/monitor.log there

In every mode monitor events also go to djangocfg/monitor.log (10 MB x 5) in /var/log/<app> if writable, else ~/.local/state/<app>/log (~/Library/Logs/<app> on macOS); if neither is writable, stdout only and one warning.

DJANGO_CFG_LOG_FORMAT=json # one JSON object per line (default: json off a terminal, text at one) DJANGO_CFG_LOG_LEVEL=INFO # level of the django_cfg loggers DJANGO_CFG_LOG_DIR=/var/log/app # also django.log there (size-rotated: 10 MB x 5, pruned at boot); same as logging.dir

Text format:

[2026-11-05 12:34:56,789] WARNING in django_cfg.accounts [views.py:42]: User login failed

JSON format:

{"ts": "2026-11-05T12:34:56+0000", "level": "WARNING", "logger": "django_cfg.accounts", "message": "User login failed", "module": "views", "line": 42}

See Django Logging, the canonical page for the logging config block, precedence and defaults.

stdout in containers

The recommended setup: log to stdout and let Docker (or Kubernetes) collect it. No volume, no logs/ mount, nothing to rotate.

# docker-compose.yml services: api: image: myapp environment: DJANGO_CFG_LOG_FORMAT: json logging: driver: json-file options: max-size: "10m" max-file: "5"
docker compose logs -f api

Do not set DJANGO_CFG_LOG_DIR in a container unless something reads the files. If you do (an agent tailing a mounted folder), mount a volume at that path. django-cfg rotates by size (logging.rotate_mb, logging.backups) and prunes old files at boot; with logrotate on the host set rotate_mb=0. The monitor file needs no mount: without one it lands in the container’s own /var/log/<app> or state dir and monitor_tail reads it there.

Upgrading from the logs/ folder

Earlier versions wrote logs/django.log, logs/djangocfg/*.log and a /tmp/djangocfg/debug.log mirror, and a ./logs folder kept being written in addition to stdout. That fallback is gone, with no warning and no alias: with no override general logs go to stdout only. A project that mounts ../files/logs:/app/logs can drop the mount, or keeps it and adds DJANGO_CFG_LOG_DIR=/app/logs to its env; python manage.py log_prune --dir /app/logs --apply clears the old dated files (dry run without --apply). DJANGO_LOG_TO_TMP is ignored (one warning); the mirror is gone.


Logger Configuration

There is no django-cfg logger factory: use logging.getLogger(__name__). It adds no handlers; handlers come from the generated LOGGING dict (see Django Logging for the API and the migration note from get_logger):

import logging logger = logging.getLogger(__name__)

Level sources (priority order):

  1. DjangoConfig(logging=DjangoLoggingConfig(level=...))
  2. DJANGO_CFG_LOG_LEVEL
  3. By environment (env_mode) and command: INFO for a development runserver / runserver_ngrok, else WARNING. DEBUG never comes from config.debug.

Logging Levels

When to Use Each Level

DEBUG - Detailed diagnostic information:

logger.debug("Query executed: %s", query) logger.debug("Cache hit for key: %s", cache_key)

INFO - General informational messages:

logger.info("User %s logged in from %s", username, ip_address) logger.info("Task completed in %.2f seconds", duration)

WARNING - Unexpected but handled situations:

logger.warning("Retry attempt %d/%d for API call", attempt, max_retries) logger.warning("Using fallback value for missing config")

ERROR - Serious problems that need attention:

logger.error("Failed to send email to %s", email, exc_info=True) logger.error("Payment gateway returned error: %s", error_code)

CRITICAL - Very serious errors:

logger.critical("Database connection lost", exc_info=True) logger.critical("Unable to load required configuration")

Best Practices

1. Include Context

# Good - provides context logger.error( "Order processing failed for order %s (user: %s)", order.id, order.user.id ) # Bad - vague message logger.error("Order failed")

2. Use Structured Logging

# Good - structured data logger.info("api_call", extra={ "endpoint": "/api/users/", "method": "GET", "status": 200, "duration_ms": 150, }) # Bad - string formatting logger.info("GET /api/users/ 200 150ms")

3. Log Exceptions Properly

# Good - includes traceback try: process_payment(order) except PaymentError: logger.error("Payment failed for order %s", order.id, exc_info=True) return failed_response() # handled here, logged once; do not log and re-raise # Bad - loses stack trace except PaymentError as e: logger.error(f"Payment failed: {str(e)}")

4. Avoid Logging Sensitive Data

# Good - sanitized logger.info("User logged in", extra={ "user_id": user.id, "username": user.username }) # Bad - includes password! logger.debug("Login attempt: %s / %s", username, password)

Integration with Monitoring

Sentry Integration

Django-CFG logging works with Sentry handlers:

import sentry_sdk sentry_sdk.init( dsn="your-sentry-dsn", environment="production", ) # Django-CFG logger automatically sends ERROR+ to Sentry logger.error("Payment failed", exc_info=True) # → Sent to Sentry

Log Aggregation (ELK, Datadog, CloudWatch)

Ship the container stream; use DJANGO_CFG_LOG_FORMAT=json so the aggregator gets structured fields:

# Docker / Kubernetes: the platform already collects stdout docker compose logs -f api # Or, with a file (DJANGO_CFG_LOG_DIR=/var/log/app), tail it filebeat -c filebeat.yml # ELK Stack datadog-agent # Datadog

Advanced Usage

Custom Logger Instance

import logging # Get named logger my_logger = logging.getLogger("myapp.payments") # Use with module-specific settings my_logger.info("Payment processed")

Log Formatting Helpers

from django_cfg.modules.django_logging import sanitize_extra, RESERVED_LOG_ATTRS # Remove reserved attributes before logging extra_data = { "user_id": 123, "name": "test", # Reserved attr - will be removed "action": "login" } clean_data = sanitize_extra(extra_data) logger.info("User action", extra=clean_data)

Troubleshooting

Logs Not Appearing

Check debug mode:

from django_cfg.core.state import get_current_config config = get_current_config() print(f"Debug mode: {config.debug}") # Should match expected environment

Check log level:

import logging logger = logging.getLogger('django_cfg') print(f"Logger level: {logger.level}") # 10=DEBUG, 30=WARNING

File Logs Not Created

Full explanation: No log file is created. Short version: django.log exists only when a directory is configured:

echo $DJANGO_CFG_LOG_DIR # empty = stdout only
from django_cfg.core.utils.runtime_paths import resolve_log_dir print(resolve_log_dir()) # None = no django.log from django_cfg.core.utils.runtime_paths import resolve_monitor_log_dir print(resolve_monitor_log_dir()) # None = nothing writable: monitor events on stdout only

The directory is created when the first record is written. If it is not writable, django-cfg logs one warning (cannot write ..., or no writable directory for the monitor event log) and continues on stdout; fix the permissions of the mounted volume or the user the container runs as.

Colors Not Showing

Check terminal support:

import sys print(sys.stderr.isatty()) # Should be True for colors

Rich library check:

# Rich required for colored output pip install rich

See Also


TAGS: logging, monitoring, debugging, structured-logging, django-cfg DEPENDS_ON: [django-cfg, environment-detection] USED_BY: [monitoring, production, debugging]

Last updated on