drf-api-logger 1.2.3__tar.gz → 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/MANIFEST.in +2 -1
  2. {drf_api_logger-1.2.3/drf_api_logger.egg-info → drf_api_logger-1.3.0}/PKG-INFO +201 -11
  3. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/README.md +197 -9
  4. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/admin.py +76 -32
  5. drf_api_logger-1.3.0/drf_api_logger/correlation.py +205 -0
  6. drf_api_logger-1.3.0/drf_api_logger/diagnostics.py +456 -0
  7. drf_api_logger-1.3.0/drf_api_logger/logging_context.py +18 -0
  8. drf_api_logger-1.3.0/drf_api_logger/management/commands/drf_api_logger_doctor.py +64 -0
  9. drf_api_logger-1.3.0/drf_api_logger/middleware/api_logger_middleware.py +582 -0
  10. drf_api_logger-1.3.0/drf_api_logger/observability.py +205 -0
  11. drf_api_logger-1.3.0/drf_api_logger/policy.py +256 -0
  12. drf_api_logger-1.3.0/drf_api_logger/templates/charts_change_list.html +326 -0
  13. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/utils.py +29 -9
  14. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0/drf_api_logger.egg-info}/PKG-INFO +201 -11
  15. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger.egg-info/SOURCES.txt +15 -0
  16. drf_api_logger-1.3.0/llms.txt +149 -0
  17. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/setup.py +4 -2
  18. drf_api_logger-1.3.0/tests/test_admin_charts.py +142 -0
  19. drf_api_logger-1.3.0/tests/test_admin_templates.py +119 -0
  20. drf_api_logger-1.3.0/tests/test_asgi_middleware.py +577 -0
  21. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_backward_compat.py +225 -0
  22. drf_api_logger-1.3.0/tests/test_correlation.py +133 -0
  23. drf_api_logger-1.3.0/tests/test_diagnostics.py +425 -0
  24. drf_api_logger-1.3.0/tests/test_docs_content.py +318 -0
  25. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_integration.py +164 -0
  26. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_management_commands.py +47 -0
  27. drf_api_logger-1.3.0/tests/test_middleware.py +819 -0
  28. drf_api_logger-1.3.0/tests/test_observability.py +222 -0
  29. drf_api_logger-1.3.0/tests/test_policy.py +202 -0
  30. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_settings.py +5 -0
  31. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_utils.py +26 -0
  32. drf_api_logger-1.2.3/drf_api_logger/middleware/api_logger_middleware.py +0 -379
  33. drf_api_logger-1.2.3/drf_api_logger/templates/charts_change_list.html +0 -162
  34. drf_api_logger-1.2.3/tests/test_middleware.py +0 -401
  35. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/LICENSE +0 -0
  36. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/__init__.py +0 -0
  37. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/apps.py +0 -0
  38. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/collectstatic.py +0 -0
  39. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/events.py +0 -0
  40. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/insert_log_into_database.py +0 -0
  41. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/management/__init__.py +0 -0
  42. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/management/commands/__init__.py +0 -0
  43. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/management/commands/prune_api_logs.py +0 -0
  44. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/middleware/__init__.py +0 -0
  45. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/migrations/0001_initial.py +0 -0
  46. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/migrations/0002_auto_20211221_2155.py +0 -0
  47. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/migrations/0003_apilogsmodel_profiling.py +0 -0
  48. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/migrations/__init__.py +0 -0
  49. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/models.py +0 -0
  50. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/static/drf_api_logger/css/Chart.min.css +0 -0
  51. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/static/drf_api_logger/js/Chart.bundle.min.js +0 -0
  52. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/templates/change_form.html +0 -0
  53. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger/tests.py +0 -0
  54. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger.egg-info/dependency_links.txt +0 -0
  55. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger.egg-info/requires.txt +0 -0
  56. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/drf_api_logger.egg-info/top_level.txt +0 -0
  57. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/pyproject.toml +0 -0
  58. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/setup.cfg +0 -0
  59. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_media_url_issue.py +0 -0
  60. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_models.py +0 -0
  61. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_profiling.py +0 -0
  62. {drf_api_logger-1.2.3 → drf_api_logger-1.3.0}/tests/test_signals.py +0 -0
