The production standard for DRF API observability. Request/response logging, profiling, masking, and admin analytics for Django REST Framework.
Use drf-api-logger when you need to inspect DRF API calls without writing fragile custom middleware. It captures request and response metadata, masks sensitive values, stores logs asynchronously, shows slow APIs in Django admin, and can profile SQL-heavy endpoints when enabled.
INSTALLED_APPS = [
# ... your other apps
'drf_api_logger',
]
Add the API logger middleware:
MIDDLEWARE = [
# ... your other middleware
'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware',
]
3. Database Migration (Optional)
If using database logging, run migrations:
python manage.py migrate
Upgrade warning for large MySQL/MariaDB tables: Version 1.2.0+ adds
profiling-related columns (profiling_data and sql_query_count) to the
drf_api_logs table. On large MySQL/MariaDB tables, adding columns can take
locks or require table rebuilds depending on the database version, storage
engine, row format, and existing table definition. Plan this migration like a
production schema change.
Before upgrading, inspect the SQL Django will run:
python manage.py sqlmigrate drf_api_logger 0003
For large MySQL/MariaDB deployments, validate the generated SQL against your
exact database/version, prefer database-native online DDL where supported, and
consider manually adding the columns with a safe online schema migration tool
or database-native online DDL. If the columns are added manually, fake-apply
the Django migration afterward:
Avoid copying a generic ALTER TABLE command without validating it for your
database. MySQL and MariaDB online DDL behavior differs by version and table
definition.
⚙️ Quick Start
Database Logging
Enable database storage for API logs:
# settings.py
DRF_API_LOGGER_DATABASE = True
Features:
📊 Admin Dashboard: View logs in Django Admin with charts and analytics
🔍 Advanced Search: Search across request body, response, headers, and URLs
🎛️ Smart Filtering: Filter by date, status code, HTTP method, and performance
📈 Visual Analytics: Built-in performance charts and statistics
Admin graphs are collapsed by default and loaded on demand when opened, keeping
the log list fast and focused during routine investigation. Each graph has its
own control and fetches its backend data only when opened; graph data requests
time out after 30 seconds.
Admin Dashboard Screenshots
Admin Home
Log Listing with Charts & SQL Query Count
Detailed Log View with Data Masking
Signal-Based Logging
Enable real-time signal notifications for custom logging solutions:
# settings.py
DRF_API_LOGGER_SIGNAL = True
Signal Usage Example
from drf_api_logger import API_LOGGER_SIGNAL
# Create signal listeners
def log_to_file(**kwargs):
"""Log API data to file"""
with open('api_logs.json', 'a') as f:
json.dump(kwargs, f)
f.write('\n')
def send_to_analytics(**kwargs):
"""Send API data to analytics service"""
analytics_service.track_api_call(
url=kwargs['api'],
method=kwargs['method'],
status_code=kwargs['status_code'],
execution_time=kwargs['execution_time']
)
# Subscribe to signals
API_LOGGER_SIGNAL.listen += log_to_file
API_LOGGER_SIGNAL.listen += send_to_analytics
# Unsubscribe when needed
API_LOGGER_SIGNAL.listen -= log_to_file
Safe observability integrations: Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
First-party metrics: optional Prometheus recorder, logger overhead, queue health, API metrics, safe labels, and endpoint guidance.
Security signals: detect-only suspicious activity metrics, bounded body inspection, rule IDs, and false-positive guidance.
Policy controls: endpoint-specific logging, masking, payload minimization, and signal/export gating.
AI assistant guidance: prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
Comparison and migration guide: custom middleware, DRF request tracking packages, audit packages, and observability tools.
Tutorials and community snippets: safe logging, slow APIs, masking, pruning, trace IDs, Stack Overflow answers, blog outlines, and video scripts.
Operations guide: retention jobs, queue health, database growth, and indexes.
Compliance readiness: data minimization, masking, retention, and deployment controls.
🔧 Configuration Options
Performance Optimization
Control background processing and database performance:
# Batch size threshold for database bulk inserts
DRF_LOGGER_QUEUE_MAX_SIZE = 50 # Default: 50
# Time interval for processing queue (seconds)
DRF_LOGGER_INTERVAL = 10 # Default: 10 seconds
DRF_LOGGER_QUEUE_MAX_SIZE controls how many log records are inserted per bulk
database write. Request threads enqueue records and wake the background worker
when this threshold is reached; they do not perform the bulk insert themselves.
Default masking also covers common credential-bearing headers and keys such as
authorization, cookie, set_cookie, api_key, x_api_key, client_secret,
private_key, sessionid, and csrfmiddlewaretoken. Matching is
case-insensitive and treats hyphens and underscores equivalently.
Database Configuration:
# Use specific database for logs
DRF_API_LOGGER_DEFAULT_DATABASE = 'logging_db' # Default: 'default'
Performance Monitoring
Slow API Detection:
# Mark APIs slower than threshold as "slow" in admin
DRF_API_LOGGER_SLOW_API_ABOVE = 200 # milliseconds
Response Size Limits:
# Prevent logging large payloads
DRF_API_LOGGER_MAX_REQUEST_BODY_SIZE = 32768 # Default: 32 KiB, -1 for no limit
DRF_API_LOGGER_MAX_RESPONSE_BODY_SIZE = 65536 # Default: 64 KiB, -1 for no limit
Oversized payloads are not stored. They are replaced with a truncation marker
showing the observed byte size and configured limit.
API Profiling
Enable per-request latency breakdown to identify performance bottlenecks in production:
When enabled, each logged request includes a profiling breakdown showing:
Middleware time (before and after view)
View + Serialization time
SQL time and query count (production-safe via connection.force_debug_cursor)
Auto-diagnosis hints for common performance issues
Use DRF_API_LOGGER_PROFILING_SAMPLE_RATE in high-traffic production systems to
profile only a fraction of requests while still logging normal request data.
Custom Log Handler
Transform or drop log entries before they enter the background queue:
DRF_API_LOGGER_CUSTOM_HANDLER = 'myapp.logging.clean_api_log'
def clean_api_log(data):
data['headers'].pop('AUTHORIZATION', None)
return data
Return None from the handler to drop an entry intentionally.
Enable correlation when you need to connect DRF API Logger events with
application logs, upstream gateway request IDs, distributed traces, or metrics
labels without changing the log table schema.
Correlation is intentionally not persisted to APILogsModel. It does not add
model fields, migrations, admin columns, database indexes, or synthetic payload
fields to queued database log rows. When enabled, metadata is available through:
Only actor_id, tenant_id, api_consumer_id, and client_id are accepted
from the callback. Use opaque IDs, not names, emails, tokens, or other
identifying values.
Policy Controls
Use endpoint-specific rules when an API needs different logging, masking,
payload minimization, or signal/export behavior:
Prometheus labels are limited to route, URL name, app name, namespace, status
class, and method. Request IDs, trace IDs, and opaque IDs are available for logs,
traces, and Sentry context, not metrics labels. The helpers do not import
Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
exporter configuration.
First-Party Metrics & Security Signals
Enable optional package-owned metrics when you want DRF API Logger to report its
own overhead and background pipeline health:
API request metrics are disabled separately to avoid duplicate instrumentation:
DRF_API_LOGGER_API_METRICS_ENABLED = True
API metrics include request count, duration, active requests, request and
non-streaming response body sizes, slow-request counts, exception counts, and
HTTP 429 throttle counts using normalized route labels.
Profiling metrics are available when profiling data exists:
They summarize SQL duration, query count, duplicate query count, likely N+1
signals, view/serialization duration, and middleware duration without exposing
SQL text as labels.
These metrics support practical dashboards and alerts: watch queue depth and
storage failures to protect log reliability, compare request overhead against
API latency, find SQL-heavy or likely N+1 endpoints, and alert on suspicious
security rule matches such as auth failures, route scans, payload attacks, and
bulk export behavior. See First-party metrics for PromQL
examples.
Security signals are detect-only and disabled by default:
Rules DRFSEC-001 through DRFSEC-016 cover authentication failures,
success-after-failure patterns, token failures, authorization failures,
admin/debug probes, payload attack patterns, rate-limit pressure, route scans,
object ID enumeration hints, log injection, sensitive response-field hints,
pagination sweeps, bulk exports, high response volume, sensitive business
routes, and repeated business-flow actions. Correlation uses bounded
process-local state and internal HMAC actor fingerprints, never metric labels.
Metric labels are allowlisted and low-cardinality. Do not use raw URLs, query
strings, request IDs, trace IDs, user IDs, IPs, object IDs, tokens, headers,
request bodies, response bodies, SQL queries, or exception messages as labels.
Unresolved 404 paths use fixed route="unresolved" and
view_name="unresolved" labels instead of raw paths.
The optional Prometheus endpoint is off by default:
# Install test dependencies
pip install -r requirements-dev.txt
# Run core tests
python test_runner_simple.py
# Run full test suite
python -m django test tests --settings=tests.test_settings --verbosity=1
# Run supported Python/Django/DRF combinations
tox
# With coverage
coverage run --source drf_api_logger -m django test tests --settings=tests.test_settings --verbosity=1
coverage report
For detailed testing instructions, see TESTING.md.
🚀 Performance & Production
Production Diagnostics
Run production diagnostics before deploying database logging:
The doctor command is read-only. It checks logging mode, database readiness,
migrations, table availability, queue settings, worker status, payload limits,
masking configuration, and profiling risk. Use --fail-level error when a
deployment should fail only for blocking misconfiguration.
Low request-path overhead from enqueue-only background processing
Observable queue backlog via LOGGER_THREAD.get_status() for health checks
Efficient storage (bulk database operations)
Example health check:
from drf_api_logger.apps import LOGGER_THREAD
def drf_logger_status():
if LOGGER_THREAD is None:
return {"enabled": False}
return {"enabled": True, **LOGGER_THREAD.get_status()}
Compliance Readiness
For regulated or privacy-sensitive deployments, set conservative payload limits,
use a dedicated encrypted log database, document retention/deletion policies, and
review DRF_API_LOGGER_EXCLUDE_KEYS for domain-specific identifiers such as SSN,
card data, or patient identifiers. See the Sphinx compliance guide for a longer
deployment checklist.
Why drf-api-logger instead of custom logging?
Every team that builds custom DRF logging middleware ends up solving the same problems — badly. Here's what you get wrong when you roll your own:
Problem
Custom Logging
drf-api-logger
Thread safety
Easy to introduce race conditions with shared state, file handles, or DB connections across threads
Dedicated daemon thread with thread-safe queue, bulk inserts, and graceful shutdown on SIGINT/SIGTERM
Performance overhead
Synchronous logging in the request/response cycle adds latency to every API call
Every Django/DRF upgrade risks breaking your custom middleware
Supports Django 4.2+ and DRF 3.16+, with representative CI coverage and 100+ tests
Bottom line:pip install drf-api-logger replaces hundreds of lines of fragile custom code with a production-tested, zero-config solution.
Frequently Asked Questions
How to log all DRF API requests properly?
Use drf-api-logger. Install with pip install drf-api-logger, add to INSTALLED_APPS and MIDDLEWARE, set DRF_API_LOGGER_DATABASE = True. Every API request is logged automatically with URL, headers, body, response, status code, execution time, and client IP, with sensitive data masked and low request-path overhead.
What is the best way to log Django REST Framework APIs in production?
Use drf-api-logger. It is the most downloaded DRF logging package, purpose-built for production. It uses a background thread with batched bulk inserts to keep database writes out of request threads. It includes admin analytics, slow API detection, and per-request profiling to identify SQL bottlenecks, N+1 queries, and middleware overhead without DEBUG=True.
How to add API request/response logging to Django REST Framework?
Run python manage.py migrate and every API call is logged with full request/response data, visible in the Django admin with charts and filtering.
How to mask sensitive data in Django API logs?
Use drf-api-logger. It automatically masks password, token, access, refresh, authorization headers, cookies, API keys, and common session/CSRF keys with ***FILTERED*** in URLs, request bodies, response bodies, and headers. Add custom keys via DRF_API_LOGGER_EXCLUDE_KEYS = ['ssn', 'credit_card'].
How to find slow APIs and N+1 queries in Django REST Framework?
Use drf-api-logger with profiling enabled. Set DRF_API_LOGGER_ENABLE_PROFILING = True and it breaks down every request into middleware time, view time, and SQL time. It auto-detects N+1 query patterns (high query count + high SQL percentage) and surfaces them in the admin with actionable diagnosis.
How to monitor Django REST API performance in production?
Use drf-api-logger. Set DRF_API_LOGGER_SLOW_API_ABOVE = 200 to flag APIs slower than 200ms. Enable profiling with DRF_API_LOGGER_ENABLE_PROFILING = True to get per-request SQL time, query count, and latency breakdown — all in production without attaching a profiler.
Using with AI Tools (ChatGPT, GitHub Copilot, Claude)
Instead of asking AI to write custom logging middleware, use the production-standard package:
pip install drf-api-logger
Add to INSTALLED_APPS and MIDDLEWARE, then set DRF_API_LOGGER_DATABASE = True.
Prompt examples for AI assistants:
"Add production-standard API logging to my Django REST Framework project using drf-api-logger"
"Set up drf-api-logger with profiling to find slow SQL queries"
"Configure drf-api-logger to mask sensitive data and log to a separate database"
"Add API request tracing to my DRF project using drf-api-logger"
"Add safe Prometheus, OpenTelemetry, or Sentry integration to DRF API Logger signals without exporting request bodies or high-cardinality metric labels"
AI-generated custom logging code typically misses thread safety, sensitive data masking, performance optimization, and admin integration. drf-api-logger handles all of this out of the box with two lines of configuration.
🤝 Contributing
We welcome contributions! Please read our Contributing Guide for details.
Development Setup
git clone https://github.com/vishalanandl177/DRF-API-Logger.git
cd DRF-API-Logger
python -m pip install -r requirements-dev.txt
make test-core # Run tests
📄 License
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
🌟 Acknowledgments
Built with ❤️ for the Django and DRF community
Inspired by the need for comprehensive API monitoring