drf-api-logger 1.4.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.
Files changed (74) hide show
  1. {drf_api_logger-1.4.0/drf_api_logger.egg-info → drf_api_logger-1.4.1}/PKG-INFO +38 -6
  2. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/README.md +34 -3
  3. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/insert_log_into_database.py +17 -17
  4. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/utils.py +10 -2
  5. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1/drf_api_logger.egg-info}/PKG-INFO +38 -6
  6. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/SOURCES.txt +1 -0
  7. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/setup.py +4 -3
  8. drf_api_logger-1.4.1/tests/test_logging_regressions.py +341 -0
  9. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_signals.py +15 -8
  10. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/LICENSE +0 -0
  11. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/MANIFEST.in +0 -0
  12. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/__init__.py +0 -0
  13. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/admin.py +0 -0
  14. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/apps.py +0 -0
  15. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/collectstatic.py +0 -0
  16. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/correlation.py +0 -0
  17. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/diagnostics.py +0 -0
  18. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/events.py +0 -0
  19. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/logging_context.py +0 -0
  20. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/management/__init__.py +0 -0
  21. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/management/commands/__init__.py +0 -0
  22. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/management/commands/drf_api_logger_doctor.py +0 -0
  23. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/management/commands/prune_api_logs.py +0 -0
  24. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/__init__.py +0 -0
  25. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/labels.py +0 -0
  26. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/noop.py +0 -0
  27. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/prometheus.py +0 -0
  28. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/recorder.py +0 -0
  29. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/rules.py +0 -0
  30. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/security.py +0 -0
  31. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/settings.py +0 -0
  32. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/state.py +0 -0
  33. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/system_checks.py +0 -0
  34. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/urls.py +0 -0
  35. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/metrics/views.py +0 -0
  36. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/middleware/__init__.py +0 -0
  37. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/middleware/api_logger_middleware.py +0 -0
  38. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/0001_initial.py +0 -0
  39. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/0002_auto_20211221_2155.py +0 -0
  40. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/0003_apilogsmodel_profiling.py +0 -0
  41. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/migrations/__init__.py +0 -0
  42. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/models.py +0 -0
  43. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/observability.py +0 -0
  44. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/policy.py +0 -0
  45. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/static/drf_api_logger/css/Chart.min.css +0 -0
  46. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/static/drf_api_logger/js/Chart.bundle.min.js +0 -0
  47. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/templates/change_form.html +0 -0
  48. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/templates/charts_change_list.html +0 -0
  49. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger/tests.py +0 -0
  50. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/dependency_links.txt +0 -0
  51. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/requires.txt +0 -0
  52. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/drf_api_logger.egg-info/top_level.txt +0 -0
  53. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/llms.txt +0 -0
  54. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/pyproject.toml +0 -0
  55. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/setup.cfg +0 -0
  56. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_admin_charts.py +0 -0
  57. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_admin_templates.py +0 -0
  58. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_asgi_middleware.py +0 -0
  59. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_backward_compat.py +0 -0
  60. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_correlation.py +0 -0
  61. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_diagnostics.py +0 -0
  62. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_docs_content.py +0 -0
  63. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_integration.py +0 -0
  64. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_management_commands.py +0 -0
  65. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_media_url_issue.py +0 -0
  66. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_metrics.py +0 -0
  67. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_middleware.py +0 -0
  68. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_models.py +0 -0
  69. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_observability.py +0 -0
  70. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_policy.py +0 -0
  71. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_profiling.py +0 -0
  72. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_publish_workflow.py +0 -0
  73. {drf_api_logger-1.4.0 → drf_api_logger-1.4.1}/tests/test_settings.py +0 -0
  74. {drf_api_logger-1.4.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.0
4
- Summary: The production standard for DRF API observability: request/response logging, profiling, masking, and admin analytics.
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://github.com/vishalanandl177/DRF-API-Logger#readme
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
@@ -50,14 +51,14 @@ Dynamic: summary
50
51
 
51
52
  # DRF API Logger
52
53
 
53
- [![Version](https://img.shields.io/badge/version-1.4.0-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
54
+ [![Version](https://img.shields.io/badge/version-1.4.1-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
54
55
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
55
56
  [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
56
57
  [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
57
58
  [![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)
58
59
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
59
60
 
60
- **The production standard for DRF API observability.** Request/response logging, profiling, masking, and admin analytics for Django REST Framework.
61
+ **Request and response observability for Django REST Framework.** Configurable logging, profiling, masking, and admin analytics with production safety controls.
61
62
 
62
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.
63
64
 
@@ -124,6 +125,13 @@ DRF API Logger automatically captures and stores comprehensive API information:
124
125
 
125
126
  ### 🌐 Community & Support
126
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
+
127
135
  <p align="center">
128
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>
129
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>
@@ -309,6 +317,7 @@ API_LOGGER_SIGNAL.listen -= log_to_file
309
317
  - [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
310
318
  - [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
311
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.
312
321
  - [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
313
322
  - [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
314
323
 
@@ -330,6 +339,15 @@ DRF_LOGGER_INTERVAL = 10 # Default: 10 seconds
330
339
  database write. Request threads enqueue records and wake the background worker
331
340
  when this threshold is reached; they do not perform the bulk insert themselves.
332
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
+
333
351
  ### Selective Logging
334
352
 
335
353
  **Skip by Namespace:**
@@ -372,6 +390,20 @@ Default masking also covers common credential-bearing headers and keys such as
372
390
  `private_key`, `sessionid`, and `csrfmiddlewaretoken`. Matching is
373
391
  case-insensitive and treats hyphens and underscores equivalently.
374
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
+
375
407
  **Database Configuration:**
376
408
  ```python
377
409
  # Use specific database for logs
@@ -915,7 +947,7 @@ Use `drf-api-logger`. It automatically masks `password`, `token`, `access`, `ref
915
947
 
916
948
  **How to find slow APIs and N+1 queries in Django REST Framework?**
917
949
 
918
- Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it breaks down every request into middleware time, view time, and SQL time. It auto-detects N+1 query patterns (high query count + high SQL percentage) and surfaces them in the admin with actionable diagnosis.
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.
919
951
 
920
952
  **How to monitor Django REST API performance in production?**
921
953
 
@@ -1,13 +1,13 @@
1
1
  # DRF API Logger
2
2
 
3
- [![Version](https://img.shields.io/badge/version-1.4.0-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
3
+ [![Version](https://img.shields.io/badge/version-1.4.1-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
4
4
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
5
5
  [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
6
6
  [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
7
7
  [![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=total&left_color=black&right_color=orange&left_text=Downloads)](http://pepy.tech/project/drf-api-logger)
8
8
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
9
9
 
10
- **The production standard for DRF API observability.** Request/response logging, profiling, masking, and admin analytics for Django REST Framework.
10
+ **Request and response observability for Django REST Framework.** Configurable logging, profiling, masking, and admin analytics with production safety controls.
11
11
 
12
12
  Use `drf-api-logger` when you need to inspect DRF API calls without writing fragile custom middleware. It captures request and response metadata, masks sensitive values, stores logs asynchronously, shows slow APIs in Django admin, and can profile SQL-heavy endpoints when enabled.
13
13
 
@@ -74,6 +74,13 @@ DRF API Logger automatically captures and stores comprehensive API information:
74
74
 
75
75
  ### 🌐 Community & Support
76
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
+
77
84
  <p align="center">
78
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>
79
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>
@@ -259,6 +266,7 @@ API_LOGGER_SIGNAL.listen -= log_to_file
259
266
  - [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
260
267
  - [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
261
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.
262
270
  - [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
263
271
  - [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
264
272
 
@@ -280,6 +288,15 @@ DRF_LOGGER_INTERVAL = 10 # Default: 10 seconds
280
288
  database write. Request threads enqueue records and wake the background worker
281
289
  when this threshold is reached; they do not perform the bulk insert themselves.
282
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
+
283
300
  ### Selective Logging
284
301
 
285
302
  **Skip by Namespace:**
@@ -322,6 +339,20 @@ Default masking also covers common credential-bearing headers and keys such as
322
339
  `private_key`, `sessionid`, and `csrfmiddlewaretoken`. Matching is
323
340
  case-insensitive and treats hyphens and underscores equivalently.
324
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
+
325
356
  **Database Configuration:**
326
357
  ```python
327
358
  # Use specific database for logs
@@ -865,7 +896,7 @@ Use `drf-api-logger`. It automatically masks `password`, `token`, `access`, `ref
865
896
 
866
897
  **How to find slow APIs and N+1 queries in Django REST Framework?**
867
898
 
868
- Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it breaks down every request into middleware time, view time, and SQL time. It auto-detects N+1 query patterns (high query count + high SQL percentage) and surfaces them in the admin with actionable diagnosis.
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.
869
900
 
870
901
  **How to monitor Django REST API performance in production?**
871
902
 
@@ -1,15 +1,19 @@
1
1
  import atexit
2
+ import logging
2
3
  import signal
3
4
  import time
4
5
  from queue import Empty, Queue
5
6
  from importlib import import_module
6
7
  from django.conf import settings
7
8
  from threading import Thread, Event, Lock
8
- from django.db.utils import OperationalError
9
+ from django.db import close_old_connections
9
10
  from drf_api_logger.metrics.recorder import get_recorder
10
11
  from drf_api_logger.models import APILogsModel
11
12
 
12
13
 
14
+ logger = logging.getLogger(__name__)
15
+
16
+
13
17
  class InsertLogIntoDatabase(Thread):
14
18
  """
15
19
  A background thread that handles asynchronous, batched insertion of API log data
@@ -169,11 +173,13 @@ class InsertLogIntoDatabase(Thread):
169
173
  Args:
170
174
  bulk_item (list): A list of APILogsModel instances to insert.
171
175
 
172
- Raises:
173
- Exception: If the model doesn't exist or another database error occurs.
176
+ Failed batches are counted and discarded, without retrying or stopping
177
+ the worker. Error reports omit database messages and log payloads.
174
178
  """
175
179
  flush_start = time.perf_counter()
176
180
  try:
181
+ # Background threads run outside Django's request connection cleanup.
182
+ close_old_connections()
177
183
  APILogsModel.objects.using(self.DRF_API_LOGGER_DEFAULT_DATABASE).bulk_create(bulk_item)
178
184
  self._increment_stat('_inserted_count', len(bulk_item))
179
185
  try:
@@ -184,29 +190,23 @@ class InsertLogIntoDatabase(Thread):
184
190
  self._record_queue_metrics(recorder)
185
191
  except Exception:
186
192
  pass
187
- except OperationalError:
193
+ except Exception as e:
188
194
  self._increment_stat('_failed_insert_count', len(bulk_item))
189
195
  try:
190
196
  recorder = get_recorder()
191
- recorder.increment_storage_write_failure('database', 'OperationalError')
197
+ recorder.increment_storage_write_failure('database', e.__class__.__name__)
192
198
  recorder.observe_storage_write('database', time.perf_counter() - flush_start)
199
+ self._record_queue_metrics(recorder)
193
200
  except Exception:
194
201
  pass
195
- raise Exception("""
196
- DRF API LOGGER EXCEPTION
197
- Model does not exist.
198
- Did you forget to migrate?
199
- """)
200
- except Exception as e:
201
- self._increment_stat('_failed_insert_count', len(bulk_item))
202
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)
203
+ logger.error(
204
+ 'DRF API LOGGER: discarded %d log records after %s.',
205
+ len(bulk_item), e.__class__.__name__,
206
+ )
206
207
  except Exception:
208
+ # An application logging handler must not terminate this worker.
207
209
  pass
208
- # Logs other unexpected exceptions to the console
209
- print('DRF API LOGGER EXCEPTION:', e)
210
210
 
211
211
  def _import_custom_handler(self, handler_path):
212
212
  """
@@ -1,4 +1,5 @@
1
1
  import re
2
+ from urllib.parse import unquote_plus
2
3
  from django.conf import settings
3
4
 
4
5
  # Default list of sensitive keys to filter from logs or API data.
@@ -44,7 +45,13 @@ def _get_sensitive_keys(extra_sensitive_keys=None):
44
45
 
45
46
 
46
47
  def _is_sensitive_key(key, extra_sensitive_keys=None):
47
- return _normalize_sensitive_key(key) in _get_sensitive_keys(extra_sensitive_keys)
48
+ """Match exact keys or compound names ending in a delimited sensitive key."""
49
+ normalized = _normalize_sensitive_key(key)
50
+ sensitive_keys = _get_sensitive_keys(extra_sensitive_keys)
51
+ return normalized in sensitive_keys or any(
52
+ sensitive_key and normalized.endswith('_' + sensitive_key)
53
+ for sensitive_key in sensitive_keys
54
+ )
48
55
 
49
56
 
50
57
  def get_headers(request=None):
@@ -162,7 +169,8 @@ def mask_sensitive_data(data, mask_api_parameters=False, extra_sensitive_keys=No
162
169
  if mask_api_parameters and type(data) is str:
163
170
  def replace_param(match):
164
171
  separator, key, value = match.groups()
165
- if _is_sensitive_key(key, extra_sensitive_keys):
172
+ # Decode names once for matching, without rewriting the URL.
173
+ if _is_sensitive_key(unquote_plus(key), extra_sensitive_keys):
166
174
  return '{}{}={}'.format(separator, key, FILTERED_VALUE)
167
175
  return '{}{}={}'.format(separator, key, value)
168
176
 
@@ -1,12 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: drf-api-logger
3
- Version: 1.4.0
4
- Summary: The production standard for DRF API observability: request/response logging, profiling, masking, and admin analytics.
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://github.com/vishalanandl177/DRF-API-Logger#readme
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
@@ -50,14 +51,14 @@ Dynamic: summary
50
51
 
51
52
  # DRF API Logger
52
53
 
53
- [![Version](https://img.shields.io/badge/version-1.4.0-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
54
+ [![Version](https://img.shields.io/badge/version-1.4.1-blue.svg)](https://github.com/vishalanandl177/DRF-API-Logger)
54
55
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
55
56
  [![Django](https://img.shields.io/badge/django-4.2%2B-green.svg)](https://djangoproject.com)
56
57
  [![DRF](https://img.shields.io/badge/djangorestframework-3.16%2B-orange.svg)](https://www.django-rest-framework.org)
57
58
  [![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)
58
59
  [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg)](https://opensource.org/licenses/Apache-2.0)
59
60
 
60
- **The production standard for DRF API observability.** Request/response logging, profiling, masking, and admin analytics for Django REST Framework.
61
+ **Request and response observability for Django REST Framework.** Configurable logging, profiling, masking, and admin analytics with production safety controls.
61
62
 
62
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.
63
64
 
@@ -124,6 +125,13 @@ DRF API Logger automatically captures and stores comprehensive API information:
124
125
 
125
126
  ### 🌐 Community & Support
126
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
+
127
135
  <p align="center">
128
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>
129
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>
@@ -309,6 +317,7 @@ API_LOGGER_SIGNAL.listen -= log_to_file
309
317
  - [AI assistant guidance](docs/ai_readiness.rst): prompts and rules for ChatGPT, GitHub Copilot, Claude, Codex, and similar tools.
310
318
  - [Comparison and migration guide](docs/comparison_and_migration.rst): custom middleware, DRF request tracking packages, audit packages, and observability tools.
311
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.
312
321
  - [Operations guide](docs/operations.rst): retention jobs, queue health, database growth, and indexes.
313
322
  - [Compliance readiness](docs/compliance.rst): data minimization, masking, retention, and deployment controls.
314
323
 
@@ -330,6 +339,15 @@ DRF_LOGGER_INTERVAL = 10 # Default: 10 seconds
330
339
  database write. Request threads enqueue records and wake the background worker
331
340
  when this threshold is reached; they do not perform the bulk insert themselves.
332
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
+
333
351
  ### Selective Logging
334
352
 
335
353
  **Skip by Namespace:**
@@ -372,6 +390,20 @@ Default masking also covers common credential-bearing headers and keys such as
372
390
  `private_key`, `sessionid`, and `csrfmiddlewaretoken`. Matching is
373
391
  case-insensitive and treats hyphens and underscores equivalently.
374
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
+
375
407
  **Database Configuration:**
376
408
  ```python
377
409
  # Use specific database for logs
@@ -915,7 +947,7 @@ Use `drf-api-logger`. It automatically masks `password`, `token`, `access`, `ref
915
947
 
916
948
  **How to find slow APIs and N+1 queries in Django REST Framework?**
917
949
 
918
- Use `drf-api-logger` with profiling enabled. Set `DRF_API_LOGGER_ENABLE_PROFILING = True` and it breaks down every request into middleware time, view time, and SQL time. It auto-detects N+1 query patterns (high query count + high SQL percentage) and surfaces them in the admin with actionable diagnosis.
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.
919
951
 
920
952
  **How to monitor Django REST API performance in production?**
921
953
 
@@ -58,6 +58,7 @@ tests/test_correlation.py
58
58
  tests/test_diagnostics.py
59
59
  tests/test_docs_content.py
60
60
  tests/test_integration.py
61
+ tests/test_logging_regressions.py
61
62
  tests/test_management_commands.py
62
63
  tests/test_media_url_issue.py
63
64
  tests/test_metrics.py
@@ -11,10 +11,10 @@ def get_long_desc():
11
11
 
12
12
  setuptools.setup(
13
13
  name="drf-api-logger",
14
- version="1.4.0",
14
+ version="1.4.1",
15
15
  author="Vishal Anand",
16
16
  author_email="vishalanandl177@gmail.com",
17
- description="The production standard for DRF API observability: request/response logging, profiling, masking, and admin analytics.",
17
+ description="Request and response observability for Django REST Framework: logging, profiling, masking, and admin analytics.",
18
18
  long_description=get_long_desc(),
19
19
  long_description_content_type="text/markdown",
20
20
  url="https://github.com/vishalanandl177/DRF-API-Logger",
@@ -30,7 +30,8 @@ setuptools.setup(
30
30
  license="Apache-2.0",
31
31
  python_requires='>=3.10',
32
32
  project_urls={
33
- "Documentation": "https://github.com/vishalanandl177/DRF-API-Logger#readme",
33
+ "Documentation": "https://drf-api-logger.readthedocs.io/en/latest/",
34
+ "Maintainer Tutorial": "https://coderssecret.com/blog/drf-api-logger-django-rest-framework",
34
35
  "Operations Guide": "https://github.com/vishalanandl177/DRF-API-Logger/blob/main/docs/operations.rst",
35
36
  "AI Guidance": "https://github.com/vishalanandl177/DRF-API-Logger/blob/main/llms.txt",
36
37
  "Source": "https://github.com/vishalanandl177/DRF-API-Logger",
@@ -0,0 +1,341 @@
1
+ """Regression coverage for credential leakage (#133) and worker failure (#135)."""
2
+
3
+ import atexit
4
+ import json
5
+ import signal
6
+ import threading
7
+ from unittest.mock import Mock, patch
8
+
9
+ from django.db import DatabaseError, IntegrityError, OperationalError
10
+ from django.http import JsonResponse
11
+ from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings
12
+
13
+ from drf_api_logger import API_LOGGER_SIGNAL
14
+ from drf_api_logger.insert_log_into_database import InsertLogIntoDatabase
15
+ from drf_api_logger.middleware.api_logger_middleware import APILoggerMiddleware
16
+ from drf_api_logger.models import APILogsModel
17
+ from drf_api_logger.utils import FILTERED_VALUE, mask_sensitive_data
18
+
19
+
20
+ def transform_log(data):
21
+ return {**data, 'api': '/transformed/'}
22
+
23
+
24
+ class CredentialMaskingTests(SimpleTestCase):
25
+ def test_compound_credentials_and_nested_values(self):
26
+ keys = (
27
+ 'access_token', 'refresh_token', 'id_token', 'auth_token',
28
+ 'user_password', 'X-Auth-Token', 'CLIENT-SECRET', ' tenant_api_key ',
29
+ )
30
+ data = {'nested': [{key: 'credential-canary' for key in keys}]}
31
+ result = mask_sensitive_data(data)
32
+ self.assertEqual(result['nested'][0], dict.fromkeys(keys, FILTERED_VALUE))
33
+ self.assertIn('credential-canary', str(data))
34
+
35
+ @override_settings(DRF_API_LOGGER_EXCLUDE_KEYS=['key', 'account_id', ''])
36
+ def test_custom_and_policy_keys_respect_boundaries(self):
37
+ data = {
38
+ 'key': 'secret', 'tenant-key': 'secret', 'tenant_account_id': 'secret',
39
+ 'user_session': 'secret', 'monkey': 'visible', 'token_type': 'Bearer',
40
+ 'accessibility': 'visible', 'session_count': 3, 'safe_': 'visible',
41
+ }
42
+ result = mask_sensitive_data(data, extra_sensitive_keys=('session', ''))
43
+ for key in ('key', 'tenant-key', 'tenant_account_id', 'user_session'):
44
+ self.assertEqual(result[key], FILTERED_VALUE, key)
45
+ for key in ('monkey', 'token_type', 'accessibility', 'session_count', 'safe_'):
46
+ self.assertEqual(result[key], data[key], key)
47
+ self.assertEqual(mask_sensitive_data({'user_session': 'visible'}),
48
+ {'user_session': 'visible'})
49
+
50
+ def test_encoded_duplicate_and_empty_query_values_preserve_url(self):
51
+ url = (
52
+ 'https://example.invalid/callback?access_%74oken=first'
53
+ '&ACCESS%2DTOKEN=second&refresh_token=&%70assword=third'
54
+ '&state=a%2Bb+c&flag&token_type=Bearer#section'
55
+ )
56
+ expected = (
57
+ 'https://example.invalid/callback?access_%74oken=***FILTERED***'
58
+ '&ACCESS%2DTOKEN=***FILTERED***&refresh_token=***FILTERED***'
59
+ '&%70assword=***FILTERED***&state=a%2Bb+c&flag&token_type=Bearer#section'
60
+ )
61
+ self.assertEqual(mask_sensitive_data(url, mask_api_parameters=True), expected)
62
+
63
+ def test_query_names_are_decoded_once_only(self):
64
+ query = 'access_%2574oken=visible&user+key=secret&bad%ZZ=value'
65
+ self.assertEqual(
66
+ mask_sensitive_data(query, mask_api_parameters=True,
67
+ extra_sensitive_keys=['user key']),
68
+ 'access_%2574oken=visible&user+key=***FILTERED***&bad%ZZ=value',
69
+ )
70
+ # Percent encoding is a URL convention, not a JSON/header key convention.
71
+ self.assertEqual(mask_sensitive_data({'access_%74oken': 'visible'}),
72
+ {'access_%74oken': 'visible'})
73
+
74
+
75
+ @override_settings(DRF_API_LOGGER_DATABASE=True, DRF_API_LOGGER_SIGNAL=True)
76
+ class MiddlewareCredentialTests(TestCase):
77
+ @patch('drf_api_logger.middleware.api_logger_middleware.resolve')
78
+ @patch('drf_api_logger.apps.LOGGER_THREAD')
79
+ def test_credentials_are_masked_before_signal_and_persistence(self, queue, resolve):
80
+ resolve.return_value.namespace = None
81
+ resolve.return_value.app_name = None
82
+ resolve.return_value.url_name = 'credential_probe'
83
+ resolve.return_value.route = 'api/probe/'
84
+ events = []
85
+
86
+ def listener(**data):
87
+ events.append(data)
88
+
89
+ def response(request):
90
+ return JsonResponse({'nested': [{'id_token': 'response-canary'}]})
91
+
92
+ resolve.return_value.func = response
93
+ API_LOGGER_SIGNAL.listen += listener
94
+
95
+ def remove_listener():
96
+ API_LOGGER_SIGNAL.listen -= listener
97
+
98
+ self.addCleanup(remove_listener)
99
+ for path_type in ('ABSOLUTE', 'FULL_PATH', 'RAW_URI'):
100
+ with self.subTest(path_type=path_type), override_settings(
101
+ DRF_API_LOGGER_PATH_TYPE=path_type,
102
+ DRF_API_LOGGER_POLICY={'rules': [
103
+ {'url_name': 'credential_probe', 'mask_keys': ['account_id']},
104
+ ]},
105
+ ):
106
+ request = RequestFactory().post(
107
+ '/api/probe/?access_%74oken=url-canary&state=visible',
108
+ data=json.dumps({'nested': [{'refresh_token': 'body-canary'}],
109
+ 'tenant_account_id': 'policy-canary'}),
110
+ content_type='application/json',
111
+ HTTP_X_AUTH_TOKEN='header-canary',
112
+ )
113
+ result = APILoggerMiddleware(response)(request)
114
+ self.assertEqual(result.status_code, 200)
115
+ self.assertIn('response-canary', result.content.decode())
116
+ self.assertEqual(events[-1]['body']['tenant_account_id'], FILTERED_VALUE)
117
+ payload = queue.put_log_data.call_args.kwargs['data']
118
+ row = APILogsModel.objects.create(**payload)
119
+ row.refresh_from_db()
120
+ for key in ('api', 'headers', 'body', 'response'):
121
+ self.assertNotIn('-canary', str(events[-1][key]), key)
122
+ self.assertNotIn('-canary', getattr(row, key), key)
123
+ self.assertIn(FILTERED_VALUE, getattr(row, key), key)
124
+ self.assertIn('state=visible', row.api)
125
+
126
+ @patch('drf_api_logger.apps.LOGGER_THREAD')
127
+ async def test_async_middleware_masks_credentials_in_both_outputs(self, queue):
128
+ events = []
129
+
130
+ def listener(**data):
131
+ events.append(data)
132
+
133
+ async def response(request):
134
+ return JsonResponse({'id_token': 'response-canary'})
135
+
136
+ API_LOGGER_SIGNAL.listen += listener
137
+ try:
138
+ request = RequestFactory().post(
139
+ '/api/test/?refresh_%74oken=url-canary',
140
+ data=json.dumps({'access_token': 'body-canary'}),
141
+ content_type='application/json', HTTP_X_AUTH_TOKEN='header-canary',
142
+ )
143
+ result = await APILoggerMiddleware(response)(request)
144
+ finally:
145
+ API_LOGGER_SIGNAL.listen -= listener
146
+ self.assertEqual(result.status_code, 200)
147
+ self.assertEqual(len(events), 1)
148
+ payload = queue.put_log_data.call_args.kwargs['data']
149
+ for key in ('api', 'headers', 'body', 'response'):
150
+ self.assertNotIn('-canary', str(events[0][key]))
151
+ self.assertNotIn('-canary', payload[key])
152
+ self.assertIn(FILTERED_VALUE, payload[key])
153
+
154
+
155
+ class WorkerRecoveryTests(SimpleTestCase):
156
+ def setUp(self):
157
+ # These tests own their workers and never replace process signal handlers.
158
+ self.signal_patch = patch('drf_api_logger.insert_log_into_database.signal.signal')
159
+ self.signal_patch.start()
160
+ self.addCleanup(self.signal_patch.stop)
161
+ self.recorder = Mock()
162
+ recorder_patch = patch('drf_api_logger.insert_log_into_database.get_recorder',
163
+ return_value=self.recorder)
164
+ recorder_patch.start()
165
+ self.addCleanup(recorder_patch.stop)
166
+ cleanup_patch = patch('drf_api_logger.insert_log_into_database.close_old_connections')
167
+ self.close_old_connections = cleanup_patch.start()
168
+ self.addCleanup(cleanup_patch.stop)
169
+
170
+ @override_settings(DRF_LOGGER_QUEUE_MAX_SIZE=1,
171
+ DRF_API_LOGGER_DEFAULT_DATABASE='logs_db')
172
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
173
+ def test_real_worker_recovers_after_repeated_database_errors(self, model):
174
+ worker = InsertLogIntoDatabase()
175
+ worker.daemon = True
176
+ completed = threading.Event()
177
+ crashes = []
178
+ original_increment = worker._increment_stat
179
+
180
+ def increment(name, amount=1):
181
+ original_increment(name, amount)
182
+ if name == '_inserted_count':
183
+ completed.set()
184
+
185
+ model.objects.using.return_value.bulk_create.side_effect = [
186
+ OperationalError('private-canary'), DatabaseError('private-canary'), None,
187
+ ]
188
+ # Synchronize after the success counter changes, not inside bulk_create.
189
+ with patch.object(worker, '_increment_stat', side_effect=increment), \
190
+ patch('threading.excepthook', side_effect=crashes.append), \
191
+ self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR') as logs:
192
+ worker.start()
193
+ try:
194
+ for _ in range(3):
195
+ worker.put_log_data({'api': '/probe/'})
196
+ self.assertTrue(completed.wait(3), 'Worker failed to process a later batch')
197
+ self.assertTrue(worker.is_alive())
198
+ self.assertEqual(worker.get_status()['failed_insert_count'], 2)
199
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
200
+ self.assertEqual(worker.get_status()['queue_backlog'], 0)
201
+ finally:
202
+ worker.shutdown()
203
+ worker.join(3)
204
+ atexit.unregister(worker.shutdown)
205
+ self.assertFalse(worker.is_alive())
206
+ self.assertEqual(crashes, [], 'Uncaught worker exceptions must fail the test')
207
+ model.objects.using.assert_called_with('logs_db')
208
+ self.assertEqual(model.objects.using.return_value.bulk_create.call_count, 3)
209
+ self.assertNotIn('private-canary', str(logs.output))
210
+ self.recorder.increment_storage_write_failure.assert_any_call('database', 'OperationalError')
211
+ self.recorder.increment_storage_write_failure.assert_any_call('database', 'DatabaseError')
212
+
213
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
214
+ def test_failure_reporting_never_exposes_database_details(self, model):
215
+ for error_type in (OperationalError, IntegrityError, ValueError):
216
+ with self.subTest(error_type=error_type):
217
+ worker = InsertLogIntoDatabase()
218
+ model.objects.using.return_value.bulk_create.side_effect = error_type(
219
+ 'INSERT private-canary\npassword=secret'
220
+ )
221
+ with self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR') as logs:
222
+ worker._insert_into_data_base([Mock(), Mock()])
223
+ self.assertEqual(worker.get_status()['failed_insert_count'], 2)
224
+ self.assertIn(error_type.__name__, logs.output[0])
225
+ self.assertIn('2', logs.output[0])
226
+ self.assertNotIn('private-canary', str(logs.output))
227
+ self.assertIsNone(logs.records[0].exc_info)
228
+
229
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
230
+ def test_shutdown_discards_failed_batch_and_flushes_next(self, model):
231
+ with override_settings(DRF_LOGGER_QUEUE_MAX_SIZE=1):
232
+ worker = InsertLogIntoDatabase()
233
+ model.objects.using.return_value.bulk_create.side_effect = [OperationalError(), None]
234
+ worker.put_log_data({'api': '/failed/'})
235
+ worker.put_log_data({'api': '/success/'})
236
+ with self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR'):
237
+ worker.shutdown()
238
+ self.assertEqual(worker.get_status()['failed_insert_count'], 1)
239
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
240
+ self.assertEqual(worker.get_status()['queue_backlog'], 0)
241
+ self.assertTrue(worker._stop_event.is_set())
242
+
243
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
244
+ def test_bad_metrics_do_not_prevent_failure_handling(self, model):
245
+ self.recorder.increment_storage_write_failure.side_effect = RuntimeError('metrics down')
246
+ model.objects.using.return_value.bulk_create.side_effect = OperationalError()
247
+ worker = InsertLogIntoDatabase()
248
+ with self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR'):
249
+ worker._insert_into_data_base([Mock()])
250
+ self.assertEqual(worker.get_status()['failed_insert_count'], 1)
251
+
252
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
253
+ def test_connection_cleanup_precedes_each_write_and_recovers_from_failure(self, model):
254
+ operations = []
255
+
256
+ def cleanup():
257
+ operations.append('cleanup')
258
+ if len(operations) == 1:
259
+ raise OperationalError('connection-canary')
260
+
261
+ self.close_old_connections.side_effect = cleanup
262
+ model.objects.using.return_value.bulk_create.side_effect = lambda batch: operations.append('write')
263
+ worker = InsertLogIntoDatabase()
264
+ with self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR'):
265
+ worker._insert_into_data_base([Mock()])
266
+ worker._insert_into_data_base([Mock()])
267
+ self.assertEqual(operations, ['cleanup', 'cleanup', 'write'])
268
+ self.assertEqual(worker.get_status()['failed_insert_count'], 1)
269
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
270
+
271
+ @patch('drf_api_logger.insert_log_into_database.logger')
272
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
273
+ def test_broken_log_handler_does_not_stop_later_inserts(self, model, logger):
274
+ logger.error.side_effect = RuntimeError('handler unavailable')
275
+ model.objects.using.return_value.bulk_create.side_effect = [OperationalError(), None]
276
+ worker = InsertLogIntoDatabase()
277
+ worker._insert_into_data_base([Mock()])
278
+ worker._insert_into_data_base([Mock()])
279
+ self.assertEqual(worker.get_status()['failed_insert_count'], 1)
280
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
281
+
282
+ @override_settings(DRF_API_LOGGER_CUSTOM_HANDLER='tests.test_logging_regressions.transform_log')
283
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
284
+ def test_configured_custom_handler_transforms_before_queueing(self, model):
285
+ worker = InsertLogIntoDatabase()
286
+ original = {'api': '/original/'}
287
+ worker.put_log_data(original)
288
+ model.assert_called_once_with(api='/transformed/')
289
+ self.assertEqual(original['api'], '/original/')
290
+ self.assertEqual(worker.get_status()['queue_backlog'], 1)
291
+
292
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
293
+ def test_unavailable_metrics_do_not_stop_enqueue_drop_insert_or_shutdown(self, model):
294
+ with patch('drf_api_logger.insert_log_into_database.get_recorder',
295
+ side_effect=RuntimeError('metrics unavailable')):
296
+ worker = InsertLogIntoDatabase()
297
+ worker.put_log_data({'api': '/kept/'})
298
+ worker.custom_handler = lambda data: None
299
+ worker.put_log_data({'api': '/dropped/'})
300
+ worker.shutdown()
301
+ self.assertEqual(worker.get_status()['dropped_count'], 1)
302
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
303
+ self.assertEqual(worker.get_status()['failed_insert_count'], 0)
304
+ self.assertEqual(worker.get_status()['queue_backlog'], 0)
305
+
306
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
307
+ def test_invalid_record_is_dropped_even_if_metrics_fail(self, model):
308
+ for metrics_fail in (False, True):
309
+ with self.subTest(metrics_fail=metrics_fail), patch('builtins.print'):
310
+ worker = InsertLogIntoDatabase()
311
+ model.side_effect = TypeError('invalid field')
312
+ self.recorder.increment_dropped_logs.side_effect = (
313
+ RuntimeError('metrics unavailable') if metrics_fail else None
314
+ )
315
+ worker.put_log_data({'unknown_field': 'invalid'})
316
+ self.assertEqual(worker.get_status()['dropped_count'], 1)
317
+ self.assertEqual(worker.get_status()['queue_backlog'], 0)
318
+
319
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
320
+ def test_worker_start_metrics_failure_does_not_prevent_flush(self, model):
321
+ worker = InsertLogIntoDatabase()
322
+ worker.put_log_data({'api': '/probe/'})
323
+ self.recorder.increment_worker_restart.side_effect = RuntimeError('metrics unavailable')
324
+ # Stop at the first wait so this exercises run() without waiting for time.
325
+ worker._flush_event.wait = Mock(side_effect=lambda timeout: worker._stop_event.set())
326
+ try:
327
+ worker.run()
328
+ finally:
329
+ atexit.unregister(worker.shutdown)
330
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
331
+ self.assertEqual(worker.get_status()['queue_backlog'], 0)
332
+
333
+ @patch('drf_api_logger.insert_log_into_database.APILogsModel')
334
+ def test_termination_signal_flushes_and_exits_cleanly(self, model):
335
+ worker = InsertLogIntoDatabase()
336
+ worker.put_log_data({'api': '/probe/'})
337
+ with self.assertRaises(SystemExit) as result:
338
+ worker._clean_exit(signal.SIGTERM, None)
339
+ self.assertEqual(result.exception.code, 0)
340
+ self.assertTrue(worker._stop_event.is_set())
341
+ self.assertEqual(worker.get_status()['inserted_count'], 1)
@@ -108,7 +108,13 @@ class TestBackgroundThread(TestCase):
108
108
 
109
109
  def setUp(self):
110
110
  """Set up test fixtures"""
111
- pass
111
+ # These unit tests mock writes and must not close TestCase's transaction.
112
+ cleanup = patch('drf_api_logger.insert_log_into_database.close_old_connections')
113
+ cleanup.start()
114
+ self.addCleanup(cleanup.stop)
115
+ signals = patch('drf_api_logger.insert_log_into_database.signal.signal')
116
+ signals.start()
117
+ self.addCleanup(signals.stop)
112
118
 
113
119
  @patch('drf_api_logger.insert_log_into_database.APILogsModel')
114
120
  def test_insert_log_thread_creation(self, mock_model):
@@ -243,13 +249,13 @@ class TestBackgroundThread(TestCase):
243
249
  thread = InsertLogIntoDatabase()
244
250
  bulk_items = [Mock()]
245
251
 
246
- with self.assertRaises(Exception) as context:
252
+ with self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR') as logs:
247
253
  thread._insert_into_data_base(bulk_items)
248
- self.assertIn("Model does not exist", str(context.exception))
254
+ self.assertEqual(thread.get_status()['failed_insert_count'], 1)
255
+ self.assertIn('OperationalError', logs.output[0])
249
256
 
250
257
  @patch('drf_api_logger.insert_log_into_database.APILogsModel')
251
- @patch('builtins.print')
252
- def test_database_insertion_generic_error(self, mock_print, mock_model):
258
+ def test_database_insertion_generic_error(self, mock_model):
253
259
  """Test database insertion with generic error"""
254
260
  from drf_api_logger.insert_log_into_database import InsertLogIntoDatabase
255
261
 
@@ -260,9 +266,10 @@ class TestBackgroundThread(TestCase):
260
266
  thread = InsertLogIntoDatabase()
261
267
  bulk_items = [Mock()]
262
268
 
263
- # Should not raise, but should print error
264
- thread._insert_into_data_base(bulk_items)
265
- mock_print.assert_called_with('DRF API LOGGER EXCEPTION:', mock_manager.using.return_value.bulk_create.side_effect)
269
+ with self.assertLogs('drf_api_logger.insert_log_into_database', level='ERROR') as logs:
270
+ thread._insert_into_data_base(bulk_items)
271
+ self.assertIn('Exception', logs.output[0])
272
+ self.assertNotIn('Generic error', logs.output[0])
266
273
  self.assertEqual(thread.get_status()['failed_insert_count'], 1)
267
274
 
268
275
  @override_settings(DRF_API_LOGGER_DEFAULT_DATABASE='custom_db')
File without changes
File without changes
File without changes