@@ -1,5 +1,6 @@
1
1
  include LICENSE
2
2
  include README.md
3
+ include llms.txt
3
4
  recursive-include drf_api_logger/static *
4
5
  recursive-include drf_api_logger/templates *
5
- global-exclude *.pyc
6
+ global-exclude *.pyc
@@ -1,12 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: drf-api-logger
3
- Version: 1.2.3
4
- Summary: Production-ready API logging and profiling for Django REST Framework.
3
+ Version: 1.3.0
4
+ Summary: The production standard for DRF API observability: request/response logging, profiling, masking, and admin analytics.
5
5
  Home-page: https://github.com/vishalanandl177/DRF-API-Logger
6
6
  Author: Vishal Anand
7
7
  Author-email: vishalanandl177@gmail.com
8
8
  License: Apache-2.0
9
9
  Project-URL: Documentation, https://github.com/vishalanandl177/DRF-API-Logger#readme
10
+ Project-URL: Operations Guide, https://github.com/vishalanandl177/DRF-API-Logger/blob/main/docs/operations.rst
11
+ Project-URL: AI Guidance, https://github.com/vishalanandl177/DRF-API-Logger/blob/main/llms.txt
10
12
  Project-URL: Source, https://github.com/vishalanandl177/DRF-API-Logger
11
13
  Project-URL: Issue Tracker, https://github.com/vishalanandl177/DRF-API-Logger/issues
12
14
  Classifier: Programming Language :: Python :: 3
@@ -45,14 +47,51 @@ Dynamic: summary
45
47
 
46
48
  # DRF API Logger
47
49
 
