drf-api-logger 1.3.0__tar.gz → 1.4.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.
- {drf_api_logger-1.3.0/drf_api_logger.egg-info → drf_api_logger-1.4.0}/PKG-INFO +116 -2
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/README.md +112 -1
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/apps.py +1 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/insert_log_into_database.py +64 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/__init__.py +3 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/labels.py +157 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/noop.py +86 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/prometheus.py +648 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/recorder.py +37 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/rules.py +374 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/security.py +75 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/settings.py +298 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/state.py +42 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/system_checks.py +75 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/urls.py +13 -0
- drf_api_logger-1.4.0/drf_api_logger/metrics/views.py +20 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/middleware/api_logger_middleware.py +433 -87
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0/drf_api_logger.egg-info}/PKG-INFO +116 -2
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger.egg-info/SOURCES.txt +14 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger.egg-info/requires.txt +3 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/llms.txt +35 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/setup.py +4 -1
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_backward_compat.py +11 -9
- drf_api_logger-1.4.0/tests/test_metrics.py +898 -0
- drf_api_logger-1.4.0/tests/test_publish_workflow.py +49 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/LICENSE +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/MANIFEST.in +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/admin.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/collectstatic.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/correlation.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/diagnostics.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/events.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/logging_context.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/management/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/management/commands/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/management/commands/drf_api_logger_doctor.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/management/commands/prune_api_logs.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/middleware/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/migrations/0001_initial.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/migrations/0002_auto_20211221_2155.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/migrations/0003_apilogsmodel_profiling.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/migrations/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/models.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/observability.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/policy.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/static/drf_api_logger/css/Chart.min.css +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/static/drf_api_logger/js/Chart.bundle.min.js +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/templates/change_form.html +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/templates/charts_change_list.html +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/tests.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger/utils.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger.egg-info/dependency_links.txt +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/drf_api_logger.egg-info/top_level.txt +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/pyproject.toml +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/setup.cfg +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_admin_charts.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_admin_templates.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_asgi_middleware.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_correlation.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_diagnostics.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_docs_content.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_integration.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_management_commands.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_media_url_issue.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_middleware.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_models.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_observability.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_policy.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_profiling.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_settings.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_signals.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.0}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: drf-api-logger
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
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
|
|
@@ -32,6 +32,8 @@ License-File: LICENSE
|
|
|
32
32
|
Requires-Dist: Django>=4.2
|
|
33
33
|
Requires-Dist: djangorestframework>=3.16
|
|
34
34
|
Requires-Dist: bleach>=3.1.5
|
|
35
|
+
Provides-Extra: prometheus
|
|
36
|
+
Requires-Dist: prometheus-client>=0.20; extra == "prometheus"
|
|
35
37
|
Dynamic: author
|
|
36
38
|
Dynamic: author-email
|
|
37
39
|
Dynamic: classifier
|
|
@@ -41,13 +43,14 @@ Dynamic: home-page
|
|
|
41
43
|
Dynamic: license
|
|
42
44
|
Dynamic: license-file
|
|
43
45
|
Dynamic: project-url
|
|
46
|
+
Dynamic: provides-extra
|
|
44
47
|
Dynamic: requires-dist
|
|
45
48
|
Dynamic: requires-python
|
|
46
49
|
Dynamic: summary
|
|
47
50
|
|
|
48
51
|
# DRF API Logger
|
|
49
52
|
|
|
50
|
-
[](https://github.com/vishalanandl177/DRF-API-Logger)
|
|
51
54
|
[](https://www.python.org)
|
|
52
55
|
[](https://djangoproject.com)
|
|
53
56
|
[](https://www.django-rest-framework.org)
|
|
@@ -116,6 +119,7 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
116
119
|
- **Request Correlation**: Opt-in request IDs, traceparent parsing, route metadata, logging context, and signal metadata without new database columns
|
|
117
120
|
- **ASGI-Native Logging**: Supports Django's async middleware chain with concurrent request context isolation
|
|
118
121
|
- **Safe Observability Integrations**: Optional helpers for Prometheus labels, OpenTelemetry span attributes, and Sentry context without hard dependencies
|
|
122
|
+
- **First-Party Metrics & Security Signals**: Optional logger health, pipeline, API timing, and detect-only security metrics with safe labels
|
|
119
123
|
- **Policy Controls**: Optional endpoint-specific rules for logging, masking, payload stripping, and signal/export gating
|
|
120
124
|
|
|
121
125
|
### 🌐 Community & Support
|
|
@@ -127,6 +131,20 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
127
131
|
<a href="https://buymeacoffee.com/riptechlead"><img src="https://img.shields.io/badge/Buy%20Me%20A%20Coffee-FFDD00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black" alt="Support"/></a>
|
|
128
132
|
</p>
|
|
129
133
|
|
|
134
|
+
#### Support maintenance
|
|
135
|
+
|
|
136
|
+
DRF API Logger is free and open source. If your team uses it in production,
|
|
137
|
+
consider supporting ongoing maintenance.
|
|
138
|
+
|
|
139
|
+
Support helps with:
|
|
140
|
+
|
|
141
|
+
- Django, DRF, and Python compatibility updates
|
|
142
|
+
- Security, masking, and privacy improvements
|
|
143
|
+
- Bug fixes, issue triage, and release validation
|
|
144
|
+
- Documentation, examples, and production guidance
|
|
145
|
+
|
|
146
|
+
Support maintenance: [Buy Me a Coffee](https://buymeacoffee.com/riptechlead)
|
|
147
|
+
|
|
130
148
|
## 📦 Installation
|
|
131
149
|
|
|
132
150
|
### 1. Install Package
|
|
@@ -285,6 +303,8 @@ API_LOGGER_SIGNAL.listen -= log_to_file
|
|
|
285
303
|
- [Copy-paste setup recipes](docs/quickstart.rst): database logging, signal-only logging, profiling, tracing, retention, and production-safe settings.
|
|
286
304
|
- [ASGI-native logging](docs/asgi.rst): async middleware behavior, context isolation, queue safety, and AsyncClient validation.
|
|
287
305
|
- [Safe observability integrations](docs/observability_integrations.rst): Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
|
|
306
|
+
- [First-party metrics](docs/metrics.rst): optional Prometheus recorder, logger overhead, queue health, API metrics, safe labels, and endpoint guidance.
|
|
307
|
+
- [Security signals](docs/security_signals.rst): detect-only suspicious activity metrics, bounded body inspection, rule IDs, and false-positive guidance.
|
|
288
308
|
- [Policy controls](docs/policy_controls.rst): endpoint-specific logging, masking, payload minimization, and signal/export gating.
|
|
289
309
|
- [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
|
|
290
310
|
- [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
|
|
@@ -609,6 +629,100 @@ traces, and Sentry context, not metrics labels. The helpers do not import
|
|
|
609
629
|
Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
|
|
610
630
|
exporter configuration.
|
|
611
631
|
|
|
632
|
+
### First-Party Metrics & Security Signals
|
|
633
|
+
|
|
634
|
+
Enable optional package-owned metrics when you want DRF API Logger to report its
|
|
635
|
+
own overhead and background pipeline health:
|
|
636
|
+
|
|
637
|
+
```bash
|
|
638
|
+
pip install "drf-api-logger[prometheus]"
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
```python
|
|
642
|
+
DRF_API_LOGGER_METRICS_ENABLED = True
|
|
643
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline"]
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
Logger and pipeline metrics include request-path overhead, payload capture,
|
|
647
|
+
masking, serialization, enqueue duration, queue depth, queue utilization,
|
|
648
|
+
worker up/down state, worker starts, flush duration, batch size, storage write
|
|
649
|
+
duration, dropped/skipped logs, and storage write failures.
|
|
650
|
+
|
|
651
|
+
API request metrics are disabled separately to avoid duplicate instrumentation:
|
|
652
|
+
|
|
653
|
+
```python
|
|
654
|
+
DRF_API_LOGGER_API_METRICS_ENABLED = True
|
|
655
|
+
```
|
|
656
|
+
|
|
657
|
+
API metrics include request count, duration, active requests, request and
|
|
658
|
+
non-streaming response body sizes, slow-request counts, exception counts, and
|
|
659
|
+
HTTP 429 throttle counts using normalized route labels.
|
|
660
|
+
|
|
661
|
+
Profiling metrics are available when profiling data exists:
|
|
662
|
+
|
|
663
|
+
```python
|
|
664
|
+
DRF_API_LOGGER_ENABLE_PROFILING = True
|
|
665
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline", "profiling"]
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
They summarize SQL duration, query count, duplicate query count, likely N+1
|
|
669
|
+
signals, view/serialization duration, and middleware duration without exposing
|
|
670
|
+
SQL text as labels.
|
|
671
|
+
|
|
672
|
+
These metrics support practical dashboards and alerts: watch queue depth and
|
|
673
|
+
storage failures to protect log reliability, compare request overhead against
|
|
674
|
+
API latency, find SQL-heavy or likely N+1 endpoints, and alert on suspicious
|
|
675
|
+
security rule matches such as auth failures, route scans, payload attacks, and
|
|
676
|
+
bulk export behavior. See [First-party metrics](docs/metrics.rst) for PromQL
|
|
677
|
+
examples.
|
|
678
|
+
|
|
679
|
+
Security signals are detect-only and disabled by default:
|
|
680
|
+
|
|
681
|
+
```python
|
|
682
|
+
DRF_API_LOGGER_SECURITY_METRICS_ENABLED = True
|
|
683
|
+
DRF_API_LOGGER_SECURITY_MODE = "detect"
|
|
684
|
+
DRF_API_LOGGER_SECURITY_BODY_INSPECTION = {
|
|
685
|
+
"enabled": True,
|
|
686
|
+
"max_body_bytes": 8192,
|
|
687
|
+
"inspect_request_body": True,
|
|
688
|
+
"inspect_response_body": False,
|
|
689
|
+
}
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
Rules `DRFSEC-001` through `DRFSEC-016` cover authentication failures,
|
|
693
|
+
success-after-failure patterns, token failures, authorization failures,
|
|
694
|
+
admin/debug probes, payload attack patterns, rate-limit pressure, route scans,
|
|
695
|
+
object ID enumeration hints, log injection, sensitive response-field hints,
|
|
696
|
+
pagination sweeps, bulk exports, high response volume, sensitive business
|
|
697
|
+
routes, and repeated business-flow actions. Correlation uses bounded
|
|
698
|
+
process-local state and internal HMAC actor fingerprints, never metric labels.
|
|
699
|
+
|
|
700
|
+
Metric labels are allowlisted and low-cardinality. Do not use raw URLs, query
|
|
701
|
+
strings, request IDs, trace IDs, user IDs, IPs, object IDs, tokens, headers,
|
|
702
|
+
request bodies, response bodies, SQL queries, or exception messages as labels.
|
|
703
|
+
Unresolved 404 paths use fixed `route="unresolved"` and
|
|
704
|
+
`view_name="unresolved"` labels instead of raw paths.
|
|
705
|
+
|
|
706
|
+
The optional Prometheus endpoint is off by default:
|
|
707
|
+
|
|
708
|
+
```python
|
|
709
|
+
DRF_API_LOGGER_METRICS_PROMETHEUS_ENDPOINT_ENABLED = True
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
Mount it only under an internal protected path:
|
|
713
|
+
|
|
714
|
+
```python
|
|
715
|
+
from django.urls import include, path
|
|
716
|
+
|
|
717
|
+
urlpatterns = [
|
|
718
|
+
path("internal/drf-api-logger/", include("drf_api_logger.metrics.urls")),
|
|
719
|
+
]
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
Run `python manage.py check` after enabling metrics. The checks report missing
|
|
723
|
+
Prometheus dependencies, unsafe labels, endpoint exposure warnings, and unsafe
|
|
724
|
+
security body-inspection limits.
|
|
725
|
+
|
|
612
726
|
## 📊 Programmatic Access
|
|
613
727
|
|
|
614
728
|
### Querying Log Data
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# DRF API Logger
|
|
2
2
|
|
|
3
|
-
[](https://github.com/vishalanandl177/DRF-API-Logger)
|
|
4
4
|
[](https://www.python.org)
|
|
5
5
|
[](https://djangoproject.com)
|
|
6
6
|
[](https://www.django-rest-framework.org)
|
|
@@ -69,6 +69,7 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
69
69
|
- **Request Correlation**: Opt-in request IDs, traceparent parsing, route metadata, logging context, and signal metadata without new database columns
|
|
70
70
|
- **ASGI-Native Logging**: Supports Django's async middleware chain with concurrent request context isolation
|
|
71
71
|
- **Safe Observability Integrations**: Optional helpers for Prometheus labels, OpenTelemetry span attributes, and Sentry context without hard dependencies
|
|
72
|
+
- **First-Party Metrics & Security Signals**: Optional logger health, pipeline, API timing, and detect-only security metrics with safe labels
|
|
72
73
|
- **Policy Controls**: Optional endpoint-specific rules for logging, masking, payload stripping, and signal/export gating
|
|
73
74
|
|
|
74
75
|
### 🌐 Community & Support
|
|
@@ -80,6 +81,20 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
80
81
|
<a href="https://buymeacoffee.com/riptechlead"><img src="https://img.shields.io/badge/Buy%20Me%20A%20Coffee-FFDD00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black" alt="Support"/></a>
|
|
81
82
|
</p>
|
|
82
83
|
|
|
84
|
+
#### Support maintenance
|
|
85
|
+
|
|
86
|
+
DRF API Logger is free and open source. If your team uses it in production,
|
|
87
|
+
consider supporting ongoing maintenance.
|
|
88
|
+
|
|
89
|
+
Support helps with:
|
|
90
|
+
|
|
91
|
+
- Django, DRF, and Python compatibility updates
|
|
92
|
+
- Security, masking, and privacy improvements
|
|
93
|
+
- Bug fixes, issue triage, and release validation
|
|
94
|
+
- Documentation, examples, and production guidance
|
|
95
|
+
|
|
96
|
+
Support maintenance: [Buy Me a Coffee](https://buymeacoffee.com/riptechlead)
|
|
97
|
+
|
|
83
98
|
## 📦 Installation
|
|
84
99
|
|
|
85
100
|
### 1. Install Package
|
|
@@ -238,6 +253,8 @@ API_LOGGER_SIGNAL.listen -= log_to_file
|
|
|
238
253
|
- [Copy-paste setup recipes](docs/quickstart.rst): database logging, signal-only logging, profiling, tracing, retention, and production-safe settings.
|
|
239
254
|
- [ASGI-native logging](docs/asgi.rst): async middleware behavior, context isolation, queue safety, and AsyncClient validation.
|
|
240
255
|
- [Safe observability integrations](docs/observability_integrations.rst): Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
|
|
256
|
+
- [First-party metrics](docs/metrics.rst): optional Prometheus recorder, logger overhead, queue health, API metrics, safe labels, and endpoint guidance.
|
|
257
|
+
- [Security signals](docs/security_signals.rst): detect-only suspicious activity metrics, bounded body inspection, rule IDs, and false-positive guidance.
|
|
241
258
|
- [Policy controls](docs/policy_controls.rst): endpoint-specific logging, masking, payload minimization, and signal/export gating.
|
|
242
259
|
- [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
|
|
243
260
|
- [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
|
|
@@ -562,6 +579,100 @@ traces, and Sentry context, not metrics labels. The helpers do not import
|
|
|
562
579
|
Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
|
|
563
580
|
exporter configuration.
|
|
564
581
|
|
|
582
|
+
### First-Party Metrics & Security Signals
|
|
583
|
+
|
|
584
|
+
Enable optional package-owned metrics when you want DRF API Logger to report its
|
|
585
|
+
own overhead and background pipeline health:
|
|
586
|
+
|
|
587
|
+
```bash
|
|
588
|
+
pip install "drf-api-logger[prometheus]"
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
```python
|
|
592
|
+
DRF_API_LOGGER_METRICS_ENABLED = True
|
|
593
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline"]
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
Logger and pipeline metrics include request-path overhead, payload capture,
|
|
597
|
+
masking, serialization, enqueue duration, queue depth, queue utilization,
|
|
598
|
+
worker up/down state, worker starts, flush duration, batch size, storage write
|
|
599
|
+
duration, dropped/skipped logs, and storage write failures.
|
|
600
|
+
|
|
601
|
+
API request metrics are disabled separately to avoid duplicate instrumentation:
|
|
602
|
+
|
|
603
|
+
```python
|
|
604
|
+
DRF_API_LOGGER_API_METRICS_ENABLED = True
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
API metrics include request count, duration, active requests, request and
|
|
608
|
+
non-streaming response body sizes, slow-request counts, exception counts, and
|
|
609
|
+
HTTP 429 throttle counts using normalized route labels.
|
|
610
|
+
|
|
611
|
+
Profiling metrics are available when profiling data exists:
|
|
612
|
+
|
|
613
|
+
```python
|
|
614
|
+
DRF_API_LOGGER_ENABLE_PROFILING = True
|
|
615
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline", "profiling"]
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
They summarize SQL duration, query count, duplicate query count, likely N+1
|
|
619
|
+
signals, view/serialization duration, and middleware duration without exposing
|
|
620
|
+
SQL text as labels.
|
|
621
|
+
|
|
622
|
+
These metrics support practical dashboards and alerts: watch queue depth and
|
|
623
|
+
storage failures to protect log reliability, compare request overhead against
|
|
624
|
+
API latency, find SQL-heavy or likely N+1 endpoints, and alert on suspicious
|
|
625
|
+
security rule matches such as auth failures, route scans, payload attacks, and
|
|
626
|
+
bulk export behavior. See [First-party metrics](docs/metrics.rst) for PromQL
|
|
627
|
+
examples.
|
|
628
|
+
|
|
629
|
+
Security signals are detect-only and disabled by default:
|
|
630
|
+
|
|
631
|
+
```python
|
|
632
|
+
DRF_API_LOGGER_SECURITY_METRICS_ENABLED = True
|
|
633
|
+
DRF_API_LOGGER_SECURITY_MODE = "detect"
|
|
634
|
+
DRF_API_LOGGER_SECURITY_BODY_INSPECTION = {
|
|
635
|
+
"enabled": True,
|
|
636
|
+
"max_body_bytes": 8192,
|
|
637
|
+
"inspect_request_body": True,
|
|
638
|
+
"inspect_response_body": False,
|
|
639
|
+
}
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
Rules `DRFSEC-001` through `DRFSEC-016` cover authentication failures,
|
|
643
|
+
success-after-failure patterns, token failures, authorization failures,
|
|
644
|
+
admin/debug probes, payload attack patterns, rate-limit pressure, route scans,
|
|
645
|
+
object ID enumeration hints, log injection, sensitive response-field hints,
|
|
646
|
+
pagination sweeps, bulk exports, high response volume, sensitive business
|
|
647
|
+
routes, and repeated business-flow actions. Correlation uses bounded
|
|
648
|
+
process-local state and internal HMAC actor fingerprints, never metric labels.
|
|
649
|
+
|
|
650
|
+
Metric labels are allowlisted and low-cardinality. Do not use raw URLs, query
|
|
651
|
+
strings, request IDs, trace IDs, user IDs, IPs, object IDs, tokens, headers,
|
|
652
|
+
request bodies, response bodies, SQL queries, or exception messages as labels.
|
|
653
|
+
Unresolved 404 paths use fixed `route="unresolved"` and
|
|
654
|
+
`view_name="unresolved"` labels instead of raw paths.
|
|
655
|
+
|
|
656
|
+
The optional Prometheus endpoint is off by default:
|
|
657
|
+
|
|
658
|
+
```python
|
|
659
|
+
DRF_API_LOGGER_METRICS_PROMETHEUS_ENDPOINT_ENABLED = True
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
Mount it only under an internal protected path:
|
|
663
|
+
|
|
664
|
+
```python
|
|
665
|
+
from django.urls import include, path
|
|
666
|
+
|
|
667
|
+
urlpatterns = [
|
|
668
|
+
path("internal/drf-api-logger/", include("drf_api_logger.metrics.urls")),
|
|
669
|
+
]
|
|
670
|
+
```
|
|
671
|
+
|
|
672
|
+
Run `python manage.py check` after enabling metrics. The checks report missing
|
|
673
|
+
Prometheus dependencies, unsafe labels, endpoint exposure warnings, and unsafe
|
|
674
|
+
security body-inspection limits.
|
|
675
|
+
|
|
565
676
|
## 📊 Programmatic Access
|
|
566
677
|
|
|
567
678
|
### Querying Log Data
|
|
@@ -24,6 +24,7 @@ class LoggerConfig(AppConfig):
|
|
|
24
24
|
but only in the main process (to avoid duplication on autoreload).
|
|
25
25
|
"""
|
|
26
26
|
global LOGGER_THREAD
|
|
27
|
+
from drf_api_logger.metrics import system_checks # noqa: F401
|
|
27
28
|
|
|
28
29
|
# Check if we should start the logger thread
|
|
29
30
|
# In development with Django's runserver, RUN_MAIN prevents duplicate threads
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import atexit
|
|
2
2
|
import signal
|
|
3
|
+
import time
|
|
3
4
|
from queue import Empty, Queue
|
|
4
5
|
from importlib import import_module
|
|
5
6
|
from django.conf import settings
|
|
6
7
|
from threading import Thread, Event, Lock
|
|
7
8
|
from django.db.utils import OperationalError
|
|
9
|
+
from drf_api_logger.metrics.recorder import get_recorder
|
|
8
10
|
from drf_api_logger.models import APILogsModel
|
|
9
11
|
|
|
10
12
|
|
|
@@ -76,6 +78,13 @@ class InsertLogIntoDatabase(Thread):
|
|
|
76
78
|
if not self._atexit_registered:
|
|
77
79
|
atexit.register(self.shutdown)
|
|
78
80
|
self._atexit_registered = True
|
|
81
|
+
try:
|
|
82
|
+
recorder = get_recorder()
|
|
83
|
+
recorder.increment_worker_restart(self.name or 'insert_log_into_database')
|
|
84
|
+
recorder.set_worker_up(self.name or 'insert_log_into_database', True)
|
|
85
|
+
self._record_queue_metrics(recorder)
|
|
86
|
+
except Exception:
|
|
87
|
+
pass
|
|
79
88
|
self.start_queue_process()
|
|
80
89
|
|
|
81
90
|
def put_log_data(self, data):
|
|
@@ -90,14 +99,37 @@ class InsertLogIntoDatabase(Thread):
|
|
|
90
99
|
data = self.custom_handler(data)
|
|
91
100
|
if data is None:
|
|
92
101
|
self._increment_stat('_dropped_count')
|
|
102
|
+
try:
|
|
103
|
+
recorder = get_recorder()
|
|
104
|
+
recorder.increment_dropped_logs('custom_handler')
|
|
105
|
+
self._record_queue_metrics(recorder)
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
93
108
|
return
|
|
94
109
|
|
|
110
|
+
enqueue_start = time.perf_counter()
|
|
95
111
|
try:
|
|
96
112
|
self._queue.put_nowait(APILogsModel(**data))
|
|
97
113
|
except Exception as e:
|
|
98
114
|
self._increment_stat('_dropped_count')
|
|
115
|
+
try:
|
|
116
|
+
recorder = get_recorder()
|
|
117
|
+
recorder.increment_dropped_logs('queue_error')
|
|
118
|
+
self._record_queue_metrics(recorder)
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
99
121
|
print('DRF API LOGGER EXCEPTION:', e)
|
|
100
122
|
return
|
|
123
|
+
finally:
|
|
124
|
+
enqueue_duration = time.perf_counter() - enqueue_start
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
recorder = get_recorder()
|
|
128
|
+
recorder.observe_enqueue({'queue_name': 'database'}, enqueue_duration)
|
|
129
|
+
recorder.increment_enqueued_logs('database')
|
|
130
|
+
self._record_queue_metrics(recorder)
|
|
131
|
+
except Exception:
|
|
132
|
+
pass
|
|
101
133
|
|
|
102
134
|
# If queue reaches the batch threshold, wake the worker to flush.
|
|
103
135
|
if self._queue.qsize() >= self.DRF_LOGGER_QUEUE_MAX_SIZE:
|
|
@@ -140,11 +172,26 @@ class InsertLogIntoDatabase(Thread):
|
|
|
140
172
|
Raises:
|
|
141
173
|
Exception: If the model doesn't exist or another database error occurs.
|
|
142
174
|
"""
|
|
175
|
+
flush_start = time.perf_counter()
|
|
143
176
|
try:
|
|
144
177
|
APILogsModel.objects.using(self.DRF_API_LOGGER_DEFAULT_DATABASE).bulk_create(bulk_item)
|
|
145
178
|
self._increment_stat('_inserted_count', len(bulk_item))
|
|
179
|
+
try:
|
|
180
|
+
recorder = get_recorder()
|
|
181
|
+
recorder.increment_processed_logs('database', len(bulk_item))
|
|
182
|
+
recorder.observe_flush('database', time.perf_counter() - flush_start, len(bulk_item))
|
|
183
|
+
recorder.observe_storage_write('database', time.perf_counter() - flush_start)
|
|
184
|
+
self._record_queue_metrics(recorder)
|
|
185
|
+
except Exception:
|
|
186
|
+
pass
|
|
146
187
|
except OperationalError:
|
|
147
188
|
self._increment_stat('_failed_insert_count', len(bulk_item))
|
|
189
|
+
try:
|
|
190
|
+
recorder = get_recorder()
|
|
191
|
+
recorder.increment_storage_write_failure('database', 'OperationalError')
|
|
192
|
+
recorder.observe_storage_write('database', time.perf_counter() - flush_start)
|
|
193
|
+
except Exception:
|
|
194
|
+
pass
|
|
148
195
|
raise Exception("""
|
|
149
196
|
DRF API LOGGER EXCEPTION
|
|
150
197
|
Model does not exist.
|
|
@@ -152,6 +199,12 @@ class InsertLogIntoDatabase(Thread):
|
|
|
152
199
|
""")
|
|
153
200
|
except Exception as e:
|
|
154
201
|
self._increment_stat('_failed_insert_count', len(bulk_item))
|
|
202
|
+
try:
|
|
203
|
+
recorder = get_recorder()
|
|
204
|
+
recorder.increment_storage_write_failure('database', e.__class__.__name__)
|
|
205
|
+
recorder.observe_storage_write('database', time.perf_counter() - flush_start)
|
|
206
|
+
except Exception:
|
|
207
|
+
pass
|
|
155
208
|
# Logs other unexpected exceptions to the console
|
|
156
209
|
print('DRF API LOGGER EXCEPTION:', e)
|
|
157
210
|
|
|
@@ -182,6 +235,10 @@ class InsertLogIntoDatabase(Thread):
|
|
|
182
235
|
self._stop_event.set()
|
|
183
236
|
self._flush_event.set()
|
|
184
237
|
self._start_bulk_insertion()
|
|
238
|
+
try:
|
|
239
|
+
get_recorder().set_worker_up(self.name or 'insert_log_into_database', False)
|
|
240
|
+
except Exception:
|
|
241
|
+
pass
|
|
185
242
|
|
|
186
243
|
def get_status(self):
|
|
187
244
|
"""
|
|
@@ -200,3 +257,10 @@ class InsertLogIntoDatabase(Thread):
|
|
|
200
257
|
def _increment_stat(self, name, amount=1):
|
|
201
258
|
with self._stats_lock:
|
|
202
259
|
setattr(self, name, getattr(self, name) + amount)
|
|
260
|
+
|
|
261
|
+
def _record_queue_metrics(self, recorder):
|
|
262
|
+
depth = self._queue.qsize()
|
|
263
|
+
capacity = self.DRF_LOGGER_QUEUE_MAX_SIZE
|
|
264
|
+
recorder.set_queue_depth('database', depth)
|
|
265
|
+
recorder.set_queue_capacity('database', capacity)
|
|
266
|
+
recorder.set_queue_utilization('database', depth / capacity if capacity else 0)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from drf_api_logger.metrics import settings as metrics_settings
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f]")
|
|
7
|
+
SAFE_ENUM_RE = re.compile(r"^[A-Za-z0-9_.:-]{1,64}$")
|
|
8
|
+
UNRESOLVED_ROUTE_LABEL = "unresolved"
|
|
9
|
+
UNRESOLVED_VIEW_LABEL = "unresolved"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _safe_text(value, max_length=None):
|
|
13
|
+
if value is None:
|
|
14
|
+
return None
|
|
15
|
+
max_length = max_length or metrics_settings.max_label_length()
|
|
16
|
+
value = str(value).strip()
|
|
17
|
+
if not value or len(value) > max_length:
|
|
18
|
+
return None
|
|
19
|
+
if CONTROL_CHAR_RE.search(value):
|
|
20
|
+
return None
|
|
21
|
+
return value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _safe_label_value(value):
|
|
25
|
+
return _safe_text(value) or metrics_settings.UNKNOWN_LABEL_VALUE
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _safe_enum_value(value):
|
|
29
|
+
value = _safe_text(value, max_length=64)
|
|
30
|
+
if not value or not SAFE_ENUM_RE.match(value):
|
|
31
|
+
return metrics_settings.UNKNOWN_LABEL_VALUE
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _safe_method(value):
|
|
36
|
+
value = _safe_text(value, max_length=16)
|
|
37
|
+
if not value:
|
|
38
|
+
return metrics_settings.UNKNOWN_LABEL_VALUE
|
|
39
|
+
value = value.upper()
|
|
40
|
+
if not SAFE_ENUM_RE.match(value):
|
|
41
|
+
return metrics_settings.UNKNOWN_LABEL_VALUE
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def status_class(status_code):
|
|
46
|
+
try:
|
|
47
|
+
status_code = int(status_code)
|
|
48
|
+
except (TypeError, ValueError):
|
|
49
|
+
return metrics_settings.UNKNOWN_LABEL_VALUE
|
|
50
|
+
if status_code < 100 or status_code > 599:
|
|
51
|
+
return metrics_settings.UNKNOWN_LABEL_VALUE
|
|
52
|
+
return "{}xx".format(status_code // 100)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _view_name(resolver_match):
|
|
56
|
+
if resolver_match is None:
|
|
57
|
+
return None
|
|
58
|
+
view_func = getattr(resolver_match, "func", None)
|
|
59
|
+
view_class = getattr(view_func, "view_class", None)
|
|
60
|
+
class_module = getattr(view_class, "__module__", None)
|
|
61
|
+
class_name = getattr(view_class, "__name__", None)
|
|
62
|
+
if type(class_module) is str and type(class_name) is str:
|
|
63
|
+
return "{}.{}".format(class_module, class_name)
|
|
64
|
+
|
|
65
|
+
func_module = getattr(view_func, "__module__", None)
|
|
66
|
+
func_name = getattr(view_func, "__name__", None)
|
|
67
|
+
if type(func_module) is str and type(func_name) is str:
|
|
68
|
+
return "{}.{}".format(func_module, func_name)
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_low_cardinality_from_resolver(resolver_match, status_code=None):
|
|
73
|
+
if resolver_match is None:
|
|
74
|
+
return {
|
|
75
|
+
"route": UNRESOLVED_ROUTE_LABEL,
|
|
76
|
+
"view_name": UNRESOLVED_VIEW_LABEL,
|
|
77
|
+
"status_class": status_class(status_code),
|
|
78
|
+
}
|
|
79
|
+
values = {
|
|
80
|
+
"route": getattr(resolver_match, "route", None),
|
|
81
|
+
"view_name": _view_name(resolver_match),
|
|
82
|
+
"app_name": getattr(resolver_match, "app_name", None),
|
|
83
|
+
"namespace": getattr(resolver_match, "namespace", None),
|
|
84
|
+
"url_name": getattr(resolver_match, "url_name", None),
|
|
85
|
+
"status_class": status_class(status_code),
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
key: _safe_label_value(value)
|
|
89
|
+
for key, value in values.items()
|
|
90
|
+
if _safe_text(value) or key == "status_class"
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _event_low_cardinality(event):
|
|
95
|
+
value = event.get("low_cardinality", {})
|
|
96
|
+
return value if type(value) is dict else {}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def build_http_labels(event):
|
|
100
|
+
low_cardinality = _event_low_cardinality(event)
|
|
101
|
+
labels = {}
|
|
102
|
+
for key in metrics_settings.metric_label_keys():
|
|
103
|
+
if key == "method":
|
|
104
|
+
labels[key] = _safe_method(event.get("method"))
|
|
105
|
+
elif key == "status_code":
|
|
106
|
+
labels[key] = _safe_label_value(event.get("status_code"))
|
|
107
|
+
elif key == "status_class":
|
|
108
|
+
labels[key] = _safe_label_value(
|
|
109
|
+
low_cardinality.get("status_class")
|
|
110
|
+
or event.get("status_class")
|
|
111
|
+
or status_class(event.get("status_code"))
|
|
112
|
+
)
|
|
113
|
+
elif key == "route":
|
|
114
|
+
labels[key] = _safe_label_value(low_cardinality.get("route") or event.get("route"))
|
|
115
|
+
elif key in metrics_settings.ALLOWED_LABELS:
|
|
116
|
+
labels[key] = _safe_label_value(low_cardinality.get(key) or event.get(key))
|
|
117
|
+
return labels
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def build_http_core_labels(event):
|
|
121
|
+
low_cardinality = _event_low_cardinality(event)
|
|
122
|
+
return {
|
|
123
|
+
"method": _safe_method(event.get("method")),
|
|
124
|
+
"route": _safe_label_value(low_cardinality.get("route") or event.get("route")),
|
|
125
|
+
"view_name": _safe_label_value(low_cardinality.get("view_name") or event.get("view_name")),
|
|
126
|
+
"status_code": _safe_label_value(event.get("status_code")),
|
|
127
|
+
"status_class": _safe_label_value(
|
|
128
|
+
low_cardinality.get("status_class")
|
|
129
|
+
or event.get("status_class")
|
|
130
|
+
or status_class(event.get("status_code"))
|
|
131
|
+
),
|
|
132
|
+
"exception_class": _safe_enum_value(event.get("exception_class")),
|
|
133
|
+
"throttle_scope": _safe_enum_value(event.get("throttle_scope")),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def build_logger_labels(labels=None):
|
|
138
|
+
labels = labels or {}
|
|
139
|
+
safe = {}
|
|
140
|
+
for key, value in labels.items():
|
|
141
|
+
if key in metrics_settings.ALLOWED_LABELS and key not in metrics_settings.FORBIDDEN_LABELS:
|
|
142
|
+
safe[key] = _safe_label_value(value)
|
|
143
|
+
return safe
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def build_security_labels(signal):
|
|
147
|
+
return {
|
|
148
|
+
"event_type": _safe_enum_value(signal.event_type),
|
|
149
|
+
"category": _safe_enum_value(signal.category),
|
|
150
|
+
"severity": _safe_enum_value(signal.severity),
|
|
151
|
+
"rule_id": _safe_enum_value(signal.rule_id),
|
|
152
|
+
"route": _safe_label_value(signal.route),
|
|
153
|
+
"method": _safe_method(signal.method),
|
|
154
|
+
"status_class": _safe_enum_value(signal.status_class),
|
|
155
|
+
"outcome": _safe_enum_value(signal.outcome),
|
|
156
|
+
"reason": _safe_enum_value(signal.reason),
|
|
157
|
+
}
|