drf-api-logger 1.2.2__tar.gz → 1.2.3__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 (49) hide show
  1. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/PKG-INFO +73 -34
  2. drf_api_logger-1.2.2/drf_api_logger.egg-info/PKG-INFO → drf_api_logger-1.2.3/README.md +54 -60
  3. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/admin.py +74 -11
  4. drf_api_logger-1.2.3/drf_api_logger/management/__init__.py +1 -0
  5. drf_api_logger-1.2.3/drf_api_logger/management/commands/__init__.py +1 -0
  6. drf_api_logger-1.2.3/drf_api_logger/management/commands/prune_api_logs.py +122 -0
  7. drf_api_logger-1.2.3/drf_api_logger/templates/change_form.html +96 -0
  8. drf_api_logger-1.2.2/README.md → drf_api_logger-1.2.3/drf_api_logger.egg-info/PKG-INFO +99 -24
  9. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger.egg-info/SOURCES.txt +5 -3
  10. drf_api_logger-1.2.3/drf_api_logger.egg-info/requires.txt +3 -0
  11. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger.egg-info/top_level.txt +0 -1
  12. drf_api_logger-1.2.3/setup.py +59 -0
  13. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_backward_compat.py +6 -1
  14. drf_api_logger-1.2.3/tests/test_management_commands.py +123 -0
  15. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_models.py +68 -0
  16. drf_api_logger-1.2.2/drf_api_logger/templates/change_form.html +0 -8
  17. drf_api_logger-1.2.2/drf_api_logger.egg-info/requires.txt +0 -2
  18. drf_api_logger-1.2.2/setup.py +0 -39
  19. drf_api_logger-1.2.2/tests/__init__.py +0 -3
  20. drf_api_logger-1.2.2/tests/urls.py +0 -35
  21. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/LICENSE +0 -0
  22. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/MANIFEST.in +0 -0
  23. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/__init__.py +0 -0
  24. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/apps.py +0 -0
  25. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/collectstatic.py +0 -0
  26. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/events.py +0 -0
  27. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/insert_log_into_database.py +0 -0
  28. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/middleware/__init__.py +0 -0
  29. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/middleware/api_logger_middleware.py +0 -0
  30. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/migrations/0001_initial.py +0 -0
  31. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/migrations/0002_auto_20211221_2155.py +0 -0
  32. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/migrations/0003_apilogsmodel_profiling.py +0 -0
  33. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/migrations/__init__.py +0 -0
  34. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/models.py +0 -0
  35. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/static/drf_api_logger/css/Chart.min.css +0 -0
  36. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/static/drf_api_logger/js/Chart.bundle.min.js +0 -0
  37. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/templates/charts_change_list.html +0 -0
  38. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/tests.py +0 -0
  39. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger/utils.py +0 -0
  40. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/drf_api_logger.egg-info/dependency_links.txt +0 -0
  41. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/pyproject.toml +0 -0
  42. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/setup.cfg +0 -0
  43. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_integration.py +0 -0
  44. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_media_url_issue.py +0 -0
  45. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_middleware.py +0 -0
  46. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_profiling.py +0 -0
  47. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_settings.py +0 -0
  48. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_signals.py +0 -0
  49. {drf_api_logger-1.2.2 → drf_api_logger-1.2.3}/tests/test_utils.py +0 -0
@@ -1,26 +1,34 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: drf-api-logger
3
- Version: 1.2.2
4
- Summary: An API Logger for your Django Rest Framework project.
3
+ Version: 1.2.3
4
+ Summary: Production-ready API logging and profiling for Django REST Framework.
5
5
  Home-page: https://github.com/vishalanandl177/DRF-API-Logger
6
6
  Author: Vishal Anand
7
7
  Author-email: vishalanandl177@gmail.com
8
- License: Apache 2.0
8
+ License: Apache-2.0
9
+ Project-URL: Documentation, https://github.com/vishalanandl177/DRF-API-Logger#readme
10
+ Project-URL: Source, https://github.com/vishalanandl177/DRF-API-Logger
11
+ Project-URL: Issue Tracker, https://github.com/vishalanandl177/DRF-API-Logger/issues
9
12
  Classifier: Programming Language :: Python :: 3