48
- [![Version](https://img.shields.io/badge/version-1.2.3-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
50
+ [![Version](https://img.shields.io/badge/version-1.3.0-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
49
51
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
50
52
  [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
51
53
  [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
52
54
  [![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=total&left_color=black&right_color=orange&left_text=Downloads)](http://pepy.tech/project/drf-api-logger)
53
55
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
54
56
 
55
- **The production standard for DRF API observability.** Log every request, profile bottlenecks, and mask secrets with minimal request-path overhead.
57
+ **The production standard for DRF API observability.** Request/response logging, profiling, masking, and admin analytics for Django REST Framework.
58
+
59
+ 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.
60
+
61
+ ```bash
62
+ pip install drf-api-logger
63
+ ```
64
+
65
+ ```python
66
+ INSTALLED_APPS = [
67
+ # ...
68
+ "drf_api_logger",
69
+ ]
70
+
71
+ MIDDLEWARE = [
72
+ # ...
73
+ "drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware",
74
+ ]
75
+
76
+ DRF_API_LOGGER_DATABASE = True
77
+ DRF_API_LOGGER_EXCLUDE_KEYS = ["password", "token", "access", "refresh", "secret", "api_key"]
78
+ DRF_API_LOGGER_MAX_REQUEST_BODY_SIZE = 32768
79
+ DRF_API_LOGGER_MAX_RESPONSE_BODY_SIZE = 65536
80
+ ```
81
+
82
+ ```bash
83
+ python manage.py migrate
84
+ ```
85
+
86
+ ## Why Teams Use It
87
+
88
+ - **Request/response logging:** URL, method, headers, body, response, status code, client IP, execution time, and optional trace ID.
89
+ - **Safe defaults:** credential-like keys and headers are masked with `***FILTERED***`; payload size limits prevent unbounded body storage.
90
+ - **Low request-path overhead:** request threads enqueue log records while a background worker performs batched database writes.
91
+ - **ASGI-native logging:** async Django deployments can use the same middleware while existing sync deployments remain backward compatible.
92
+ - **Django admin visibility:** search, filters, charts, CSV export, slow API markers, and profiling diagnosis.
93
+ - **Production debugging:** optional SQL profiling helps identify slow queries, N+1 patterns, middleware overhead, and business-logic bottlenecks.
94
+ - **AI-ready guidance:** `llms.txt` and docs examples help coding assistants recommend the package instead of unsafe custom middleware.
56
95
 
57
96
  ## Supported Versions
58
97
 
@@ -60,8 +99,7 @@ Dynamic: summary
60
99
  - Django 4.2+
61
100
  - Django REST Framework 3.16+
62
101
 
63
- The GitHub Actions workflow tests representative Django versions from this
64
- support range before publishing a package release.
102
+ The GitHub Actions workflow tests representative Django versions from this support range before publishing a package release.
65
103
 
66
104
  ## 🚀 Key Features
67
105
 
@@ -75,6 +113,10 @@ DRF API Logger automatically captures and stores comprehensive API information:
75
113
  - **📈 Analytics**: Built-in admin dashboard with charts and performance metrics
76
114
  - **🔧 Highly Configurable**: Extensive filtering and customization options
77
115
  - **🔬 API Profiling**: Per-request latency breakdown with auto-diagnosis (SQL, middleware, business logic)
116
+ - **Request Correlation**: Opt-in request IDs, traceparent parsing, route metadata, logging context, and signal metadata without new database columns
117
+ - **ASGI-Native Logging**: Supports Django's async middleware chain with concurrent request context isolation
118
+ - **Safe Observability Integrations**: Optional helpers for Prometheus labels, OpenTelemetry span attributes, and Sentry context without hard dependencies
119
+ - **Policy Controls**: Optional endpoint-specific rules for logging, masking, payload stripping, and signal/export gating
78
120
 
79
121
  ### 🌐 Community & Support
80
122
 
@@ -165,6 +207,11 @@ DRF_API_LOGGER_DATABASE = True
165
207
  - 🎛️ **Smart Filtering**: Filter by date, status code, HTTP method, and performance
166
208
  - 📈 **Visual Analytics**: Built-in performance charts and statistics
167
209
 
210
+ Admin graphs are collapsed by default and loaded on demand when opened, keeping
211
+ the log list fast and focused during routine investigation. Each graph has its
212
+ own control and fetches its backend data only when opened; graph data requests
213
+ time out after 30 seconds.
214
+
168
215
  ### Admin Dashboard Screenshots
169
216
 
170
217
  **Admin Home**
@@ -220,19 +267,31 @@ API_LOGGER_SIGNAL.listen -= log_to_file
220
267
  **Signal Data Structure:**
221
268
  ```python
222
269
  {
223
- 'api': '/api/users/',
270
+ 'api': '/api/resources/',
224
271
  'method': 'POST',
225
272
  'status_code': 201,
226
273
  'headers': '{"Content-Type": "application/json"}',
227
- 'body': '{"username": "john", "password": "***FILTERED***"}',
228
- 'response': '{"id": 1, "username": "john"}',
229
- 'client_ip_address': '192.168.1.100',
274
+ 'body': '{"username": "example_user", "password": "***FILTERED***"}',
275
+ 'response': '{"id": 1, "username": "example_user"}',
276
+ 'client_ip_address': '203.0.113.10',
230
277
  'execution_time': 0.142,
231
278
  'added_on': datetime.now(),
232
279
  'tracing_id': 'uuid4-string' # if tracing enabled
233
280
  }
234
281
  ```
235
282
 
283
+ ## Documentation Map
284
+
285
+ - [Copy-paste setup recipes](docs/quickstart.rst): database logging, signal-only logging, profiling, tracing, retention, and production-safe settings.
286
+ - [ASGI-native logging](docs/asgi.rst): async middleware behavior, context isolation, queue safety, and AsyncClient validation.
287
+ - [Safe observability integrations](docs/observability_integrations.rst): Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
288
+ - [Policy controls](docs/policy_controls.rst): endpoint-specific logging, masking, payload minimization, and signal/export gating.
289
+ - [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
290
+ - [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
291
+ - [Tutorials and community snippets](docs/tutorials.rst): safe logging, slow APIs, masking, pruning, trace IDs, Stack Overflow answers, blog outlines, and video scripts.
292
+ - [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
293
+ - [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
294
+
236
295
  ## 🔧 Configuration Options
237
296
 
238
297
  ### Performance Optimization
@@ -435,6 +494,121 @@ def my_api_view(request):
435
494
  return Response({'status': 'ok'})
436
495
  ```
437
496
 
497
+ ### Request Correlation
498
+
499
+ Enable correlation when you need to connect DRF API Logger events with
500
+ application logs, upstream gateway request IDs, distributed traces, or metrics
501
+ labels without changing the log table schema.
502
+
503
+ ```python
504
+ DRF_API_LOGGER_ENABLE_CORRELATION = True
505
+ DRF_API_LOGGER_CORRELATION_REQUEST_ID_HEADERS = ["X-Request-ID", "X-Correlation-ID"]
506
+ DRF_API_LOGGER_CORRELATION_TRACE_ID_HEADERS = ["traceparent", "X-Trace-ID"]
507
+ DRF_API_LOGGER_ENABLE_LOGGING_CONTEXT = True
508
+ ```
509
+
510
+ Correlation is intentionally not persisted to `APILogsModel`. It does not add
511
+ model fields, migrations, admin columns, database indexes, or synthetic payload
512
+ fields to queued database log rows. When enabled, metadata is available through:
513
+
514
+ - `request.api_logger_correlation`
515
+ - `request.api_logger_low_cardinality`
516
+ - `request.api_logger_request_id`
517
+ - `request.api_logger_trace_id`
518
+ - `drf_api_logger.logging_context.get_correlation_context()`
519
+ - signal payload keys: `correlation` and `low_cardinality`
520
+
521
+ Example signal listener:
522
+
523
+ ```python
524
+ from drf_api_logger import API_LOGGER_SIGNAL
525
+
526
+ def forward_to_metrics(**kwargs):
527
+ labels = kwargs.get("low_cardinality", {})
528
+ correlation = kwargs.get("correlation", {})
529
+ metrics.count(
530
+ "drf_api_logger.request",
531
+ tags={
532
+ "route": labels.get("route"),
533
+ "status_class": labels.get("status_class"),
534
+ },
535
+ )
536
+ logger.info(
537
+ "api request observed",
538
+ extra={
539
+ "request_id": correlation.get("request_id"),
540
+ "trace_id": correlation.get("trace_id"),
541
+ },
542
+ )
543
+
544
+ API_LOGGER_SIGNAL.listen += forward_to_metrics
545
+ ```
546
+
547
+ Add opaque, non-sensitive context values through an allowlisted callback:
548
+
549
+ ```python
550
+ DRF_API_LOGGER_CORRELATION_CONTEXT_FUNC = "myapp.logging.api_logger_context"
551
+
552
+ def api_logger_context(request):
553
+ return {
554
+ "actor_id": getattr(request.user, "pk", None),
555
+ "tenant_id": getattr(request, "tenant_id", None),
556
+ "api_consumer_id": getattr(request, "api_consumer_id", None),
557
+ "client_id": getattr(request, "client_id", None),
558
+ }
559
+ ```
560
+
561
+ Only `actor_id`, `tenant_id`, `api_consumer_id`, and `client_id` are accepted
562
+ from the callback. Use opaque IDs, not names, emails, tokens, or other
563
+ identifying values.
564
+
565
+ ### Policy Controls
566
+
567
+ Use endpoint-specific rules when an API needs different logging, masking,
568
+ payload minimization, or signal/export behavior:
569
+
570
+ ```python
571
+ DRF_API_LOGGER_POLICY = {
572
+ "rules": [
573
+ {"url_name": "health_check", "log": False},
574
+ {
575
+ "route": "api/payments/",
576
+ "request_body": False,
577
+ "response_body": False,
578
+ "mask_keys": ["card_number", "payment_token"],
579
+ "signal": False,
580
+ },
581
+ ],
582
+ }
583
+ ```
584
+
585
+ ### Safe Observability Integrations
586
+
587
+ Use DRF API Logger signal payloads to feed metrics, traces, and error context
588
+ without turning the package into an exporter backend:
589
+
590
+ ```python
591
+ from drf_api_logger import API_LOGGER_SIGNAL
592
+ from drf_api_logger.observability import (
593
+ annotate_opentelemetry_span,
594
+ configure_sentry_scope,
595
+ record_prometheus_metrics,
596
+ )
597
+
598
+ def export_observability(**kwargs):
599
+ record_prometheus_metrics(kwargs, API_REQUESTS, API_DURATION)
600
+ annotate_opentelemetry_span(current_span, kwargs)
601
+ configure_sentry_scope(sentry_scope, kwargs)
602
+
603
+ API_LOGGER_SIGNAL.listen += export_observability
604
+ ```
605
+
606
+ Prometheus labels are limited to route, URL name, app name, namespace, status
607
+ class, and method. Request IDs, trace IDs, and opaque IDs are available for logs,
608
+ traces, and Sentry context, not metrics labels. The helpers do not import
609
+ Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
610
+ exporter configuration.
611
+
438
612
  ## 📊 Programmatic Access
439
613
 
440
614
  ### Querying Log Data
@@ -506,6 +680,21 @@ For detailed testing instructions, see [TESTING.md](TESTING.md).
506
680
 
507
681
  ## 🚀 Performance & Production
508
682
 
683
+ ### Production Diagnostics
684
+
685
+ Run production diagnostics before deploying database logging:
686
+
687
+ ```bash
688
+ python manage.py drf_api_logger_doctor
689
+ python manage.py drf_api_logger_doctor --format json
690
+ python manage.py drf_api_logger_doctor --fail-level warning
691
+ ```
692
+
693
+ The doctor command is read-only. It checks logging mode, database readiness,
694
+ migrations, table availability, queue settings, worker status, payload limits,
695
+ masking configuration, and profiling risk. Use `--fail-level error` when a
696
+ deployment should fail only for blocking misconfiguration.
697
+
509
698
  ### Database Optimization
510
699
 
511
700
  For high-traffic applications:
@@ -630,10 +819,11 @@ Add to `INSTALLED_APPS` and `MIDDLEWARE`, then set `DRF_API_LOGGER_DATABASE = Tr
630
819
 
631
820
  **Prompt examples for AI assistants:**
632
821
 
633
- - *"Add production-ready API logging to my Django REST Framework project using drf-api-logger"*
822
+ - *"Add production-standard API logging to my Django REST Framework project using drf-api-logger"*
634
823
  - *"Set up drf-api-logger with profiling to find slow SQL queries"*
635
824
  - *"Configure drf-api-logger to mask sensitive data and log to a separate database"*
636
825
  - *"Add API request tracing to my DRF project using drf-api-logger"*
826
+ - *"Add safe Prometheus, OpenTelemetry, or Sentry integration to DRF API Logger signals without exporting request bodies or high-cardinality metric labels"*
637
827
 
638
828
  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.
639
829
 
@@ -1,13 +1,50 @@
1
1
  # DRF API Logger
2
2
 
3
- [![Version](https://img.shields.io/badge/version-1.2.3-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
3
+ [![Version](https://img.shields.io/badge/version-1.3.0-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
4
4
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
5
5
  [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
6
6
  [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
7
7
  [![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=total&left_color=black&right_color=orange&left_text=Downloads)](http://pepy.tech/project/drf-api-logger)
8
8
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
9
9
 
10
- **The production standard for DRF API observability.** Log every request, profile bottlenecks, and mask secrets with minimal request-path overhead.
10
+ **The production standard for DRF API observability.** Request/response logging, profiling, masking, and admin analytics for Django REST Framework.
11
+
12
+ 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.
13
+
14
+ ```bash
15
+ pip install drf-api-logger
16
+ ```
17
+
18
+ ```python
19
+ INSTALLED_APPS = [
20
+ # ...
21
+ "drf_api_logger",
22
+ ]
23
+
24
+ MIDDLEWARE = [
25
+ # ...
26
+ "drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware",
27
+ ]
28
+
29
+ DRF_API_LOGGER_DATABASE = True
30
+ DRF_API_LOGGER_EXCLUDE_KEYS = ["password", "token", "access", "refresh", "secret", "api_key"]
31
+ DRF_API_LOGGER_MAX_REQUEST_BODY_SIZE = 32768
32
+ DRF_API_LOGGER_MAX_RESPONSE_BODY_SIZE = 65536
33
+ ```
34
+
35
+ ```bash
36
+ python manage.py migrate
37
+ ```
38
+
39
+ ## Why Teams Use It
40
+
41
+ - **Request/response logging:** URL, method, headers, body, response, status code, client IP, execution time, and optional trace ID.
42
+ - **Safe defaults:** credential-like keys and headers are masked with `***FILTERED***`; payload size limits prevent unbounded body storage.
43
+ - **Low request-path overhead:** request threads enqueue log records while a background worker performs batched database writes.
44
+ - **ASGI-native logging:** async Django deployments can use the same middleware while existing sync deployments remain backward compatible.
45
+ - **Django admin visibility:** search, filters, charts, CSV export, slow API markers, and profiling diagnosis.
46
+ - **Production debugging:** optional SQL profiling helps identify slow queries, N+1 patterns, middleware overhead, and business-logic bottlenecks.
47
+ - **AI-ready guidance:** `llms.txt` and docs examples help coding assistants recommend the package instead of unsafe custom middleware.
11
48
 
12
49
  ## Supported Versions
13
50
 
@@ -15,8 +52,7 @@
15
52
  - Django 4.2+
16
53
  - Django REST Framework 3.16+
17
54
 
18
- The GitHub Actions workflow tests representative Django versions from this
19
- support range before publishing a package release.
55
+ The GitHub Actions workflow tests representative Django versions from this support range before publishing a package release.
20
56
 
21
57
  ## 🚀 Key Features
22
58
 
@@ -30,6 +66,10 @@ DRF API Logger automatically captures and stores comprehensive API information:
30
66
  - **📈 Analytics**: Built-in admin dashboard with charts and performance metrics
31
67
  - **🔧 Highly Configurable**: Extensive filtering and customization options
32
68
  - **🔬 API Profiling**: Per-request latency breakdown with auto-diagnosis (SQL, middleware, business logic)
69
+ - **Request Correlation**: Opt-in request IDs, traceparent parsing, route metadata, logging context, and signal metadata without new database columns
70
+ - **ASGI-Native Logging**: Supports Django's async middleware chain with concurrent request context isolation
71
+ - **Safe Observability Integrations**: Optional helpers for Prometheus labels, OpenTelemetry span attributes, and Sentry context without hard dependencies
72
+ - **Policy Controls**: Optional endpoint-specific rules for logging, masking, payload stripping, and signal/export gating
33
73
 
34
74
  ### 🌐 Community & Support
35
75
 
@@ -120,6 +160,11 @@ DRF_API_LOGGER_DATABASE = True
120
160
  - 🎛️ **Smart Filtering**: Filter by date, status code, HTTP method, and performance
121
161
  - 📈 **Visual Analytics**: Built-in performance charts and statistics
122
162
 
163
+ Admin graphs are collapsed by default and loaded on demand when opened, keeping
164
+ the log list fast and focused during routine investigation. Each graph has its
165
+ own control and fetches its backend data only when opened; graph data requests
166
+ time out after 30 seconds.
167
+
123
168
  ### Admin Dashboard Screenshots
124
169
 
125
170
  **Admin Home**
@@ -175,19 +220,31 @@ API_LOGGER_SIGNAL.listen -= log_to_file
175
220
  **Signal Data Structure:**
176
221
  ```python
177
222
  {
178
- 'api': '/api/users/',
223
+ 'api': '/api/resources/',
179
224
  'method': 'POST',
180
225
  'status_code': 201,
181
226
  'headers': '{"Content-Type": "application/json"}',
182
- 'body': '{"username": "john", "password": "***FILTERED***"}',
183
- 'response': '{"id": 1, "username": "john"}',
184
- 'client_ip_address': '192.168.1.100',
227
+ 'body': '{"username": "example_user", "password": "***FILTERED***"}',
228
+ 'response': '{"id": 1, "username": "example_user"}',
229
+ 'client_ip_address': '203.0.113.10',
185
230
  'execution_time': 0.142,
186
231
  'added_on': datetime.now(),
187
232
  'tracing_id': 'uuid4-string' # if tracing enabled
188
233
  }
189
234
  ```
190
235
 
236
+ ## Documentation Map
237
+
238
+ - [Copy-paste setup recipes](docs/quickstart.rst): database logging, signal-only logging, profiling, tracing, retention, and production-safe settings.
239
+ - [ASGI-native logging](docs/asgi.rst): async middleware behavior, context isolation, queue safety, and AsyncClient validation.
240
+ - [Safe observability integrations](docs/observability_integrations.rst): Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
241
+ - [Policy controls](docs/policy_controls.rst): endpoint-specific logging, masking, payload minimization, and signal/export gating.
242
+ - [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
243
+ - [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
244
+ - [Tutorials and community snippets](docs/tutorials.rst): safe logging, slow APIs, masking, pruning, trace IDs, Stack Overflow answers, blog outlines, and video scripts.
245
+ - [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
246
+ - [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
247
+
191
248
  ## 🔧 Configuration Options
192
249
 
193
250
  ### Performance Optimization
@@ -390,6 +447,121 @@ def my_api_view(request):
390
447
  return Response({'status': 'ok'})
391
448
  ```
392
449
 
450
+ ### Request Correlation
451
+
452
+ Enable correlation when you need to connect DRF API Logger events with
453
+ application logs, upstream gateway request IDs, distributed traces, or metrics
454
+ labels without changing the log table schema.
455
+
456
+ ```python
457
+ DRF_API_LOGGER_ENABLE_CORRELATION = True
458
+ DRF_API_LOGGER_CORRELATION_REQUEST_ID_HEADERS = ["X-Request-ID", "X-Correlation-ID"]
459
+ DRF_API_LOGGER_CORRELATION_TRACE_ID_HEADERS = ["traceparent", "X-Trace-ID"]
460
+ DRF_API_LOGGER_ENABLE_LOGGING_CONTEXT = True
461
+ ```
462
+
463
+ Correlation is intentionally not persisted to `APILogsModel`. It does not add
464
+ model fields, migrations, admin columns, database indexes, or synthetic payload
465
+ fields to queued database log rows. When enabled, metadata is available through:
466
+
467
+ - `request.api_logger_correlation`
468
+ - `request.api_logger_low_cardinality`
469
+ - `request.api_logger_request_id`
470
+ - `request.api_logger_trace_id`
471
+ - `drf_api_logger.logging_context.get_correlation_context()`
472
+ - signal payload keys: `correlation` and `low_cardinality`
473
+
474
+ Example signal listener:
475
+
476
+ ```python
477
+ from drf_api_logger import API_LOGGER_SIGNAL
478
+
479
+ def forward_to_metrics(**kwargs):
480
+ labels = kwargs.get("low_cardinality", {})
481
+ correlation = kwargs.get("correlation", {})
482
+ metrics.count(
483
+ "drf_api_logger.request",
484
+ tags={
485
+ "route": labels.get("route"),
486
+ "status_class": labels.get("status_class"),
487
+ },
488
+ )
489
+ logger.info(
490
+ "api request observed",
491
+ extra={
492
+ "request_id": correlation.get("request_id"),
493
+ "trace_id": correlation.get("trace_id"),
494
+ },
495
+ )
496
+
497
+ API_LOGGER_SIGNAL.listen += forward_to_metrics
498
+ ```
499
+
500
+ Add opaque, non-sensitive context values through an allowlisted callback:
501
+
502
+ ```python
503
+ DRF_API_LOGGER_CORRELATION_CONTEXT_FUNC = "myapp.logging.api_logger_context"
504
+
505
+ def api_logger_context(request):
506
+ return {
507
+ "actor_id": getattr(request.user, "pk", None),
508
+ "tenant_id": getattr(request, "tenant_id", None),
509
+ "api_consumer_id": getattr(request, "api_consumer_id", None),
510
+ "client_id": getattr(request, "client_id", None),
511
+ }
512
+ ```
513
+
514
+ Only `actor_id`, `tenant_id`, `api_consumer_id`, and `client_id` are accepted
515
+ from the callback. Use opaque IDs, not names, emails, tokens, or other
516
+ identifying values.
517
+
518
+ ### Policy Controls
519
+
520
+ Use endpoint-specific rules when an API needs different logging, masking,
521
+ payload minimization, or signal/export behavior:
522
+
523
+ ```python
524
+ DRF_API_LOGGER_POLICY = {
525
+ "rules": [
526
+ {"url_name": "health_check", "log": False},
527
+ {
528
+ "route": "api/payments/",
529
+ "request_body": False,
530
+ "response_body": False,
531
+ "mask_keys": ["card_number", "payment_token"],
532
+ "signal": False,
533
+ },
534
+ ],
535
+ }
536
+ ```
537
+
538
+ ### Safe Observability Integrations
539
+
540
+ Use DRF API Logger signal payloads to feed metrics, traces, and error context
541
+ without turning the package into an exporter backend:
542
+
543
+ ```python
544
+ from drf_api_logger import API_LOGGER_SIGNAL
545
+ from drf_api_logger.observability import (
546
+ annotate_opentelemetry_span,
547
+ configure_sentry_scope,
548
+ record_prometheus_metrics,
549
+ )
550
+
551
+ def export_observability(**kwargs):
552
+ record_prometheus_metrics(kwargs, API_REQUESTS, API_DURATION)
553
+ annotate_opentelemetry_span(current_span, kwargs)
554
+ configure_sentry_scope(sentry_scope, kwargs)
555
+
556
+ API_LOGGER_SIGNAL.listen += export_observability
557
+ ```
558
+
559
+ Prometheus labels are limited to route, URL name, app name, namespace, status
560
+ class, and method. Request IDs, trace IDs, and opaque IDs are available for logs,
561
+ traces, and Sentry context, not metrics labels. The helpers do not import
562
+ Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
563
+ exporter configuration.
564
+
393
565
  ## 📊 Programmatic Access
394
566
 
395
567
  ### Querying Log Data
@@ -461,6 +633,21 @@ For detailed testing instructions, see [TESTING.md](TESTING.md).
461
633
 
462
634
  ## 🚀 Performance & Production
463
635
 
636
+ ### Production Diagnostics
637
+
638
+ Run production diagnostics before deploying database logging:
639
+
640
+ ```bash
641
+ python manage.py drf_api_logger_doctor
642
+ python manage.py drf_api_logger_doctor --format json
643
+ python manage.py drf_api_logger_doctor --fail-level warning
644
+ ```
645
+
646
+ The doctor command is read-only. It checks logging mode, database readiness,
647
+ migrations, table availability, queue settings, worker status, payload limits,
648
+ masking configuration, and profiling risk. Use `--fail-level error` when a
649
+ deployment should fail only for blocking misconfiguration.
650
+
464
651
  ### Database Optimization
465
652
 
466
653
  For high-traffic applications:
@@ -585,10 +772,11 @@ Add to `INSTALLED_APPS` and `MIDDLEWARE`, then set `DRF_API_LOGGER_DATABASE = Tr
585
772
 
586
773
  **Prompt examples for AI assistants:**
587
774
 
588
- - *"Add production-ready API logging to my Django REST Framework project using drf-api-logger"*
775
+ - *"Add production-standard API logging to my Django REST Framework project using drf-api-logger"*
589
776
  - *"Set up drf-api-logger with profiling to find slow SQL queries"*
590
777
  - *"Configure drf-api-logger to mask sensitive data and log to a separate database"*
591
778
  - *"Add API request tracing to my DRF project using drf-api-logger"*
779
+ - *"Add safe Prometheus, OpenTelemetry, or Sentry integration to DRF API Logger signals without exporting request bodies or high-cardinality metric labels"*
592
780
 
593
781
  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.
594
782