Monitoring Guide
Django-CFG ships health endpoints and a logging module that work in development and production. Metrics export and alerting are left to external tools.
Core Principles
What You Get Without Configuration
- Health checks at
/healthzand/healthz/ready(the always-installedhealthapp) - Database checks for every configured database alias
- Smart logging with automatic level adjustment and repeat collapsing
Environment-Aware
- Development: verbose logging, detailed errors
- Production: WARNING and above on stdout, text or JSON
Health Check Endpoints
Django-CFG includes built-in health check endpoints for monitoring service status.
Simple Health Check
Basic liveness probe for container orchestration:
GET /healthzResponse:
{
"status": "ok",
"timestamp": "2025-10-14T12:34:56.789Z"
}Use cases:
- Docker health checks
- Kubernetes liveness probes
- Load balancer health monitoring
Comprehensive Health Check
Detailed system status with metrics. The overall status is healthy, degraded (a check warns) or unhealthy (a check failed):
GET /healthz/readyResponse:
{
"status": "healthy",
"timestamp": "2025-10-14T12:34:56.789Z",
"checks": {
"database": {
"status": "healthy",
"databases": {
"default": {
"status": "healthy",
"response_time_ms": 2.45,
"engine": "django.db.backends.postgresql"
}
}
},
"cache": {
"status": "healthy",
"response_time_ms": 0.89,
"backend": "django_redis.cache.RedisCache"
},
"system": {
"status": "healthy",
"cpu": {
"usage_percent": 15.2,
"status": "healthy"
},
"memory": {
"usage_percent": 45.6,
"total_gb": 16.0,
"available_gb": 8.7,
"status": "healthy"
},
"disk": {
"usage_percent": 62.3,
"total_gb": 500.0,
"free_gb": 188.5,
"status": "healthy"
}
},
"configuration": {
"status": "healthy",
"django_cfg": {
"version": "1.3.13",
"debug": false,
"environment": "production",
"secret_key_length": 64,
"project_name": "myapp",
"enable_accounts": true,
"enable_tasks": true
}
}
}
}Monitored components:
- ✅ Database connectivity and response times
- ✅ Cache availability and performance
- ✅ CPU, memory, disk usage
- ✅ Load average
- ✅ Configuration validation
System Metrics
The system block of /healthz/ready (see above) reports CPU, memory, disk and load average through psutil. A check turns to warning above 80% and the block above 90%.
Note that the readiness probe samples the CPU for one second, so give a probe at least a 2 second timeout.
Logging System
Django-CFG includes a built-in logging module that works out of the box.
Zero-Configuration Logging
Logging is automatically configured based on environment:
Development:
- Console output with colors
- DEBUG level messages
- Rich tracebacks for errors
Production:
- stdout/stderr (a log file is opt-in via
DJANGO_CFG_LOG_DIR) - WARNING level and above
- Text or JSON (
DJANGO_CFG_LOG_FORMAT=json)
Smart Logger
One root handler (CollapsingStreamHandler) collapses identical lines within 60 seconds (“repeated N times”). ERROR and above are never collapsed. Every line carries request_id when RequestIdMiddleware is active (it also sets the X-Request-ID header). Tune it with logging.collapse, log_levels, access_ignore_paths and redact_keys; see Logging Configuration for details and manage.py log_noise --stdin for finding the noisiest lines.
Basic Usage
import logging
logger = logging.getLogger(__name__)
logger.info("User logged in")
logger.warning("Cache miss")
logger.error("Connection failed")That’s it! No configuration needed—the module handles everything automatically.
For detailed logging configuration, see Logging Configuration →
Docker Health Checks
Django-CFG health checks work seamlessly with Docker.
Docker Compose Configuration
services:
django:
image: your-django-app
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/healthz"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40sKubernetes Probes
apiVersion: v1
kind: Pod
spec:
containers:
- name: django
image: your-django-app
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /healthz/ready
port: 8000
initialDelaySeconds: 10
periodSeconds: 5Production Monitoring Best Practices
1. External Monitoring
Integrate with external monitoring services:
Uptime Monitoring:
- UptimeRobot
- Pingdom
- StatusCake
Configure to check /healthz endpoint every 1-5 minutes.
Error Tracking:
# Add Sentry integration (optional)
import sentry_sdk
sentry_sdk.init(
dsn="your-sentry-dsn",
environment="production",
)2. Log Aggregation
Send logs to centralized service:
- ELK Stack (Elasticsearch, Logstash, Kibana)
- Datadog - Application monitoring
- CloudWatch - AWS logging
- Grafana Loki - Log aggregation
3. Alerting Rules
Set up alerts for:
# Example alerting thresholds (configure in your monitoring system)
cpu_usage: > 80%
memory_usage: > 85%
disk_usage: > 90%
database_response_time: > 1000ms
error_rate: > 10 errors/minute4. Metrics Export
Export metrics to monitoring systems:
# Prometheus metrics endpoint (optional)
# django-cfg ships no Prometheus exporter; use django-prometheus if you need one
INSTALLED_APPS += ['django_prometheus']
# Metrics available at /metrics/Monitoring Checklist
Before deploying to production:
Health Checks
-
/healthzendpoint returns 200 OK -
/healthz/readyshows all systems healthy - Database connectivity verified
- Cache availability verified
Logging
- Logs reach your aggregator (stdout, or
DJANGO_CFG_LOG_DIRis writable) - Log rotation configured if you write files
- Log level set to WARNING or higher
-
RequestIdMiddlewareactive so lines can be correlated
External Monitoring
- Uptime monitoring configured
- Error tracking service integrated
- Log aggregation set up
- Alert rules configured
Resource Monitoring
- CPU usage tracking enabled
- Memory monitoring active
- Disk space alerts configured
- Database performance tracked
Troubleshooting
Health Check Returns “unhealthy”
Check database connectivity:
# Test database connection
python manage.py dbshell
# Check database logs
docker logs postgres_containerCheck cache connectivity:
# Test Redis connection
redis-cli ping
# Check cache configuration
python manage.py shell -c "from django.core.cache import cache; print(cache.get('test'))"High Resource Usage Warnings
CPU usage > 90%:
- Check for infinite loops
- Review Django-RQ worker count
- Optimize database queries
- Enable query caching
Memory usage > 85%:
- Check for memory leaks
- Review queryset evaluation
- Optimize image processing
- Reduce worker memory limit
Disk usage > 90%:
- Clean up old log files (if you set
DJANGO_CFG_LOG_DIR) - Remove unused media files
- Set up
logrotate, or log to stdout only - Archive old backups
Logs Not Writing
General logs go to stdout (docker compose logs); django.log needs logging.dir / DJANGO_CFG_LOG_DIR, and only the monitor file is written by default. See Django Logging.
Check permissions (only when DJANGO_CFG_LOG_DIR is set):
# Ensure the log directory is writable by the app user
chmod 755 "$DJANGO_CFG_LOG_DIR"
chown -R django-user:django-user "$DJANGO_CFG_LOG_DIR"If the directory is not writable, django-cfg logs one warning and keeps logging to stdout (monitor events fall back to /var/log/<app>, then the per-user state dir).
Check disk space:
# Verify available disk space
df -h "$DJANGO_CFG_LOG_DIR"Check configuration:
# Verify logging config in settings
print(settings.LOGGING)See Also
- Logging Configuration - Detailed logging setup
- Docker Guide - Docker health checks
- Security Guide - Security monitoring
- Production Config - Production best practices
TAGS: monitoring, logging, health-checks, metrics, docker, kubernetes, production DEPENDS_ON: [django-cfg, docker, postgresql, redis] USED_BY: [production, devops, sre, monitoring-tools]