10
- Classifier: Programming Language :: Python :: 3.6
11
- Classifier: Programming Language :: Python :: 3.7
12
- Classifier: Programming Language :: Python :: 3.8
13
- Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
14
  Classifier: Programming Language :: Python :: 3.10
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
- Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Framework :: Django
19
+ Classifier: Framework :: Django :: 4.2
20
+ Classifier: Framework :: Django :: 5.0
21
+ Classifier: Framework :: Django :: 5.1
22
+ Classifier: Framework :: Django :: 5.2
23
+ Classifier: Framework :: Django :: 6.0
19
24
  Classifier: Operating System :: OS Independent
20
- Requires-Python: >=3.6
25
+ Classifier: Topic :: Internet :: WWW/HTTP
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Requires-Python: >=3.10
21
28
  Description-Content-Type: text/markdown
22
29
  License-File: LICENSE
23
- Requires-Dist: djangorestframework>=3.7.4
30
+ Requires-Dist: Django>=4.2
31
+ Requires-Dist: djangorestframework>=3.16
24
32
  Requires-Dist: bleach>=3.1.5
25
33
  Dynamic: author
26
34
  Dynamic: author-email
@@ -30,21 +38,31 @@ Dynamic: description-content-type
30
38
  Dynamic: home-page
31
39
  Dynamic: license
32
40
  Dynamic: license-file
41
+ Dynamic: project-url
33
42
  Dynamic: requires-dist
34
43
  Dynamic: requires-python
35
44
  Dynamic: summary
36
45
 
37
46
  # DRF API Logger
38
47
 
