drf-api-logger 1.3.0__tar.gz → 1.4.1__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-1.4.1}/PKG-INFO +152 -6
- drf_api_logger-1.3.0/drf_api_logger.egg-info/PKG-INFO → drf_api_logger-1.4.1/README.md +145 -50
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/apps.py +1 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/insert_log_into_database.py +76 -12
- drf_api_logger-1.4.1/drf_api_logger/metrics/__init__.py +3 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/labels.py +157 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/noop.py +86 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/prometheus.py +648 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/recorder.py +37 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/rules.py +374 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/security.py +75 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/settings.py +298 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/state.py +42 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/system_checks.py +75 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/urls.py +13 -0
- drf_api_logger-1.4.1/drf_api_logger/metrics/views.py +20 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/middleware/api_logger_middleware.py +433 -87
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/utils.py +10 -2
- drf_api_logger-1.3.0/README.md → drf_api_logger-1.4.1/drf_api_logger.egg-info/PKG-INFO +196 -3
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/SOURCES.txt +15 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/requires.txt +3 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/llms.txt +35 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/setup.py +7 -3
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_backward_compat.py +11 -9
- drf_api_logger-1.4.1/tests/test_logging_regressions.py +341 -0
- drf_api_logger-1.4.1/tests/test_metrics.py +898 -0
- drf_api_logger-1.4.1/tests/test_publish_workflow.py +49 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_signals.py +15 -8
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/LICENSE +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/MANIFEST.in +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/admin.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/collectstatic.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/correlation.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/diagnostics.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/events.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/logging_context.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/management/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/management/commands/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/management/commands/drf_api_logger_doctor.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/management/commands/prune_api_logs.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/middleware/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/0001_initial.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/0002_auto_20211221_2155.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/0003_apilogsmodel_profiling.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/__init__.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/models.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/observability.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/policy.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/static/drf_api_logger/css/Chart.min.css +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/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.1}/drf_api_logger/templates/change_form.html +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/templates/charts_change_list.html +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger/tests.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/dependency_links.txt +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/top_level.txt +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/pyproject.toml +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/setup.cfg +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_admin_charts.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_admin_templates.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_asgi_middleware.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_correlation.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_diagnostics.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_docs_content.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_integration.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_management_commands.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_media_url_issue.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_middleware.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_models.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_observability.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_policy.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_profiling.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_settings.py +0 -0
- {drf_api_logger-1.3.0 → drf_api_logger-1.4.1}/tests/test_utils.py +0 -0
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: drf-api-logger
|
|
3
|
-
Version: 1.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 1.4.1
|
|
4
|
+
Summary: Request and response observability for Django REST Framework: 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
|
-
Project-URL: Documentation, https://
|
|
9
|
+
Project-URL: Documentation, https://drf-api-logger.readthedocs.io/en/latest/
|
|
10
|
+
Project-URL: Maintainer Tutorial, https://coderssecret.com/blog/drf-api-logger-django-rest-framework
|
|
10
11
|
Project-URL: Operations Guide, https://github.com/vishalanandl177/DRF-API-Logger/blob/main/docs/operations.rst
|
|
11
12
|
Project-URL: AI Guidance, https://github.com/vishalanandl177/DRF-API-Logger/blob/main/llms.txt
|
|
12
13
|
Project-URL: Source, https://github.com/vishalanandl177/DRF-API-Logger
|
|
@@ -32,6 +33,8 @@ License-File: LICENSE
|
|
|
32
33
|
Requires-Dist: Django>=4.2
|
|
33
34
|
Requires-Dist: djangorestframework>=3.16
|
|
34
35
|
Requires-Dist: bleach>=3.1.5
|
|
36
|
+
Provides-Extra: prometheus
|
|
37
|
+
Requires-Dist: prometheus-client>=0.20; extra == "prometheus"
|
|
35
38
|
Dynamic: author
|
|
36
39
|
Dynamic: author-email
|
|
37
40
|
Dynamic: classifier
|
|
@@ -41,20 +44,21 @@ Dynamic: home-page
|
|
|
41
44
|
Dynamic: license
|
|
42
45
|
Dynamic: license-file
|
|
43
46
|
Dynamic: project-url
|
|
47
|
+
Dynamic: provides-extra
|
|
44
48
|
Dynamic: requires-dist
|
|
45
49
|
Dynamic: requires-python
|
|
46
50
|
Dynamic: summary
|
|
47
51
|
|
|
48
52
|
# DRF API Logger
|
|
49
53
|
|
|
50
|
-
[](https://github.com/vishalanandl177/DRF-API-Logger)
|
|
51
55
|
[](https://www.python.org)
|
|
52
56
|
[](https://djangoproject.com)
|
|
53
57
|
[](https://www.django-rest-framework.org)
|
|
54
58
|
[](http://pepy.tech/project/drf-api-logger)
|
|
55
59
|
[](https://opensource.org/licenses/Apache-2.0)
|
|
56
60
|
|
|
57
|
-
**
|
|
61
|
+
**Request and response observability for Django REST Framework.** Configurable logging, profiling, masking, and admin analytics with production safety controls.
|
|
58
62
|
|
|
59
63
|
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
64
|
|
|
@@ -116,10 +120,18 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
116
120
|
- **Request Correlation**: Opt-in request IDs, traceparent parsing, route metadata, logging context, and signal metadata without new database columns
|
|
117
121
|
- **ASGI-Native Logging**: Supports Django's async middleware chain with concurrent request context isolation
|
|
118
122
|
- **Safe Observability Integrations**: Optional helpers for Prometheus labels, OpenTelemetry span attributes, and Sentry context without hard dependencies
|
|
123
|
+
- **First-Party Metrics & Security Signals**: Optional logger health, pipeline, API timing, and detect-only security metrics with safe labels
|
|
119
124
|
- **Policy Controls**: Optional endpoint-specific rules for logging, masking, payload stripping, and signal/export gating
|
|
120
125
|
|
|
121
126
|
### 🌐 Community & Support
|
|
122
127
|
|
|
128
|
+
For a maintainer-led walkthrough of safe request logging, masking, profiling,
|
|
129
|
+
retention, and production trade-offs, read the
|
|
130
|
+
[DRF API Logger production guide on CodersSecret](https://coderssecret.com/blog/drf-api-logger-django-rest-framework).
|
|
131
|
+
DRF API Logger is also listed in Django REST Framework's
|
|
132
|
+
[third-party packages documentation](https://www.django-rest-framework.org/community/third-party-packages/).
|
|
133
|
+
That ecosystem listing is not an endorsement or certification.
|
|
134
|
+
|
|
123
135
|
<p align="center">
|
|
124
136
|
<a href="https://discord.gg/eeYansFDCT"><img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" alt="Join Discord"/></a>
|
|
125
137
|
<a href="https://www.instagram.com/coderssecret/"><img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white" alt="Follow on Instagram"/></a>
|
|
@@ -127,6 +139,20 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
127
139
|
<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
140
|
</p>
|
|
129
141
|
|
|
142
|
+
#### Support maintenance
|
|
143
|
+
|
|
144
|
+
DRF API Logger is free and open source. If your team uses it in production,
|
|
145
|
+
consider supporting ongoing maintenance.
|
|
146
|
+
|
|
147
|
+
Support helps with:
|
|
148
|
+
|
|
149
|
+
- Django, DRF, and Python compatibility updates
|
|
150
|
+
- Security, masking, and privacy improvements
|
|
151
|
+
- Bug fixes, issue triage, and release validation
|
|
152
|
+
- Documentation, examples, and production guidance
|
|
153
|
+
|
|
154
|
+
Support maintenance: [Buy Me a Coffee](https://buymeacoffee.com/riptechlead)
|
|
155
|
+
|
|
130
156
|
## 📦 Installation
|
|
131
157
|
|
|
132
158
|
### 1. Install Package
|
|
@@ -285,10 +311,13 @@ API_LOGGER_SIGNAL.listen -= log_to_file
|
|
|
285
311
|
- [Copy-paste setup recipes](docs/quickstart.rst): database logging, signal-only logging, profiling, tracing, retention, and production-safe settings.
|
|
286
312
|
- [ASGI-native logging](docs/asgi.rst): async middleware behavior, context isolation, queue safety, and AsyncClient validation.
|
|
287
313
|
- [Safe observability integrations](docs/observability_integrations.rst): Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
|
|
314
|
+
- [First-party metrics](docs/metrics.rst): optional Prometheus recorder, logger overhead, queue health, API metrics, safe labels, and endpoint guidance.
|
|
315
|
+
- [Security signals](docs/security_signals.rst): detect-only suspicious activity metrics, bounded body inspection, rule IDs, and false-positive guidance.
|
|
288
316
|
- [Policy controls](docs/policy_controls.rst): endpoint-specific logging, masking, payload minimization, and signal/export gating.
|
|
289
317
|
- [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
|
|
290
318
|
- [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
|
|
291
319
|
- [Tutorials and community snippets](docs/tutorials.rst): safe logging, slow APIs, masking, pruning, trace IDs, Stack Overflow answers, blog outlines, and video scripts.
|
|
320
|
+
- [Release checklist](docs/release_checklist.rst): versioning, compatibility, package metadata, documentation links, build validation, and release verification.
|
|
292
321
|
- [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
|
|
293
322
|
- [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
|
|
294
323
|
|
|
@@ -310,6 +339,15 @@ DRF_LOGGER_INTERVAL = 10 # Default: 10 seconds
|
|
|
310
339
|
database write. Request threads enqueue records and wake the background worker
|
|
311
340
|
when this threshold is reached; they do not perform the bulk insert themselves.
|
|
312
341
|
|
|
342
|
+
The queue is unbounded; this setting is not a memory limit. Before each batch,
|
|
343
|
+
the worker closes old or unusable Django database connections. If a write fails,
|
|
344
|
+
the batch is discarded without retry, `failed_insert_count` increases by its
|
|
345
|
+
record count, and the worker continues with later batches. Failure reports use
|
|
346
|
+
the `drf_api_logger.insert_log_into_database` Python logger at `ERROR` level and
|
|
347
|
+
include only the batch size and exception class, not SQL or exception messages.
|
|
348
|
+
Monitor failed inserts and queue backlog as described in the
|
|
349
|
+
[operations guide](docs/operations.rst).
|
|
350
|
+
|
|
313
351
|
### Selective Logging
|
|
314
352
|
|
|
315
353
|
**Skip by Namespace:**
|
|
@@ -352,6 +390,20 @@ Default masking also covers common credential-bearing headers and keys such as
|
|
|
352
390
|
`private_key`, `sessionid`, and `csrfmiddlewaretoken`. Matching is
|
|
353
391
|
case-insensitive and treats hyphens and underscores equivalently.
|
|
354
392
|
|
|
393
|
+
Keys match exactly or end with a sensitive key preceded by `_` or `-`. This
|
|
394
|
+
masks `access_token`, `refresh_token`, `id_token`, `auth_token`, and
|
|
395
|
+
`user_password` in URLs, nested bodies, and headers before database storage or
|
|
396
|
+
signal emission. `token_type` and `accessibility` remain visible; adding `key`
|
|
397
|
+
masks `tenant_key` but not `monkey`. The same rule applies to configured
|
|
398
|
+
exclusions and per-request policy mask keys. CamelCase names such as
|
|
399
|
+
`accessToken` require an explicit exclusion.
|
|
400
|
+
|
|
401
|
+
Query parameter names are URL-decoded once for matching, so `access_%74oken`
|
|
402
|
+
is masked too. Original key spelling, parameter order, repeated parameters,
|
|
403
|
+
and unrelated values are preserved. This does not inspect arbitrary text or
|
|
404
|
+
rewrite previously stored logs. After upgrading, review existing logs and
|
|
405
|
+
exports for exposed credentials and rotate affected credentials as appropriate.
|
|
406
|
+
|
|
355
407
|
**Database Configuration:**
|
|
356
408
|
```python
|
|
357
409
|
# Use specific database for logs
|
|
@@ -609,6 +661,100 @@ traces, and Sentry context, not metrics labels. The helpers do not import
|
|
|
609
661
|
Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
|
|
610
662
|
exporter configuration.
|
|
611
663
|
|
|
664
|
+
### First-Party Metrics & Security Signals
|
|
665
|
+
|
|
666
|
+
Enable optional package-owned metrics when you want DRF API Logger to report its
|
|
667
|
+
own overhead and background pipeline health:
|
|
668
|
+
|
|
669
|
+
```bash
|
|
670
|
+
pip install "drf-api-logger[prometheus]"
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
```python
|
|
674
|
+
DRF_API_LOGGER_METRICS_ENABLED = True
|
|
675
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline"]
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
Logger and pipeline metrics include request-path overhead, payload capture,
|
|
679
|
+
masking, serialization, enqueue duration, queue depth, queue utilization,
|
|
680
|
+
worker up/down state, worker starts, flush duration, batch size, storage write
|
|
681
|
+
duration, dropped/skipped logs, and storage write failures.
|
|
682
|
+
|
|
683
|
+
API request metrics are disabled separately to avoid duplicate instrumentation:
|
|
684
|
+
|
|
685
|
+
```python
|
|
686
|
+
DRF_API_LOGGER_API_METRICS_ENABLED = True
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
API metrics include request count, duration, active requests, request and
|
|
690
|
+
non-streaming response body sizes, slow-request counts, exception counts, and
|
|
691
|
+
HTTP 429 throttle counts using normalized route labels.
|
|
692
|
+
|
|
693
|
+
Profiling metrics are available when profiling data exists:
|
|
694
|
+
|
|
695
|
+
```python
|
|
696
|
+
DRF_API_LOGGER_ENABLE_PROFILING = True
|
|
697
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline", "profiling"]
|
|
698
|
+
```
|
|
699
|
+
|
|
700
|
+
They summarize SQL duration, query count, duplicate query count, likely N+1
|
|
701
|
+
signals, view/serialization duration, and middleware duration without exposing
|
|
702
|
+
SQL text as labels.
|
|
703
|
+
|
|
704
|
+
These metrics support practical dashboards and alerts: watch queue depth and
|
|
705
|
+
storage failures to protect log reliability, compare request overhead against
|
|
706
|
+
API latency, find SQL-heavy or likely N+1 endpoints, and alert on suspicious
|
|
707
|
+
security rule matches such as auth failures, route scans, payload attacks, and
|
|
708
|
+
bulk export behavior. See [First-party metrics](docs/metrics.rst) for PromQL
|
|
709
|
+
examples.
|
|
710
|
+
|
|
711
|
+
Security signals are detect-only and disabled by default:
|
|
712
|
+
|
|
713
|
+
```python
|
|
714
|
+
DRF_API_LOGGER_SECURITY_METRICS_ENABLED = True
|
|
715
|
+
DRF_API_LOGGER_SECURITY_MODE = "detect"
|
|
716
|
+
DRF_API_LOGGER_SECURITY_BODY_INSPECTION = {
|
|
717
|
+
"enabled": True,
|
|
718
|
+
"max_body_bytes": 8192,
|
|
719
|
+
"inspect_request_body": True,
|
|
720
|
+
"inspect_response_body": False,
|
|
721
|
+
}
|
|
722
|
+
```
|
|
723
|
+
|
|
724
|
+
Rules `DRFSEC-001` through `DRFSEC-016` cover authentication failures,
|
|
725
|
+
success-after-failure patterns, token failures, authorization failures,
|
|
726
|
+
admin/debug probes, payload attack patterns, rate-limit pressure, route scans,
|
|
727
|
+
object ID enumeration hints, log injection, sensitive response-field hints,
|
|
728
|
+
pagination sweeps, bulk exports, high response volume, sensitive business
|
|
729
|
+
routes, and repeated business-flow actions. Correlation uses bounded
|
|
730
|
+
process-local state and internal HMAC actor fingerprints, never metric labels.
|
|
731
|
+
|
|
732
|
+
Metric labels are allowlisted and low-cardinality. Do not use raw URLs, query
|
|
733
|
+
strings, request IDs, trace IDs, user IDs, IPs, object IDs, tokens, headers,
|
|
734
|
+
request bodies, response bodies, SQL queries, or exception messages as labels.
|
|
735
|
+
Unresolved 404 paths use fixed `route="unresolved"` and
|
|
736
|
+
`view_name="unresolved"` labels instead of raw paths.
|
|
737
|
+
|
|
738
|
+
The optional Prometheus endpoint is off by default:
|
|
739
|
+
|
|
740
|
+
```python
|
|
741
|
+
DRF_API_LOGGER_METRICS_PROMETHEUS_ENDPOINT_ENABLED = True
|
|
742
|
+
```
|
|
743
|
+
|
|
744
|
+
Mount it only under an internal protected path:
|
|
745
|
+
|
|
746
|
+
```python
|
|
747
|
+
from django.urls import include, path
|
|
748
|
+
|
|
749
|
+
urlpatterns = [
|
|
750
|
+
path("internal/drf-api-logger/", include("drf_api_logger.metrics.urls")),
|
|
751
|
+
]
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
Run `python manage.py check` after enabling metrics. The checks report missing
|
|
755
|
+
Prometheus dependencies, unsafe labels, endpoint exposure warnings, and unsafe
|
|
756
|
+
security body-inspection limits.
|
|
757
|
+
|
|
612
758
|
## 📊 Programmatic Access
|
|
613
759
|
|
|
614
760
|
### Querying Log Data
|
|
@@ -801,7 +947,7 @@ Use `drf-api-logger`. It automatically masks `password`, `token`, `access`, `ref
|
|
|
801
947
|
|
|
802
948
|
**How to find slow APIs and N+1 queries in Django REST Framework?**
|
|
803
949
|
|
|
804
|
-
Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it
|
|
950
|
+
Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it can break sampled requests into middleware time, view time, and SQL time. It detects likely N+1 query patterns (high query count plus high SQL percentage) and surfaces the evidence in the admin for investigation.
|
|
805
951
|
|
|
806
952
|
**How to monitor Django REST API performance in production?**
|
|
807
953
|
|
|
@@ -1,60 +1,13 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: drf-api-logger
|
|
3
|
-
Version: 1.3.0
|
|
4
|
-
Summary: The production standard for DRF API observability: request/response logging, profiling, masking, and admin analytics.
|
|
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
|
-
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
|
|
12
|
-
Project-URL: Source, https://github.com/vishalanandl177/DRF-API-Logger
|
|
13
|
-
Project-URL: Issue Tracker, https://github.com/vishalanandl177/DRF-API-Logger/issues
|
|
14
|
-
Classifier: Programming Language :: Python :: 3
|
|
15
|
-
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
-
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
-
Classifier: Framework :: Django
|
|
21
|
-
Classifier: Framework :: Django :: 4.2
|
|
22
|
-
Classifier: Framework :: Django :: 5.0
|
|
23
|
-
Classifier: Framework :: Django :: 5.1
|
|
24
|
-
Classifier: Framework :: Django :: 5.2
|
|
25
|
-
Classifier: Framework :: Django :: 6.0
|
|
26
|
-
Classifier: Operating System :: OS Independent
|
|
27
|
-
Classifier: Topic :: Internet :: WWW/HTTP
|
|
28
|
-
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
29
|
-
Requires-Python: >=3.10
|
|
30
|
-
Description-Content-Type: text/markdown
|
|
31
|
-
License-File: LICENSE
|
|
32
|
-
Requires-Dist: Django>=4.2
|
|
33
|
-
Requires-Dist: djangorestframework>=3.16
|
|
34
|
-
Requires-Dist: bleach>=3.1.5
|
|
35
|
-
Dynamic: author
|
|
36
|
-
Dynamic: author-email
|
|
37
|
-
Dynamic: classifier
|
|
38
|
-
Dynamic: description
|
|
39
|
-
Dynamic: description-content-type
|
|
40
|
-
Dynamic: home-page
|
|
41
|
-
Dynamic: license
|
|
42
|
-
Dynamic: license-file
|
|
43
|
-
Dynamic: project-url
|
|
44
|
-
Dynamic: requires-dist
|
|
45
|
-
Dynamic: requires-python
|
|
46
|
-
Dynamic: summary
|
|
47
|
-
|
|
48
1
|
# DRF API Logger
|
|
49
2
|
|
|
50
|
-
[](https://github.com/vishalanandl177/DRF-API-Logger)
|
|
51
4
|
[](https://www.python.org)
|
|
52
5
|
[](https://djangoproject.com)
|
|
53
6
|
[](https://www.django-rest-framework.org)
|
|
54
7
|
[](http://pepy.tech/project/drf-api-logger)
|
|
55
8
|
[](https://opensource.org/licenses/Apache-2.0)
|
|
56
9
|
|
|
57
|
-
**
|
|
10
|
+
**Request and response observability for Django REST Framework.** Configurable logging, profiling, masking, and admin analytics with production safety controls.
|
|
58
11
|
|
|
59
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.
|
|
60
13
|
|
|
@@ -116,10 +69,18 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
116
69
|
- **Request Correlation**: Opt-in request IDs, traceparent parsing, route metadata, logging context, and signal metadata without new database columns
|
|
117
70
|
- **ASGI-Native Logging**: Supports Django's async middleware chain with concurrent request context isolation
|
|
118
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
|
|
119
73
|
- **Policy Controls**: Optional endpoint-specific rules for logging, masking, payload stripping, and signal/export gating
|
|
120
74
|
|
|
121
75
|
### 🌐 Community & Support
|
|
122
76
|
|
|
77
|
+
For a maintainer-led walkthrough of safe request logging, masking, profiling,
|
|
78
|
+
retention, and production trade-offs, read the
|
|
79
|
+
[DRF API Logger production guide on CodersSecret](https://coderssecret.com/blog/drf-api-logger-django-rest-framework).
|
|
80
|
+
DRF API Logger is also listed in Django REST Framework's
|
|
81
|
+
[third-party packages documentation](https://www.django-rest-framework.org/community/third-party-packages/).
|
|
82
|
+
That ecosystem listing is not an endorsement or certification.
|
|
83
|
+
|
|
123
84
|
<p align="center">
|
|
124
85
|
<a href="https://discord.gg/eeYansFDCT"><img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" alt="Join Discord"/></a>
|
|
125
86
|
<a href="https://www.instagram.com/coderssecret/"><img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white" alt="Follow on Instagram"/></a>
|
|
@@ -127,6 +88,20 @@ DRF API Logger automatically captures and stores comprehensive API information:
|
|
|
127
88
|
<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
89
|
</p>
|
|
129
90
|
|
|
91
|
+
#### Support maintenance
|
|
92
|
+
|
|
93
|
+
DRF API Logger is free and open source. If your team uses it in production,
|
|
94
|
+
consider supporting ongoing maintenance.
|
|
95
|
+
|
|
96
|
+
Support helps with:
|
|
97
|
+
|
|
98
|
+
- Django, DRF, and Python compatibility updates
|
|
99
|
+
- Security, masking, and privacy improvements
|
|
100
|
+
- Bug fixes, issue triage, and release validation
|
|
101
|
+
- Documentation, examples, and production guidance
|
|
102
|
+
|
|
103
|
+
Support maintenance: [Buy Me a Coffee](https://buymeacoffee.com/riptechlead)
|
|
104
|
+
|
|
130
105
|
## 📦 Installation
|
|
131
106
|
|
|
132
107
|
### 1. Install Package
|
|
@@ -285,10 +260,13 @@ API_LOGGER_SIGNAL.listen -= log_to_file
|
|
|
285
260
|
- [Copy-paste setup recipes](docs/quickstart.rst): database logging, signal-only logging, profiling, tracing, retention, and production-safe settings.
|
|
286
261
|
- [ASGI-native logging](docs/asgi.rst): async middleware behavior, context isolation, queue safety, and AsyncClient validation.
|
|
287
262
|
- [Safe observability integrations](docs/observability_integrations.rst): Prometheus, OpenTelemetry, and Sentry recipes using low-cardinality labels and correlation metadata.
|
|
263
|
+
- [First-party metrics](docs/metrics.rst): optional Prometheus recorder, logger overhead, queue health, API metrics, safe labels, and endpoint guidance.
|
|
264
|
+
- [Security signals](docs/security_signals.rst): detect-only suspicious activity metrics, bounded body inspection, rule IDs, and false-positive guidance.
|
|
288
265
|
- [Policy controls](docs/policy_controls.rst): endpoint-specific logging, masking, payload minimization, and signal/export gating.
|
|
289
266
|
- [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
|
|
290
267
|
- [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
|
|
291
268
|
- [Tutorials and community snippets](docs/tutorials.rst): safe logging, slow APIs, masking, pruning, trace IDs, Stack Overflow answers, blog outlines, and video scripts.
|
|
269
|
+
- [Release checklist](docs/release_checklist.rst): versioning, compatibility, package metadata, documentation links, build validation, and release verification.
|
|
292
270
|
- [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
|
|
293
271
|
- [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
|
|
294
272
|
|
|
@@ -310,6 +288,15 @@ DRF_LOGGER_INTERVAL = 10 # Default: 10 seconds
|
|
|
310
288
|
database write. Request threads enqueue records and wake the background worker
|
|
311
289
|
when this threshold is reached; they do not perform the bulk insert themselves.
|
|
312
290
|
|
|
291
|
+
The queue is unbounded; this setting is not a memory limit. Before each batch,
|
|
292
|
+
the worker closes old or unusable Django database connections. If a write fails,
|
|
293
|
+
the batch is discarded without retry, `failed_insert_count` increases by its
|
|
294
|
+
record count, and the worker continues with later batches. Failure reports use
|
|
295
|
+
the `drf_api_logger.insert_log_into_database` Python logger at `ERROR` level and
|
|
296
|
+
include only the batch size and exception class, not SQL or exception messages.
|
|
297
|
+
Monitor failed inserts and queue backlog as described in the
|
|
298
|
+
[operations guide](docs/operations.rst).
|
|
299
|
+
|
|
313
300
|
### Selective Logging
|
|
314
301
|
|
|
315
302
|
**Skip by Namespace:**
|
|
@@ -352,6 +339,20 @@ Default masking also covers common credential-bearing headers and keys such as
|
|
|
352
339
|
`private_key`, `sessionid`, and `csrfmiddlewaretoken`. Matching is
|
|
353
340
|
case-insensitive and treats hyphens and underscores equivalently.
|
|
354
341
|
|
|
342
|
+
Keys match exactly or end with a sensitive key preceded by `_` or `-`. This
|
|
343
|
+
masks `access_token`, `refresh_token`, `id_token`, `auth_token`, and
|
|
344
|
+
`user_password` in URLs, nested bodies, and headers before database storage or
|
|
345
|
+
signal emission. `token_type` and `accessibility` remain visible; adding `key`
|
|
346
|
+
masks `tenant_key` but not `monkey`. The same rule applies to configured
|
|
347
|
+
exclusions and per-request policy mask keys. CamelCase names such as
|
|
348
|
+
`accessToken` require an explicit exclusion.
|
|
349
|
+
|
|
350
|
+
Query parameter names are URL-decoded once for matching, so `access_%74oken`
|
|
351
|
+
is masked too. Original key spelling, parameter order, repeated parameters,
|
|
352
|
+
and unrelated values are preserved. This does not inspect arbitrary text or
|
|
353
|
+
rewrite previously stored logs. After upgrading, review existing logs and
|
|
354
|
+
exports for exposed credentials and rotate affected credentials as appropriate.
|
|
355
|
+
|
|
355
356
|
**Database Configuration:**
|
|
356
357
|
```python
|
|
357
358
|
# Use specific database for logs
|
|
@@ -609,6 +610,100 @@ traces, and Sentry context, not metrics labels. The helpers do not import
|
|
|
609
610
|
Prometheus, OpenTelemetry, or Sentry; applications own those dependencies and
|
|
610
611
|
exporter configuration.
|
|
611
612
|
|
|
613
|
+
### First-Party Metrics & Security Signals
|
|
614
|
+
|
|
615
|
+
Enable optional package-owned metrics when you want DRF API Logger to report its
|
|
616
|
+
own overhead and background pipeline health:
|
|
617
|
+
|
|
618
|
+
```bash
|
|
619
|
+
pip install "drf-api-logger[prometheus]"
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
```python
|
|
623
|
+
DRF_API_LOGGER_METRICS_ENABLED = True
|
|
624
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline"]
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
Logger and pipeline metrics include request-path overhead, payload capture,
|
|
628
|
+
masking, serialization, enqueue duration, queue depth, queue utilization,
|
|
629
|
+
worker up/down state, worker starts, flush duration, batch size, storage write
|
|
630
|
+
duration, dropped/skipped logs, and storage write failures.
|
|
631
|
+
|
|
632
|
+
API request metrics are disabled separately to avoid duplicate instrumentation:
|
|
633
|
+
|
|
634
|
+
```python
|
|
635
|
+
DRF_API_LOGGER_API_METRICS_ENABLED = True
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
API metrics include request count, duration, active requests, request and
|
|
639
|
+
non-streaming response body sizes, slow-request counts, exception counts, and
|
|
640
|
+
HTTP 429 throttle counts using normalized route labels.
|
|
641
|
+
|
|
642
|
+
Profiling metrics are available when profiling data exists:
|
|
643
|
+
|
|
644
|
+
```python
|
|
645
|
+
DRF_API_LOGGER_ENABLE_PROFILING = True
|
|
646
|
+
DRF_API_LOGGER_METRICS_GROUPS = ["logger", "pipeline", "profiling"]
|
|
647
|
+
```
|
|
648
|
+
|
|
649
|
+
They summarize SQL duration, query count, duplicate query count, likely N+1
|
|
650
|
+
signals, view/serialization duration, and middleware duration without exposing
|
|
651
|
+
SQL text as labels.
|
|
652
|
+
|
|
653
|
+
These metrics support practical dashboards and alerts: watch queue depth and
|
|
654
|
+
storage failures to protect log reliability, compare request overhead against
|
|
655
|
+
API latency, find SQL-heavy or likely N+1 endpoints, and alert on suspicious
|
|
656
|
+
security rule matches such as auth failures, route scans, payload attacks, and
|
|
657
|
+
bulk export behavior. See [First-party metrics](docs/metrics.rst) for PromQL
|
|
658
|
+
examples.
|
|
659
|
+
|
|
660
|
+
Security signals are detect-only and disabled by default:
|
|
661
|
+
|
|
662
|
+
```python
|
|
663
|
+
DRF_API_LOGGER_SECURITY_METRICS_ENABLED = True
|
|
664
|
+
DRF_API_LOGGER_SECURITY_MODE = "detect"
|
|
665
|
+
DRF_API_LOGGER_SECURITY_BODY_INSPECTION = {
|
|
666
|
+
"enabled": True,
|
|
667
|
+
"max_body_bytes": 8192,
|
|
668
|
+
"inspect_request_body": True,
|
|
669
|
+
"inspect_response_body": False,
|
|
670
|
+
}
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
Rules `DRFSEC-001` through `DRFSEC-016` cover authentication failures,
|
|
674
|
+
success-after-failure patterns, token failures, authorization failures,
|
|
675
|
+
admin/debug probes, payload attack patterns, rate-limit pressure, route scans,
|
|
676
|
+
object ID enumeration hints, log injection, sensitive response-field hints,
|
|
677
|
+
pagination sweeps, bulk exports, high response volume, sensitive business
|
|
678
|
+
routes, and repeated business-flow actions. Correlation uses bounded
|
|
679
|
+
process-local state and internal HMAC actor fingerprints, never metric labels.
|
|
680
|
+
|
|
681
|
+
Metric labels are allowlisted and low-cardinality. Do not use raw URLs, query
|
|
682
|
+
strings, request IDs, trace IDs, user IDs, IPs, object IDs, tokens, headers,
|
|
683
|
+
request bodies, response bodies, SQL queries, or exception messages as labels.
|
|
684
|
+
Unresolved 404 paths use fixed `route="unresolved"` and
|
|
685
|
+
`view_name="unresolved"` labels instead of raw paths.
|
|
686
|
+
|
|
687
|
+
The optional Prometheus endpoint is off by default:
|
|
688
|
+
|
|
689
|
+
```python
|
|
690
|
+
DRF_API_LOGGER_METRICS_PROMETHEUS_ENDPOINT_ENABLED = True
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
Mount it only under an internal protected path:
|
|
694
|
+
|
|
695
|
+
```python
|
|
696
|
+
from django.urls import include, path
|
|
697
|
+
|
|
698
|
+
urlpatterns = [
|
|
699
|
+
path("internal/drf-api-logger/", include("drf_api_logger.metrics.urls")),
|
|
700
|
+
]
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
Run `python manage.py check` after enabling metrics. The checks report missing
|
|
704
|
+
Prometheus dependencies, unsafe labels, endpoint exposure warnings, and unsafe
|
|
705
|
+
security body-inspection limits.
|
|
706
|
+
|
|
612
707
|
## 📊 Programmatic Access
|
|
613
708
|
|
|
614
709
|
### Querying Log Data
|
|
@@ -801,7 +896,7 @@ Use `drf-api-logger`. It automatically masks `password`, `token`, `access`, `ref
|
|
|
801
896
|
|
|
802
897
|
**How to find slow APIs and N+1 queries in Django REST Framework?**
|
|
803
898
|
|
|
804
|
-
Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it
|
|
899
|
+
Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it can break sampled requests into middleware time, view time, and SQL time. It detects likely N+1 query patterns (high query count plus high SQL percentage) and surfaces the evidence in the admin for investigation.
|
|
805
900
|
|
|
806
901
|
**How to monitor Django REST API performance in production?**
|
|
807
902
|
|
|
@@ -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,13 +1,19 @@
|
|
|
1
1
|
import atexit
|
|
2
|
+
import logging
|
|
2
3
|
import signal
|
|
4
|
+
import time
|
|
3
5
|
from queue import Empty, Queue
|
|
4
6
|
from importlib import import_module
|
|
5
7
|
from django.conf import settings
|
|
6
8
|
from threading import Thread, Event, Lock
|
|
7
|
-
from django.db
|
|
9
|
+
from django.db import close_old_connections
|
|
10
|
+
from drf_api_logger.metrics.recorder import get_recorder
|
|
8
11
|
from drf_api_logger.models import APILogsModel
|
|
9
12
|
|
|
10
13
|
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
11
17
|
class InsertLogIntoDatabase(Thread):
|
|
12
18
|
"""
|
|
13
19
|
A background thread that handles asynchronous, batched insertion of API log data
|
|
@@ -76,6 +82,13 @@ class InsertLogIntoDatabase(Thread):
|
|
|
76
82
|
if not self._atexit_registered:
|
|
77
83
|
atexit.register(self.shutdown)
|
|
78
84
|
self._atexit_registered = True
|
|
85
|
+
try:
|
|
86
|
+
recorder = get_recorder()
|
|
87
|
+
recorder.increment_worker_restart(self.name or 'insert_log_into_database')
|
|
88
|
+
recorder.set_worker_up(self.name or 'insert_log_into_database', True)
|
|
89
|
+
self._record_queue_metrics(recorder)
|
|
90
|
+
except Exception:
|
|
91
|
+
pass
|
|
79
92
|
self.start_queue_process()
|
|
80
93
|
|
|
81
94
|
def put_log_data(self, data):
|
|
@@ -90,14 +103,37 @@ class InsertLogIntoDatabase(Thread):
|
|
|
90
103
|
data = self.custom_handler(data)
|
|
91
104
|
if data is None:
|
|
92
105
|
self._increment_stat('_dropped_count')
|
|
106
|
+
try:
|
|
107
|
+
recorder = get_recorder()
|
|
108
|
+
recorder.increment_dropped_logs('custom_handler')
|
|
109
|
+
self._record_queue_metrics(recorder)
|
|
110
|
+
except Exception:
|
|
111
|
+
pass
|
|
93
112
|
return
|
|
94
113
|
|
|
114
|
+
enqueue_start = time.perf_counter()
|
|
95
115
|
try:
|
|
96
116
|
self._queue.put_nowait(APILogsModel(**data))
|
|
97
117
|
except Exception as e:
|
|
98
118
|
self._increment_stat('_dropped_count')
|
|
119
|
+
try:
|
|
120
|
+
recorder = get_recorder()
|
|
121
|
+
recorder.increment_dropped_logs('queue_error')
|
|
122
|
+
self._record_queue_metrics(recorder)
|
|
123
|
+
except Exception:
|
|
124
|
+
pass
|
|
99
125
|
print('DRF API LOGGER EXCEPTION:', e)
|
|
100
126
|
return
|
|
127
|
+
finally:
|
|
128
|
+
enqueue_duration = time.perf_counter() - enqueue_start
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
recorder = get_recorder()
|
|
132
|
+
recorder.observe_enqueue({'queue_name': 'database'}, enqueue_duration)
|
|
133
|
+
recorder.increment_enqueued_logs('database')
|
|
134
|
+
self._record_queue_metrics(recorder)
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
101
137
|
|
|
102
138
|
# If queue reaches the batch threshold, wake the worker to flush.
|
|
103
139
|
if self._queue.qsize() >= self.DRF_LOGGER_QUEUE_MAX_SIZE:
|
|
@@ -137,23 +173,40 @@ class InsertLogIntoDatabase(Thread):
|
|
|
137
173
|
Args:
|
|
138
174
|
bulk_item (list): A list of APILogsModel instances to insert.
|
|
139
175
|
|
|
140
|
-
|
|
141
|
-
|
|
176
|
+
Failed batches are counted and discarded, without retrying or stopping
|
|
177
|
+
the worker. Error reports omit database messages and log payloads.
|
|
142
178
|
"""
|
|
179
|
+
flush_start = time.perf_counter()
|
|
143
180
|
try:
|
|
181
|
+
# Background threads run outside Django's request connection cleanup.
|
|
182
|
+
close_old_connections()
|
|
144
183
|
APILogsModel.objects.using(self.DRF_API_LOGGER_DEFAULT_DATABASE).bulk_create(bulk_item)
|
|
145
184
|
self._increment_stat('_inserted_count', len(bulk_item))
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
185
|
+
try:
|
|
186
|
+
recorder = get_recorder()
|
|
187
|
+
recorder.increment_processed_logs('database', len(bulk_item))
|
|
188
|
+
recorder.observe_flush('database', time.perf_counter() - flush_start, len(bulk_item))
|
|
189
|
+
recorder.observe_storage_write('database', time.perf_counter() - flush_start)
|
|
190
|
+
self._record_queue_metrics(recorder)
|
|
191
|
+
except Exception:
|
|
192
|
+
pass
|
|
153
193
|
except Exception as e:
|
|
154
194
|
self._increment_stat('_failed_insert_count', len(bulk_item))
|
|
155
|
-
|
|
156
|
-
|
|
195
|
+
try:
|
|
196
|
+
recorder = get_recorder()
|
|
197
|
+
recorder.increment_storage_write_failure('database', e.__class__.__name__)
|
|
198
|
+
recorder.observe_storage_write('database', time.perf_counter() - flush_start)
|
|
199
|
+
self._record_queue_metrics(recorder)
|
|
200
|
+
except Exception:
|
|
201
|
+
pass
|
|
202
|
+
try:
|
|
203
|
+
logger.error(
|
|
204
|
+
'DRF API LOGGER: discarded %d log records after %s.',
|
|
205
|
+
len(bulk_item), e.__class__.__name__,
|
|
206
|
+
)
|
|
207
|
+
except Exception:
|
|
208
|
+
# An application logging handler must not terminate this worker.
|
|
209
|
+
pass
|
|
157
210
|
|
|
158
211
|
def _import_custom_handler(self, handler_path):
|
|
159
212
|
"""
|
|
@@ -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)
|