Polyaxon v3 is coming →

Django logging on Kubernetes

Configure Django logs for container collection, useful request context, exception diagnosis, privacy, and correlation with Kubernetes workload state.

March 27, 2026by Polyaxon
Django logging on Kubernetes

Django uses Python's logging framework and adds loggers for requests, server behavior, database queries, security events, and framework internals. In Kubernetes, the application should emit useful records to the container stream while the platform handles collection, retention, and search.

The goal is not maximum volume. It is enough structured context to connect a user-visible failure to the Django component, deployment, Pod, dependency, and request path that produced it.

Configure logging through settings

Django applies logging configuration through the LOGGING setting. The official Django logging guide recommends extending the framework's defaults rather than disabling existing loggers.

This baseline sends application and request records to stdout:

import os


LOG_LEVEL = os.getenv("DJANGO_LOG_LEVEL", "INFO").upper()

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {
            "format": "{asctime} {levelname} {name} {message}",
            "style": "{",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "standard",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "WARNING",
    },
    "loggers": {
        "django.request": {
            "handlers": ["console"],
            "level": "WARNING",
            "propagate": False,
        },
        "myproject": {
            "handlers": ["console"],
            "level": LOG_LEVEL,
            "propagate": False,
        },
    },
}

Replace myproject with the root of your application's logger hierarchy. Using one handler with propagate: False prevents the same record from appearing again through the root logger.

Log events from application code

Create loggers by module and use parameterized messages:

import logging

from django.http import HttpRequest, JsonResponse

logger = logging.getLogger(__name__)


def start_evaluation(request: HttpRequest) -> JsonResponse:
    evaluation_id = request.headers.get("X-Evaluation-ID", "unknown")
    logger.info(
        "evaluation_requested evaluation_id=%s",
        evaluation_id,
    )
    return JsonResponse({"evaluation_id": evaluation_id}, status=202)

In production, validate externally supplied identifiers before using them as trusted correlation data. Do not log the request body simply because it is available.

Log state transitions and outcomes: request accepted, background work submitted, dependency timed out, permission denied, or result stored. Avoid narrating every line of application code.

Separate logs, metrics, and traces

Use logs for discrete events and diagnostic context. Use metrics for request rates, error ratios, latency distributions, queue depth, and resource use. Use traces to follow one request across Django, a queue, a worker, and downstream services.

Carry a correlation identifier between the signals, but keep metric labels bounded. A request ID belongs in logs and traces, not as a metric label with a new value for every request.

For asynchronous work, record both the web request identifier and the durable task or Polyaxon run identifier. That lets an operator move from the API event to the operation that performed the expensive computation.

Handle exceptions without duplication

Django records unhandled request exceptions through django.request. In application exception handlers, use logger.exception() when you need the active traceback and the error is not already logged by a higher layer.

Avoid catching every exception only to log and re-raise it if Django will emit the same traceback. Duplicate records inflate error counts and obscure the original context. Decide which layer owns the error event and which layers add trace context.

Return safe error responses to clients. Detailed stack traces, settings, SQL, and environment data belong in controlled diagnostics, never in public production responses.

Protect sensitive data

Django requests can contain session cookies, authorization headers, form values, uploaded files, and personal data. Define an allowlist of fields that may enter logs. Redact secrets before records leave the process, and apply retention and access policies in the logging backend.

Keep DEBUG=False in production. Debug pages can reveal sensitive application and request details and are not an observability substitute.

Add Kubernetes context

Enrich collected records with infrastructure metadata such as service version, image digest, Pod, namespace, node, and cluster. Prefer collector or deployment metadata for fields the process does not need to know. Keep application code focused on request and domain context.

Correlate Django errors with:

  • Pod readiness and restart history;
  • CPU throttling and memory termination;
  • deployment and image revision;
  • database and queue latency;
  • ingress status and upstream timeouts;
  • node or network failures.

A 500 response is an application symptom, but its cause may be an exhausted connection pool, a terminating Pod, or an unavailable dependency.

Connect Django to Polyaxon workloads

A Django service may submit training, evaluation, or batch-inference work to Polyaxon. Log the accepted request and resulting run identifier, then let the operation carry its own logs, metrics, parameters, and artifacts. Do not stream an entire training log through the web request process.

Use Polyaxon's logging guidance for operation output and platform observability for deployment health. Together with Django application telemetry, they connect a web request to the infrastructure and ML execution it initiated.

The most useful Django logging configuration is deliberately boring: one clear ownership model, predictable stdout records, controlled verbosity, safe context, and a direct path from an error to the operation that needs attention.