39
- [![Version](https://img.shields.io/badge/version-1.2.2-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
40
- [![Python](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org)
41
- [![Django](https://img.shields.io/badge/django-3.2+-green.svg)](https://djangoproject.com)
42
- [![DRF](https://img.shields.io/badge/djangorestframework-3.12+-orange.svg)](https://www.django-rest-framework.org)
48
+ [![Version](https://img.shields.io/badge/version-1.2.3-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
49
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
50
+ [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
51
+ [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
43
52
  [![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)
44
53
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
45
54
 
46
55
  **The production standard for DRF API observability.** Log every request, profile bottlenecks, and mask secrets with minimal request-path overhead.
47
56
 
57
+ ## Supported Versions
58
+
59
+ - Python 3.10+
60
+ - Django 4.2+
61
+ - Django REST Framework 3.16+
62
+
63
+ The GitHub Actions workflow tests representative Django versions from this
64
+ support range before publishing a package release.
65
+
48
66
  ## 🚀 Key Features
49
67
 
50
68
  DRF API Logger automatically captures and stores comprehensive API information:
@@ -468,16 +486,19 @@ The package includes comprehensive test coverage:
468
486
 
469
487
  ```bash
470
488
  # Install test dependencies
471
- pip install -e .
489
+ pip install -r requirements-dev.txt
472
490
 
473
491
  # Run core tests
474
492
  python test_runner_simple.py
475
493
 
476
- # Run full test suite
477
- python run_tests.py
494
+ # Run full test suite
495
+ python -m django test tests --settings=tests.test_settings --verbosity=1
496
+
497
+ # Run supported Python/Django/DRF combinations
498
+ tox
478
499
 
479
500
  # With coverage
480
- coverage run --source drf_api_logger run_tests.py
501
+ coverage run --source drf_api_logger -m django test tests --settings=tests.test_settings --verbosity=1
481
502
  coverage report
482
503
  ```
483
504
 
@@ -506,13 +527,20 @@ For high-traffic applications:
506
527
  CREATE INDEX idx_api_logs_api_method ON drf_api_logs(api, method);
507
528
  ```
508
529
 
509
- 4. **Archive old data** periodically:
510
- ```python
511
- # Delete logs older than 30 days
512
- old_logs = APILogsModel.objects.filter(
513
- added_on__lt=timezone.now() - timedelta(days=30)
514
- )
515
- old_logs.delete()
530
+ 4. **Prune old data** periodically:
531
+ ```bash
532
+ # Preview rows older than 30 days
533
+ python manage.py prune_api_logs --days 30 --dry-run
534
+
535
+ # Delete rows older than 30 days in batches
536
+ python manage.py prune_api_logs --days 30 --batch-size 1000
537
+ ```
538
+
539
+ You can also prune before a fixed date:
540
+
541
+ ```bash
542
+ python manage.py prune_api_logs --before 2026-06-01 --dry-run
543
+ python manage.py prune_api_logs --before 2026-06-01
516
544
  ```
517
545
 
518
546
  ### Performance Impact
@@ -521,6 +549,17 @@ For high-traffic applications:
521
549
  - **Observable queue backlog** via `LOGGER_THREAD.get_status()` for health checks
522
550
  - **Efficient storage** (bulk database operations)
523
551
 
552
+ Example health check:
553
+
554
+ ```python
555
+ from drf_api_logger.apps import LOGGER_THREAD
556
+
557
+ def drf_logger_status():
558
+ if LOGGER_THREAD is None:
559
+ return {"enabled": False}
560
+ return {"enabled": True, **LOGGER_THREAD.get_status()}
561
+ ```
562
+
524
563
  ### Compliance Readiness
525
564
 
526
565
  For regulated or privacy-sensitive deployments, set conservative payload limits,
@@ -533,15 +572,15 @@ deployment checklist.
533
572
 
534
573
  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:
535
574
 
536
- | Problem | Custom Logging | drf-api-logger |
537
- |---|---|---|
538
- | **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 |
539
- | **Performance overhead** | Synchronous logging in the request/response cycle adds latency to every API call | Request threads enqueue records; the background worker performs bulk database writes |
540
- | **Sensitive data exposure** | Passwords, tokens, headers, and secrets end up in logs unless you remember to filter every field | Automatic recursive masking of credential keys and headers with `***FILTERED***`, extensible via settings |
541
- | **No analytics** | Raw log files or DB rows with no way to visualize trends, filter by status code, or spot slow endpoints | Built-in Django admin dashboard with charts, date hierarchy, status code distribution, CSV export, and slow API detection |
575
+ | Problem | Custom Logging | drf-api-logger |
576
+ |---|---|---------------------------------------------------------------------------------------------------------------------------------|
577
+ | **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 |
578
+ | **Performance overhead** | Synchronous logging in the request/response cycle adds latency to every API call | Request threads enqueue records; the background worker performs bulk database writes |
579
+ | **Sensitive data exposure** | Passwords, tokens, headers, and secrets end up in logs unless you remember to filter every field | Automatic recursive masking of credential keys and headers with `***FILTERED***`, extensible via settings |
580
+ | **No analytics** | Raw log files or DB rows with no way to visualize trends, filter by status code, or spot slow endpoints | Built-in Django admin dashboard with charts, date hierarchy, status code distribution, CSV export, and slow API detection |
542
581
  | **No profiling** | No idea if slowness is from SQL, business logic, or middleware — you attach `django-debug-toolbar` and hope | Per-request latency breakdown with auto-diagnosis: N+1 queries, slow queries, middleware overhead — in production, not just dev |
543
- | **Missing request context** | Client IP behind proxies, request tracing across services, timezone-aware timestamps — all manual work | `X-Forwarded-For` handling, configurable tracing IDs (UUID, header, custom function), timezone-aware logging |
544
- | **Maintenance burden** | Every Django/DRF upgrade risks breaking your custom middleware | Battle-tested across Django 3.2+ and DRF 3.12+, with CI and 100+ tests |
582
+ | **Missing request context** | Client IP behind proxies, request tracing across services, timezone-aware timestamps — all manual work | `X-Forwarded-For` handling, configurable tracing IDs (UUID, header, custom function), timezone-aware logging |
583
+ | **Maintenance burden** | Every Django/DRF upgrade risks breaking your custom middleware | Supports Django 4.2+ and DRF 3.16+, with representative CI coverage and 100+ tests |
545
584
 
546
585
  **Bottom line:** `pip install drf-api-logger` replaces hundreds of lines of fragile custom code with a production-tested, zero-config solution.
547
586
 
@@ -607,7 +646,7 @@ We welcome contributions! Please read our [Contributing Guide](CONTRIBUTING.md)
607
646
  ```bash
608
647
  git clone https://github.com/vishalanandl177/DRF-API-Logger.git
609
648
  cd DRF-API-Logger
610
- pip install -e .
649
+ python -m pip install -r requirements-dev.txt
611
650
  make test-core # Run tests
612
651
  ```
613
652
 
@@ -1,50 +1,23 @@
1
- Metadata-Version: 2.4
2
- Name: drf-api-logger
3
- Version: 1.2.2
4
- Summary: An API Logger for your Django Rest Framework project.
5
- Home-page: https://github.com/vishalanandl177/DRF-API-Logger
6
- Author: Vishal Anand
7
- Author-email: vishalanandl177@gmail.com
8
- License: Apache 2.0
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Programming Language :: Python :: 3.6
11
- Classifier: Programming Language :: Python :: 3.7
12
- Classifier: Programming Language :: Python :: 3.8
13
- Classifier: Programming Language :: Python :: 3.9
14
- Classifier: Programming Language :: Python :: 3.10
15
- Classifier: Programming Language :: Python :: 3.11
16
- Classifier: Programming Language :: Python :: 3.12
17
- Classifier: Programming Language :: Python :: 3.13
18
- Classifier: License :: OSI Approved :: Apache Software License
19
- Classifier: Operating System :: OS Independent
20
- Requires-Python: >=3.6
21
- Description-Content-Type: text/markdown
22
- License-File: LICENSE
23
- Requires-Dist: djangorestframework>=3.7.4
24
- Requires-Dist: bleach>=3.1.5
25
- Dynamic: author
26
- Dynamic: author-email
27
- Dynamic: classifier
28
- Dynamic: description
29
- Dynamic: description-content-type
30
- Dynamic: home-page
31
- Dynamic: license
32
- Dynamic: license-file
33
- Dynamic: requires-dist
34
- Dynamic: requires-python
35
- Dynamic: summary
36
-
37
1
  # DRF API Logger
38
2
 
39
- [![Version](https://img.shields.io/badge/version-1.2.2-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
40
- [![Python](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org)
41
- [![Django](https://img.shields.io/badge/django-3.2+-green.svg)](https://djangoproject.com)
42
- [![DRF](https://img.shields.io/badge/djangorestframework-3.12+-orange.svg)](https://www.django-rest-framework.org)
3
+ [![Version](https://img.shields.io/badge/version-1.2.3-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
4
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
5
+ [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
6
+ [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
43
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)
44
8
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
45
9
 
46
10
  **The production standard for DRF API observability.** Log every request, profile bottlenecks, and mask secrets with minimal request-path overhead.
47
11
 
12
+ ## Supported Versions
13
+
14
+ - Python 3.10+
15
+ - Django 4.2+
16
+ - Django REST Framework 3.16+
17
+
18
+ The GitHub Actions workflow tests representative Django versions from this
19
+ support range before publishing a package release.
20
+
48
21
  ## 🚀 Key Features
49
22
 
50
23
  DRF API Logger automatically captures and stores comprehensive API information:
@@ -468,16 +441,19 @@ The package includes comprehensive test coverage:
468
441
 
469
442
  ```bash
470
443
  # Install test dependencies
471
- pip install -e .
444
+ pip install -r requirements-dev.txt
472
445
 
473
446
  # Run core tests
474
447
  python test_runner_simple.py
475
448
 
476
- # Run full test suite
477
- python run_tests.py
449
+ # Run full test suite
450
+ python -m django test tests --settings=tests.test_settings --verbosity=1
451
+
452
+ # Run supported Python/Django/DRF combinations
453
+ tox
478
454
 
479
455
  # With coverage
480
- coverage run --source drf_api_logger run_tests.py
456
+ coverage run --source drf_api_logger -m django test tests --settings=tests.test_settings --verbosity=1
481
457
  coverage report
482
458
  ```
483
459
 
@@ -506,13 +482,20 @@ For high-traffic applications:
506
482
  CREATE INDEX idx_api_logs_api_method ON drf_api_logs(api, method);
507
483
  ```
508
484
 
509
- 4. **Archive old data** periodically:
510
- ```python
511
- # Delete logs older than 30 days
512
- old_logs = APILogsModel.objects.filter(
513
- added_on__lt=timezone.now() - timedelta(days=30)
514
- )
515
- old_logs.delete()
485
+ 4. **Prune old data** periodically:
486
+ ```bash
487
+ # Preview rows older than 30 days
488
+ python manage.py prune_api_logs --days 30 --dry-run
489
+
490
+ # Delete rows older than 30 days in batches
491
+ python manage.py prune_api_logs --days 30 --batch-size 1000
492
+ ```
493
+
494
+ You can also prune before a fixed date:
495
+
496
+ ```bash
497
+ python manage.py prune_api_logs --before 2026-06-01 --dry-run
498
+ python manage.py prune_api_logs --before 2026-06-01
516
499
  ```
517
500
 
518
501
  ### Performance Impact
@@ -521,6 +504,17 @@ For high-traffic applications:
521
504
  - **Observable queue backlog** via `LOGGER_THREAD.get_status()` for health checks
522
505
  - **Efficient storage** (bulk database operations)
523
506
 
507
+ Example health check:
508
+
509
+ ```python
510
+ from drf_api_logger.apps import LOGGER_THREAD
511
+
512
+ def drf_logger_status():
513
+ if LOGGER_THREAD is None:
514
+ return {"enabled": False}
515
+ return {"enabled": True, **LOGGER_THREAD.get_status()}
516
+ ```
517
+
524
518
  ### Compliance Readiness
525
519
 
526
520
  For regulated or privacy-sensitive deployments, set conservative payload limits,
@@ -533,15 +527,15 @@ deployment checklist.
533
527
 
534
528
  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:
535
529
 
536
- | Problem | Custom Logging | drf-api-logger |
537
- |---|---|---|
538
- | **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 |
539
- | **Performance overhead** | Synchronous logging in the request/response cycle adds latency to every API call | Request threads enqueue records; the background worker performs bulk database writes |
540
- | **Sensitive data exposure** | Passwords, tokens, headers, and secrets end up in logs unless you remember to filter every field | Automatic recursive masking of credential keys and headers with `***FILTERED***`, extensible via settings |
541
- | **No analytics** | Raw log files or DB rows with no way to visualize trends, filter by status code, or spot slow endpoints | Built-in Django admin dashboard with charts, date hierarchy, status code distribution, CSV export, and slow API detection |
530
+ | Problem | Custom Logging | drf-api-logger |
531
+ |---|---|---------------------------------------------------------------------------------------------------------------------------------|
532
+ | **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 |
533
+ | **Performance overhead** | Synchronous logging in the request/response cycle adds latency to every API call | Request threads enqueue records; the background worker performs bulk database writes |
534
+ | **Sensitive data exposure** | Passwords, tokens, headers, and secrets end up in logs unless you remember to filter every field | Automatic recursive masking of credential keys and headers with `***FILTERED***`, extensible via settings |
535
+ | **No analytics** | Raw log files or DB rows with no way to visualize trends, filter by status code, or spot slow endpoints | Built-in Django admin dashboard with charts, date hierarchy, status code distribution, CSV export, and slow API detection |
542
536
  | **No profiling** | No idea if slowness is from SQL, business logic, or middleware — you attach `django-debug-toolbar` and hope | Per-request latency breakdown with auto-diagnosis: N+1 queries, slow queries, middleware overhead — in production, not just dev |
543
- | **Missing request context** | Client IP behind proxies, request tracing across services, timezone-aware timestamps — all manual work | `X-Forwarded-For` handling, configurable tracing IDs (UUID, header, custom function), timezone-aware logging |
544
- | **Maintenance burden** | Every Django/DRF upgrade risks breaking your custom middleware | Battle-tested across Django 3.2+ and DRF 3.12+, with CI and 100+ tests |
537
+ | **Missing request context** | Client IP behind proxies, request tracing across services, timezone-aware timestamps — all manual work | `X-Forwarded-For` handling, configurable tracing IDs (UUID, header, custom function), timezone-aware logging |
538
+ | **Maintenance burden** | Every Django/DRF upgrade risks breaking your custom middleware | Supports Django 4.2+ and DRF 3.16+, with representative CI coverage and 100+ tests |
545
539
 
546
540
  **Bottom line:** `pip install drf-api-logger` replaces hundreds of lines of fragile custom code with a production-tested, zero-config solution.
547
541
 
@@ -607,7 +601,7 @@ We welcome contributions! Please read our [Contributing Guide](CONTRIBUTING.md)
607
601
  ```bash
608
602
  git clone https://github.com/vishalanandl177/DRF-API-Logger.git
609
603
  cd DRF-API-Logger
610
- pip install -e .
604
+ python -m pip install -r requirements-dev.txt
611
605
  make test-core # Run tests
612
606
  ```
613
607
 
@@ -4,10 +4,46 @@ from django.conf import settings
4
4
  from django.contrib import admin
5
5
  from django.db.models import Count, Avg
6
6
  from django.http import HttpResponse
7
+ from django.utils.html import escape
7
8
  from django.utils.safestring import mark_safe
8
9
  from drf_api_logger.utils import database_log_enabled
9
10
 
10
11
 
12
+ def _prettify_json_field(value):
13
+ """
14
+ Render a stored log field (headers / body / response) as a pretty-printed,
15
+ HTML-escaped JSON block for the admin change form.
16
+
17
+ The middleware already stores these as indented JSON, but plain/large or
18
+ non-JSON payloads (truncation markers, XML, streaming placeholders, ...) are
19
+ handled gracefully. The returned markup is wrapped in ``<pre class="apilogs-json">``
20
+ which the change-form template syntax-highlights on the client side. No size
21
+ limit is applied here so even large bodies are prettified in full.
22
+ """
23
+ if value is None or value == '':
24
+ return mark_safe('<div class="apilogs-empty">— empty —</div>')
25
+
26
+ text = value if isinstance(value, str) else str(value)
27
+ stripped = text.strip()
28
+
29
+ # Special placeholders emitted by the middleware, e.g.
30
+ # "** Response body truncated: 70000 bytes exceeds 65536 byte limit **".
31
+ is_marker = stripped.startswith('**') and stripped.endswith('**')
32
+
33
+ badge = ''
34
+ if is_marker and 'truncated' in stripped.lower():
35
+ badge = '<div class="apilogs-truncated">TRUNCATED</div>'
36
+
37
+ pretty = text
38
+ if not is_marker:
39
+ try:
40
+ pretty = json.dumps(json.loads(text), indent=2, ensure_ascii=False)
41
+ except (ValueError, TypeError):
42
+ pretty = text # leave non-JSON payloads (XML, plain text, ...) as-is
43
+
44
+ return mark_safe('{}<pre class="apilogs-json">{}</pre>'.format(badge, escape(pretty)))
45
+
46
+
11
47
  def _get_profiling_diagnosis(profiling):
12
48
  """Generate a diagnosis hint based on profiling data patterns."""
13
49
  total = profiling.get('view_and_serialization', 0)
@@ -40,6 +76,12 @@ def _get_profiling_diagnosis(profiling):
40
76
  return None
41
77
 
42
78
 
79
+ def _normalized_filter_value(value):
80
+ if isinstance(value, (list, tuple)):
81
+ return value[-1] if value else None
82
+ return value
83
+
84
+
43
85
  # Ensure the API log model and related features are only used if enabled in settings
44
86
  if database_log_enabled():
45
87
  from drf_api_logger.models import APILogsModel
@@ -108,9 +150,10 @@ if database_log_enabled():
108
150
  Returns filtered queryset depending on whether 'slow' or 'fast'
109
151
  option is selected in the filter.
110
152
  """
111
- if self.value() == 'slow':
153
+ value = _normalized_filter_value(self.value())
154
+ if value == 'slow':
112
155
  return queryset.filter(execution_time__gte=self._DRF_API_LOGGER_SLOW_API_ABOVE)
113
- if self.value() == 'fast':
156
+ if value == 'fast':
114
157
  return queryset.filter(execution_time__lt=self._DRF_API_LOGGER_SLOW_API_ABOVE)
115
158
  return queryset
116
159
 
@@ -128,13 +171,14 @@ if database_log_enabled():
128
171
  )
129
172
 
130
173
  def queryset(self, request, queryset):
131
- if self.value() == 'high':
174
+ value = _normalized_filter_value(self.value())
175
+ if value == 'high':
132
176
  return queryset.filter(sql_query_count__gte=10)
133
- if self.value() == 'moderate':
177
+ if value == 'moderate':
134
178
  return queryset.filter(sql_query_count__gte=5, sql_query_count__lt=10)
135
- if self.value() == 'low':
179
+ if value == 'low':
136
180
  return queryset.filter(sql_query_count__lt=5, sql_query_count__isnull=False)
137
- if self.value() == 'none':
181
+ if value == 'none':
138
182
  return queryset.filter(sql_query_count__isnull=True)
139
183
  return queryset
140
184
 
@@ -174,10 +218,13 @@ if database_log_enabled():
174
218
  self.list_filter += (HighQueryCountFilter,)
175
219
  self.readonly_fields = (
176
220
  'execution_time', 'client_ip_address', 'api',
177
- 'headers', 'body', 'method', 'response', 'status_code',
178
- 'added_on_time', 'profiling_breakdown',
221
+ 'headers_prettified', 'body_prettified', 'method', 'response_prettified',
222
+ 'status_code', 'added_on_time', 'profiling_breakdown',
223
+ )
224
+ self.exclude = (
225
+ 'added_on', 'profiling_data', 'sql_query_count',
226
+ 'headers', 'body', 'response',
179
227
  )
180
- self.exclude = ('added_on', 'profiling_data', 'sql_query_count')
181
228
 
182
229
  def added_on_time(self, obj):
183
230
  """
@@ -311,6 +358,21 @@ if database_log_enabled():
311
358
 
312
359
  profiling_breakdown.short_description = 'Profiling Breakdown'
313
360
 
361
+ def headers_prettified(self, obj):
362
+ return _prettify_json_field(obj.headers)
363
+
364
+ headers_prettified.short_description = 'Headers'
365
+
366
+ def body_prettified(self, obj):
367
+ return _prettify_json_field(obj.body)
368
+
369
+ body_prettified.short_description = 'Body'
370
+
371
+ def response_prettified(self, obj):
372
+ return _prettify_json_field(obj.response)
373
+
374
+ response_prettified.short_description = 'Response'
375
+
314
376
  # Admin UI settings
315
377
  list_per_page = 20
316
378
  list_display = ('id', 'api', 'method', 'status_code', 'execution_time', 'added_on_time',)
@@ -318,9 +380,10 @@ if database_log_enabled():
318
380
  search_fields = ('body', 'response', 'headers', 'api',)
319
381
  readonly_fields = (
320
382
  'execution_time', 'client_ip_address', 'api',
321
- 'headers', 'body', 'method', 'response', 'status_code', 'added_on_time',
383
+ 'headers_prettified', 'body_prettified', 'method', 'response_prettified',
384
+ 'status_code', 'added_on_time',
322
385
  )
323
- exclude = ('added_on',)
386
+ exclude = ('added_on', 'headers', 'body', 'response')
324
387
 
325
388
  # Custom admin templates
326
389
  change_list_template = 'charts_change_list.html'
@@ -0,0 +1,122 @@
1
+ from datetime import datetime, time, timedelta
2
+
3
+ from django.conf import settings
4
+ from django.core.management.base import BaseCommand, CommandError
5
+ from django.utils import timezone
6
+
7
+ from drf_api_logger.utils import database_log_enabled
8
+
9
+
10
+ class Command(BaseCommand):
11
+ help = 'Delete old DRF API Logger database rows in safe batches.'
12
+
13
+ def add_arguments(self, parser):
14
+ parser.add_argument(
15
+ '--days',
16
+ type=int,
17
+ help='Delete logs older than this many days.',
18
+ )
19
+ parser.add_argument(
20
+ '--before',
21
+ help='Delete logs added before this date in YYYY-MM-DD format.',
22
+ )
23
+ parser.add_argument(
24
+ '--database',
25
+ help='Database alias to prune. Defaults to DRF_API_LOGGER_DEFAULT_DATABASE or default.',
26
+ )
27
+ parser.add_argument(
28
+ '--batch-size',
29
+ type=int,
30
+ default=1000,
31
+ help='Number of rows to delete per batch. Default: 1000.',
32
+ )
33
+ parser.add_argument(
34
+ '--dry-run',
35
+ action='store_true',
36
+ help='Report how many rows would be deleted without deleting them.',
37
+ )
38
+
39
+ def handle(self, *args, **options):
40
+ if not database_log_enabled():
41
+ raise CommandError('DRF_API_LOGGER_DATABASE must be True to prune database logs.')
42
+
43
+ batch_size = options['batch_size']
44
+ if batch_size < 1:
45
+ raise CommandError('--batch-size must be greater than 0.')
46
+
47
+ cutoff = self._get_cutoff(options.get('days'), options.get('before'))
48
+ database = options.get('database') or getattr(
49
+ settings,
50
+ 'DRF_API_LOGGER_DEFAULT_DATABASE',
51
+ 'default',
52
+ )
53
+
54
+ from drf_api_logger.models import APILogsModel
55
+
56
+ queryset = APILogsModel.objects.using(database).filter(added_on__lt=cutoff)
57
+ matching_count = queryset.count()
58
+
59
+ if options['dry_run']:
60
+ self.stdout.write(
61
+ 'Would delete {} API log row(s) older than {} from database "{}".'.format(
62
+ matching_count,
63
+ self._format_cutoff(cutoff),
64
+ database,
65
+ )
66
+ )
67
+ return
68
+
69
+ deleted_count = self._delete_in_batches(APILogsModel, database, cutoff, batch_size)
70
+ self.stdout.write(
71
+ self.style.SUCCESS(
72
+ 'Deleted {} API log row(s) older than {} from database "{}".'.format(
73
+ deleted_count,
74
+ self._format_cutoff(cutoff),
75
+ database,
76
+ )
77
+ )
78
+ )
79
+
80
+ def _get_cutoff(self, days, before):
81
+ if (days is None and before is None) or (days is not None and before is not None):
82
+ raise CommandError('Provide exactly one of --days or --before.')
83
+
84
+ if days is not None:
85
+ if days < 1:
86
+ raise CommandError('--days must be greater than 0.')
87
+ return self._now() - timedelta(days=days)
88
+
89
+ try:
90
+ parsed_date = datetime.strptime(before, '%Y-%m-%d').date()
91
+ except ValueError:
92
+ raise CommandError('--before must use YYYY-MM-DD format.')
93
+
94
+ cutoff = datetime.combine(parsed_date, time.min)
95
+ if settings.USE_TZ:
96
+ return timezone.make_aware(cutoff, timezone.get_current_timezone())
97
+ return cutoff
98
+
99
+ def _now(self):
100
+ if settings.USE_TZ:
101
+ return timezone.now()
102
+ return datetime.now()
103
+
104
+ def _delete_in_batches(self, model, database, cutoff, batch_size):
105
+ deleted_count = 0
106
+ while True:
107
+ ids = list(
108
+ model.objects.using(database)
109
+ .filter(added_on__lt=cutoff)
110
+ .order_by('added_on', 'pk')
111
+ .values_list('pk', flat=True)[:batch_size]
112
+ )
113
+ if not ids:
114
+ break
115
+
116
+ batch_deleted, _ = model.objects.using(database).filter(pk__in=ids).delete()
117
+ deleted_count += batch_deleted
118
+
119
+ return deleted_count
120
+
121
+ def _format_cutoff(self, cutoff):
122
+ return cutoff.isoformat()