base-api-utils 1.1.123__tar.gz → 1.1.125__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.
- {base_api_utils-1.1.123/src/base_api_utils.egg-info → base_api_utils-1.1.125}/PKG-INFO +29 -1
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/README.md +15 -1
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/pyproject.toml +21 -2
- base_api_utils-1.1.125/src/base_api_utils/log_handlers.py +22 -0
- base_api_utils-1.1.125/src/base_api_utils/log_redaction.py +279 -0
- base_api_utils-1.1.125/src/base_api_utils/logging_config.py +140 -0
- base_api_utils-1.1.125/src/base_api_utils/otel_celery.py +80 -0
- base_api_utils-1.1.125/src/base_api_utils/otel_instrumentation.py +437 -0
- base_api_utils-1.1.125/src/base_api_utils/otel_logging.py +264 -0
- base_api_utils-1.1.125/src/base_api_utils/tracing.py +65 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/__init__.py +7 -1
- base_api_utils-1.1.125/src/base_api_utils/utils/log_redaction.py +15 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125/src/base_api_utils.egg-info}/PKG-INFO +29 -1
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils.egg-info/SOURCES.txt +12 -0
- base_api_utils-1.1.125/src/base_api_utils.egg-info/requires.txt +31 -0
- base_api_utils-1.1.125/tests/test_log_redaction.py +691 -0
- base_api_utils-1.1.125/tests/test_logging_config.py +339 -0
- base_api_utils-1.1.125/tests/test_otel_celery.py +224 -0
- base_api_utils-1.1.125/tests/test_otel_instrumentation.py +634 -0
- base_api_utils-1.1.125/tests/test_otel_logging.py +507 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_retryable_event_propagation.py +1 -1
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_token_logging.py +1 -1
- base_api_utils-1.1.125/tests/test_tracing.py +134 -0
- base_api_utils-1.1.123/src/base_api_utils/utils/log_redaction.py +0 -112
- base_api_utils-1.1.123/src/base_api_utils.egg-info/requires.txt +0 -16
- base_api_utils-1.1.123/tests/test_log_redaction.py +0 -269
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/LICENSE +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/setup.cfg +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/commands/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/commands/failed_task_management_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/domain/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/domain/event_message.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/domain/event_message_factory.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/domain/events.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/domain/exceptions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/dtos/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/dtos/authz_user.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/fields/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/fields/email_list_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/filters/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/filters/base_filter.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/filters/custom_ordering_filter.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/filters/filter_utils_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/handlers/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/handlers/base_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/handlers/sponsor_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/handlers/sponsorship_addon_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/handlers/sponsorship_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/handlers/summit_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/ioc/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/ioc/container.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/models/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/models/item_image.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/abstract_access_token_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/abstract_oauth2_api_client.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/access_token_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/check_sponsor_user_permissions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/group_required.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/oauth2_authentication.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/oauth2_client_factory.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/oauth2_scope_required.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/permission_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/shared.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/security/user_permissions_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/base_model_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/email_list_char_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/nullable_slug_related_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/serializers_registry.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/task_result_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/timestamp_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/v2/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/v2/abstract_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/v2/base_model_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/v2/expands.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/v2/query_params.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/serializers/v2/spectacular.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/abstract_domain_events_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/abstract_event_dispatcher.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/abstract_images_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/abstract_sponsor_metadata_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/abstract_storage_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/abstract_summit_metadata_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/amqp_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/celery_failed.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/event_dispatcher.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/images_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/s3_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/strategies/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/strategies/abstract_task_runner_strategy.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/services/strategies/publish_domain_event_strategy.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/tests/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/tests/test_failed_celery_task_management.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/tests/test_task_status_endpoints.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/urls.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/admin_groups.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/async_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/circuit_breaker.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/config.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/custom_auto_schema.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/db_connection_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/debounce_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/enums.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/env_var_eval.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/exceptions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/expand_queryset_optimization_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/external_errors.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/file_lock.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/fingerprint_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/http_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/inject_job.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/look_up_value_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/model_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/oauth2_custom_schema_base.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/pagination.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/rate_utils.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/read_write_serializer_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/serializers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/service_utils.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/string.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/utils/tests.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/views/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/views/base_view.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/views/parent_children_crud.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/views/root_entity_crud.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils/views/tasks_result_view.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils.egg-info/dependency_links.txt +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/src/base_api_utils.egg-info/top_level.txt +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_amqp_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_check_sponsor_user_permissions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_circuit_breaker.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_db_connection_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_file_lock.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_is_admin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_lazy_imports.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_oauth2_scope_required.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_timestamp_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.125}/tests/test_v2_abstract_serializer.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: base-api-utils
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.125
|
|
4
4
|
Summary: Django Rest Framework micro services common utilities
|
|
5
5
|
Author-email: Román Gutierrez <roman@tipit.net>, Sebastian Marcet <sebastian@tipit.net>
|
|
6
6
|
Project-URL: Homepage, https://github.com/fntechgit/base-api-utils
|
|
@@ -22,8 +22,22 @@ Requires-Dist: pika
|
|
|
22
22
|
Requires-Dist: pybreaker
|
|
23
23
|
Requires-Dist: requests
|
|
24
24
|
Requires-Dist: requests-oauthlib
|
|
25
|
+
Provides-Extra: otel
|
|
26
|
+
Requires-Dist: opentelemetry-sdk>=1.38.0; extra == "otel"
|
|
27
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.38.0; extra == "otel"
|
|
28
|
+
Requires-Dist: opentelemetry-instrumentation-logging; extra == "otel"
|
|
29
|
+
Requires-Dist: opentelemetry-instrumentation-django; extra == "otel"
|
|
30
|
+
Requires-Dist: opentelemetry-instrumentation-mysqlclient; extra == "otel"
|
|
31
|
+
Requires-Dist: opentelemetry-instrumentation-redis; extra == "otel"
|
|
32
|
+
Requires-Dist: opentelemetry-instrumentation-requests; extra == "otel"
|
|
33
|
+
Requires-Dist: opentelemetry-instrumentation-celery; extra == "otel"
|
|
25
34
|
Provides-Extra: dev
|
|
26
35
|
Requires-Dist: pytest==9.0.2; extra == "dev"
|
|
36
|
+
Requires-Dist: opentelemetry-sdk==1.44.0; extra == "dev"
|
|
37
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http==1.44.0; extra == "dev"
|
|
38
|
+
Requires-Dist: opentelemetry-instrumentation-logging==0.65b0; extra == "dev"
|
|
39
|
+
Requires-Dist: opentelemetry-instrumentation-requests==0.65b0; extra == "dev"
|
|
40
|
+
Requires-Dist: opentelemetry-instrumentation-celery==0.65b0; extra == "dev"
|
|
27
41
|
Dynamic: license-file
|
|
28
42
|
|
|
29
43
|
# base-api-utils
|
|
@@ -109,3 +123,17 @@ pip install git+https://github.com/fntechgit/base-api-utils
|
|
|
109
123
|
For a deep dive into the technical implementation, CLI usage, and troubleshooting steps, please refer to the dedicated management guide:
|
|
110
124
|
|
|
111
125
|
**[Management & Recovery Deep Dive: /docs/celery-management.md](./docs/celery-management.md)**
|
|
126
|
+
|
|
127
|
+
# Logging and the OTLP log bridge
|
|
128
|
+
|
|
129
|
+
`base_api_utils.logging_config.build_logging` builds a service's `settings.LOGGING`, and
|
|
130
|
+
`base_api_utils.otel_logging.configure_otel_logging` ships its log records over OTLP:
|
|
131
|
+
|
|
132
|
+
**[Logging and the OTLP log bridge: /docs/logging.md](./docs/logging.md)**
|
|
133
|
+
|
|
134
|
+
# Traces
|
|
135
|
+
|
|
136
|
+
`base_api_utils.otel_instrumentation`, `base_api_utils.tracing` and `base_api_utils.otel_celery`
|
|
137
|
+
give a service its traces, a root span for jobs and consumers, and the Celery worker hooks:
|
|
138
|
+
|
|
139
|
+
**[Traces, root spans and the Celery worker hooks: /docs/tracing.md](./docs/tracing.md)**
|
|
@@ -80,4 +80,18 @@ pip install git+https://github.com/fntechgit/base-api-utils
|
|
|
80
80
|
|
|
81
81
|
For a deep dive into the technical implementation, CLI usage, and troubleshooting steps, please refer to the dedicated management guide:
|
|
82
82
|
|
|
83
|
-
**[Management & Recovery Deep Dive: /docs/celery-management.md](./docs/celery-management.md)**
|
|
83
|
+
**[Management & Recovery Deep Dive: /docs/celery-management.md](./docs/celery-management.md)**
|
|
84
|
+
|
|
85
|
+
# Logging and the OTLP log bridge
|
|
86
|
+
|
|
87
|
+
`base_api_utils.logging_config.build_logging` builds a service's `settings.LOGGING`, and
|
|
88
|
+
`base_api_utils.otel_logging.configure_otel_logging` ships its log records over OTLP:
|
|
89
|
+
|
|
90
|
+
**[Logging and the OTLP log bridge: /docs/logging.md](./docs/logging.md)**
|
|
91
|
+
|
|
92
|
+
# Traces
|
|
93
|
+
|
|
94
|
+
`base_api_utils.otel_instrumentation`, `base_api_utils.tracing` and `base_api_utils.otel_celery`
|
|
95
|
+
give a service its traces, a root span for jobs and consumers, and the Celery worker hooks:
|
|
96
|
+
|
|
97
|
+
**[Traces, root spans and the Celery worker hooks: /docs/tracing.md](./docs/tracing.md)**
|
|
@@ -7,7 +7,7 @@ where = ["src"]
|
|
|
7
7
|
|
|
8
8
|
[project]
|
|
9
9
|
name = "base-api-utils"
|
|
10
|
-
version = "1.1.
|
|
10
|
+
version = "1.1.125"
|
|
11
11
|
dependencies = [
|
|
12
12
|
"boto3",
|
|
13
13
|
"celery",
|
|
@@ -36,8 +36,27 @@ classifiers = [
|
|
|
36
36
|
]
|
|
37
37
|
|
|
38
38
|
[project.optional-dependencies]
|
|
39
|
+
# The OpenTelemetry scaffold (otel_logging, otel_instrumentation, tracing, otel_celery).
|
|
40
|
+
# A service pins its own SDK line.
|
|
41
|
+
otel = [
|
|
42
|
+
"opentelemetry-sdk>=1.38.0",
|
|
43
|
+
"opentelemetry-exporter-otlp-proto-http>=1.38.0",
|
|
44
|
+
"opentelemetry-instrumentation-logging",
|
|
45
|
+
"opentelemetry-instrumentation-django",
|
|
46
|
+
"opentelemetry-instrumentation-mysqlclient",
|
|
47
|
+
"opentelemetry-instrumentation-redis",
|
|
48
|
+
"opentelemetry-instrumentation-requests",
|
|
49
|
+
"opentelemetry-instrumentation-celery"
|
|
50
|
+
]
|
|
51
|
+
# The instrumentors of Django, mysqlclient and Redis are stubbed in the tests: each imports the
|
|
52
|
+
# library it instruments.
|
|
39
53
|
dev = [
|
|
40
|
-
"pytest==9.0.2"
|
|
54
|
+
"pytest==9.0.2",
|
|
55
|
+
"opentelemetry-sdk==1.44.0",
|
|
56
|
+
"opentelemetry-exporter-otlp-proto-http==1.44.0",
|
|
57
|
+
"opentelemetry-instrumentation-logging==0.65b0",
|
|
58
|
+
"opentelemetry-instrumentation-requests==0.65b0",
|
|
59
|
+
"opentelemetry-instrumentation-celery==0.65b0"
|
|
41
60
|
]
|
|
42
61
|
|
|
43
62
|
[project.urls]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""The local sinks ``logging_config.build_logging`` declares.
|
|
2
|
+
|
|
3
|
+
Each writes a redacted copy of the record, as the OTLP handler exports it: urllib3 logs the
|
|
4
|
+
introspection request line at DEBUG, and base_api_utils.security sends the token in its query
|
|
5
|
+
string.
|
|
6
|
+
|
|
7
|
+
dictConfig loads this module by its dotted path when Django configures logging, which is before it
|
|
8
|
+
loads the apps. So it imports nothing but the standard library and log_redaction, which does the
|
|
9
|
+
same: base_api_utils.utils imports Django REST framework's views, and those resolve the service's
|
|
10
|
+
default authentication classes, which may import a model.
|
|
11
|
+
"""
|
|
12
|
+
import logging
|
|
13
|
+
|
|
14
|
+
from base_api_utils.log_redaction import RedactingHandlerMixin
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RedactingStreamHandler(RedactingHandlerMixin, logging.StreamHandler):
|
|
18
|
+
"""The console sink."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RedactingFileHandler(RedactingHandlerMixin, logging.FileHandler):
|
|
22
|
+
"""The file sink."""
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Keep credentials out of log lines.
|
|
2
|
+
|
|
3
|
+
A log line may say which token a request carried, never the token itself: logs are read by
|
|
4
|
+
more people, and kept for longer, than a token is valid.
|
|
5
|
+
|
|
6
|
+
- ``token_fingerprint`` names a token so its lines can be told apart from another token's.
|
|
7
|
+
- ``describe_token_info`` says who a token belongs to, from an allow-list of fields.
|
|
8
|
+
- ``redact_secrets`` removes credentials from text built elsewhere, such as the message of a
|
|
9
|
+
``requests`` exception, which contains the URL and with it ``?access_token=``.
|
|
10
|
+
- ``redact_log_record`` and ``RedactingHandlerMixin`` apply ``redact_secrets`` to a whole log
|
|
11
|
+
record on its way to a handler that ships it off the process (the OTLP exporter), whoever
|
|
12
|
+
wrote the line: Django, urllib3 and requests_oauthlib log URLs and requests too.
|
|
13
|
+
|
|
14
|
+
``redact_secrets`` knows the shapes listed below and nothing else: of a credential that stands
|
|
15
|
+
alone in a sentence it finds only a long value after the word "token". Where the value is known,
|
|
16
|
+
log its fingerprint instead of passing the text through it. When in doubt it redacts: a hidden
|
|
17
|
+
word is the cheaper mistake.
|
|
18
|
+
|
|
19
|
+
This module imports nothing but the standard library: the logging handlers load it while Django
|
|
20
|
+
configures logging, before the app registry is ready, where ``base_api_utils.utils`` cannot be
|
|
21
|
+
imported. ``base_api_utils.utils.log_redaction``, its path until now, re-exports it.
|
|
22
|
+
"""
|
|
23
|
+
import copy
|
|
24
|
+
import hashlib
|
|
25
|
+
import logging
|
|
26
|
+
import re
|
|
27
|
+
|
|
28
|
+
REDACTED = '[REDACTED]'
|
|
29
|
+
|
|
30
|
+
_FINGERPRINT_LENGTH = 12
|
|
31
|
+
|
|
32
|
+
# A name is a credential's when it holds one of these words: access_token, client_secret,
|
|
33
|
+
# service_token, accessToken, api_key. The name is a whole word, taken in one piece: the second
|
|
34
|
+
# lookahead captures it and the back-reference repeats it, so a match that fails after the name
|
|
35
|
+
# does not try the name again one character shorter. On a long text that kept the time linear.
|
|
36
|
+
_CREDENTIAL_WORDS = r'(?:token|secret|password|passwd|api[_-]?key)'
|
|
37
|
+
_NAME = (rf'(?<![\w-])(?=[\w-]*?{_CREDENTIAL_WORDS})'
|
|
38
|
+
r'(?=(?P<word>[\w-]+))(?P=word)')
|
|
39
|
+
|
|
40
|
+
# name=value, name: value, "name": "value", 'name': b'value'. A quoted value ends at the quote
|
|
41
|
+
# it began with, whatever it holds; backslashes before a quote are JSON inside a JSON string.
|
|
42
|
+
# A value with no quotes ends at a space or at the next query-string parameter.
|
|
43
|
+
# Inside the quotes a backslash is read one way only, as the start of an escape: with two ways
|
|
44
|
+
# to read it, a quote that never closes made the pattern try every split of a run of backslashes.
|
|
45
|
+
# A quote that never closes takes the rest of its line. Giving up there and taking the first
|
|
46
|
+
# word instead left the rest of the value in the text, and read the line again, to its end, from
|
|
47
|
+
# every name on it: a request path of token=\'& repeated made one log call take seconds.
|
|
48
|
+
# A fingerprint is not a credential: token=sha256:2e6a931d428f, as describe_token_info writes it,
|
|
49
|
+
# is left as it is. Only when the fingerprint is the whole value: a value that begins like one
|
|
50
|
+
# and goes on is redacted.
|
|
51
|
+
_FINGERPRINT = rf'sha256:[0-9a-f]{{{_FINGERPRINT_LENGTH}}}'
|
|
52
|
+
_FINGERPRINT_VALUE = rf'''["']?{_FINGERPRINT}(?=[\s&,;"')}}\]]|$)'''
|
|
53
|
+
_ASSIGNMENT_RE = re.compile(
|
|
54
|
+
rf'''(?i)(?P<name>{_NAME})(?P<separator>\\*["']?\s*[=:]\s*)(?![=:])(?!{_FINGERPRINT_VALUE})'''
|
|
55
|
+
r'''(?:(?P<open>b?\\*(?P<quote>["']))(?:\\.|(?!(?P=quote))[^\\\n])*(?:(?P<close>(?P=quote))|[^\n]*)'''
|
|
56
|
+
r'''|[^\s&]+)'''
|
|
57
|
+
)
|
|
58
|
+
# name%3Dvalue: a URL carried inside another URL's parameter.
|
|
59
|
+
_ENCODED_ASSIGNMENT_RE = re.compile(rf'(?i)(?P<name>{_NAME})%3D(?:(?!%26)[^&\s])+')
|
|
60
|
+
# Authorization, as a header or a dict entry, up to its value. The spaces after the separator are
|
|
61
|
+
# read once: the second run belongs to an opening quote and is tried only when there is one.
|
|
62
|
+
# Two runs side by side made a long gap take quadratic time.
|
|
63
|
+
_AUTHORIZATION = r'''authorization\\*["']?\s*[:=]\s*(?:\\*["']\s*)?'''
|
|
64
|
+
# Authorization: Digest username="...", response="...": every parameter, to the end of the line.
|
|
65
|
+
_DIGEST_RE = re.compile(rf'(?i)\b({_AUTHORIZATION}digest\s+)[^\r\n]+')
|
|
66
|
+
# Authorization: Bearer <token>, Authorization: Basic <base64 of id:secret>.
|
|
67
|
+
_AUTHORIZATION_RE = re.compile(
|
|
68
|
+
rf'(?i)\b({_AUTHORIZATION}(?:(?:bearer|basic|negotiate|token)\s+)?)'
|
|
69
|
+
r'''(?!digest\s)[^\s"',;&]+'''
|
|
70
|
+
)
|
|
71
|
+
# Bearer <token> on its own. The length keeps "bearer header" in a sentence as it is.
|
|
72
|
+
_BEARER_RE = re.compile(r'(?i)\b(bearer\s+)[A-Za-z0-9\-._~+/]{12,}=*')
|
|
73
|
+
# "Access token <token> is expired!": a token named in a sentence, as OpenStackID writes it.
|
|
74
|
+
# The length keeps "token revoked" and a fingerprint (sha256:...) as they are.
|
|
75
|
+
_TOKEN_IN_A_SENTENCE_RE = re.compile(r'(?i)\b(token\s+)[A-Za-z0-9\-._~+/]{20,}=*')
|
|
76
|
+
# scheme://user:password@host. The user may be empty (redis://:password@host), and the password
|
|
77
|
+
# runs to the last @ before the path, because it may hold one.
|
|
78
|
+
_URL_PASSWORD_RE = re.compile(r'(?i)\b([a-z][a-z0-9+.-]{1,20}://[^/\s:@?#]*:)[^\s/?#]*(?=@)')
|
|
79
|
+
|
|
80
|
+
# The fields of a token_info that say who is calling. Anything else, the token and the user's
|
|
81
|
+
# name and email included, is left out.
|
|
82
|
+
_TOKEN_INFO_FIELDS = ('client_id', 'application_type', 'user_id', 'error_code')
|
|
83
|
+
# An OAuth2 error code (invalid_token, invalid_grant). Free text is not one.
|
|
84
|
+
_ERROR_CODE_RE = re.compile(r'[a-z_]{1,40}')
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def token_fingerprint(token) -> str:
|
|
88
|
+
"""A short name for ``token`` that cannot be turned back into it.
|
|
89
|
+
|
|
90
|
+
The first hex characters of its SHA-256, so every line about one token carries the same
|
|
91
|
+
value and lines about another token carry a different one.
|
|
92
|
+
"""
|
|
93
|
+
if not token:
|
|
94
|
+
return 'none'
|
|
95
|
+
raw = token if isinstance(token, bytes) else str(token).encode('utf-8')
|
|
96
|
+
return f'sha256:{hashlib.sha256(raw).hexdigest()[:_FINGERPRINT_LENGTH]}'
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _redact_assignment(match) -> str:
|
|
100
|
+
if match.group('quote'):
|
|
101
|
+
close = match.group('close') or ''
|
|
102
|
+
return f"{match.group('name')}{match.group('separator')}{match.group('open')}{REDACTED}{close}"
|
|
103
|
+
return f"{match.group('name')}{match.group('separator')}{REDACTED}"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def redact_secrets(value) -> str:
|
|
107
|
+
"""``str(value)`` with the credentials it can recognise replaced. Text with none is unchanged."""
|
|
108
|
+
text = str(value)
|
|
109
|
+
text = _DIGEST_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
110
|
+
text = _AUTHORIZATION_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
111
|
+
text = _ASSIGNMENT_RE.sub(_redact_assignment, text)
|
|
112
|
+
text = _ENCODED_ASSIGNMENT_RE.sub(lambda match: f"{match.group('name')}%3D{REDACTED}", text)
|
|
113
|
+
text = _BEARER_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
114
|
+
text = _TOKEN_IN_A_SENTENCE_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
115
|
+
return _URL_PASSWORD_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def describe_token_info(token_info) -> str:
|
|
119
|
+
"""What may be logged about a token_info: who is calling and the token's fingerprint.
|
|
120
|
+
|
|
121
|
+
For a refusal, its status and its error code. The IDP's description of a refusal is never
|
|
122
|
+
logged: OpenStackID writes the refused token into it.
|
|
123
|
+
"""
|
|
124
|
+
if not isinstance(token_info, dict):
|
|
125
|
+
return 'None' if token_info is None else f'<{type(token_info).__name__}>'
|
|
126
|
+
described = {name: token_info[name] for name in _TOKEN_INFO_FIELDS if name in token_info}
|
|
127
|
+
error = token_info.get('error')
|
|
128
|
+
if error:
|
|
129
|
+
described['error'] = error if isinstance(error, str) and _ERROR_CODE_RE.fullmatch(error) else REDACTED
|
|
130
|
+
if 'access_token' in token_info:
|
|
131
|
+
described['token'] = token_fingerprint(token_info['access_token'])
|
|
132
|
+
return ', '.join(f'{name}={value}' for name, value in described.items())
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# The attributes every LogRecord has. Any other attribute of a record was passed as ``extra`` or
|
|
136
|
+
# added by a record factory. A plain LogRecord is asked and not logging.makeLogRecord, which goes
|
|
137
|
+
# through the factory in place when this module is imported: what that factory adds would count
|
|
138
|
+
# as an attribute every record has, and would never be redacted.
|
|
139
|
+
_RECORD_ATTRIBUTES = frozenset(vars(logging.LogRecord('', 0, '', 0, '', (), None))) | {'message', 'asctime'}
|
|
140
|
+
_KEPT_AS_THEY_ARE = (bool, int, float, type(None))
|
|
141
|
+
# An exception chain is followed this far. A longer one is cut there, not read to its end.
|
|
142
|
+
_MAX_CHAIN_LINKS = 100
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _text(value, unprintable=None) -> str:
|
|
146
|
+
"""``str(value)``, or a note in its place when the value's own ``__str__`` raises.
|
|
147
|
+
|
|
148
|
+
Such a value costs its own text and not the record: the message and the stacktrace next to
|
|
149
|
+
it are still exported.
|
|
150
|
+
"""
|
|
151
|
+
try:
|
|
152
|
+
return str(value)
|
|
153
|
+
except Exception:
|
|
154
|
+
return unprintable or f'<{type(value).__name__}: str() failed>'
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# An ``extra`` with one of these in its name holds a credential, whatever its value looks like:
|
|
158
|
+
# the words that make a name a credential's in a text, and the Authorization header.
|
|
159
|
+
_CREDENTIAL_EXTRA_RE = re.compile(rf'(?i){_CREDENTIAL_WORDS}|authorization')
|
|
160
|
+
_FINGERPRINT_RE = re.compile(_FINGERPRINT)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _redact_extra(name, value):
|
|
164
|
+
if isinstance(value, _KEPT_AS_THEY_ARE):
|
|
165
|
+
return value
|
|
166
|
+
if _CREDENTIAL_EXTRA_RE.search(name):
|
|
167
|
+
# The name is what says it is a credential: a token on its own has no shape to find.
|
|
168
|
+
return value if isinstance(value, str) and _FINGERPRINT_RE.fullmatch(value) else REDACTED
|
|
169
|
+
if isinstance(value, (list, tuple)) and all(isinstance(item, (str, *_KEPT_AS_THEY_ARE)) for item in value):
|
|
170
|
+
# A plain tuple or list, never the value's own class: a named tuple takes one argument
|
|
171
|
+
# per field, and other subclasses are built from more than their items.
|
|
172
|
+
plain = tuple if isinstance(value, tuple) else list
|
|
173
|
+
return plain(item if isinstance(item, _KEPT_AS_THEY_ARE) else redact_secrets(_text(item)) for item in value)
|
|
174
|
+
return redact_secrets(_text(value))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _redacted_exception(exc, seen):
|
|
178
|
+
"""A stand-in for ``exc``: same type name, traceback and chain, every message redacted.
|
|
179
|
+
|
|
180
|
+
The chain is followed for ``_MAX_CHAIN_LINKS`` exceptions and cut there.
|
|
181
|
+
"""
|
|
182
|
+
if exc is None or id(exc) in seen or len(seen) >= _MAX_CHAIN_LINKS:
|
|
183
|
+
return None
|
|
184
|
+
seen.add(id(exc))
|
|
185
|
+
exc_class = type(exc)
|
|
186
|
+
stand_in_class = type(exc_class.__name__, (Exception,),
|
|
187
|
+
{'__module__': exc_class.__module__, '__qualname__': exc_class.__qualname__})
|
|
188
|
+
stand_in = stand_in_class(redact_secrets(_text(exc, '<exception str() failed>')))
|
|
189
|
+
stand_in.__traceback__ = exc.__traceback__
|
|
190
|
+
stand_in.__cause__ = _redacted_exception(exc.__cause__, seen)
|
|
191
|
+
stand_in.__context__ = _redacted_exception(exc.__context__, seen)
|
|
192
|
+
stand_in.__suppress_context__ = exc.__suppress_context__
|
|
193
|
+
return stand_in
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def redact_log_record(record: logging.LogRecord) -> logging.LogRecord:
|
|
197
|
+
"""A copy of ``record`` with the credentials removed from everything a handler can export.
|
|
198
|
+
|
|
199
|
+
The message is rendered with its arguments and redacted. Every ``extra`` that is not a
|
|
200
|
+
number, a bool or None is replaced by its redacted text, and a list or tuple of texts stays
|
|
201
|
+
one, as a plain list or tuple whatever its class: OpenTelemetry's LoggingHandler exports
|
|
202
|
+
every ``extra`` as an attribute, and from SDK 1.39 it exports an object such as the
|
|
203
|
+
``request`` Django passes on every 4xx and 5xx response as ``str(request)``, query string
|
|
204
|
+
included. An ``extra`` named after a credential (``access_token``, ``authorization``) is
|
|
205
|
+
replaced whole, unless it is a number, a bool, None or a fingerprint: a token on its own has
|
|
206
|
+
no shape to find. The exception keeps its type name, traceback and chain, with each message
|
|
207
|
+
redacted. A value whose ``__str__`` raises is replaced by a note that says so.
|
|
208
|
+
|
|
209
|
+
``record`` itself is left unchanged, so the other handlers still get the request object and
|
|
210
|
+
the original exception (Django's mail_admins handler reads ``request.META``).
|
|
211
|
+
"""
|
|
212
|
+
redacted = copy.copy(record)
|
|
213
|
+
try:
|
|
214
|
+
message = record.getMessage()
|
|
215
|
+
except Exception: # arguments that do not fit the message: logging reports it in emit()
|
|
216
|
+
message = _text(record.msg)
|
|
217
|
+
redacted.msg = redact_secrets(message)
|
|
218
|
+
redacted.args = None
|
|
219
|
+
if 'message' in vars(record):
|
|
220
|
+
redacted.message = redacted.msg
|
|
221
|
+
for name, value in vars(record).items():
|
|
222
|
+
if name not in _RECORD_ATTRIBUTES:
|
|
223
|
+
setattr(redacted, name, _redact_extra(name, value))
|
|
224
|
+
if record.exc_info and record.exc_info[1] is not None:
|
|
225
|
+
stand_in = _redacted_exception(record.exc_info[1], set())
|
|
226
|
+
redacted.exc_info = (type(stand_in), stand_in, record.exc_info[2])
|
|
227
|
+
if record.exc_text:
|
|
228
|
+
redacted.exc_text = redact_secrets(record.exc_text)
|
|
229
|
+
if record.stack_info:
|
|
230
|
+
redacted.stack_info = redact_secrets(record.stack_info)
|
|
231
|
+
return redacted
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _withheld(record: logging.LogRecord, error: Exception) -> logging.LogRecord:
|
|
235
|
+
"""What a handler gets in place of a record that could not be redacted.
|
|
236
|
+
|
|
237
|
+
It says where and when the record was written and names the type of the error. It holds
|
|
238
|
+
nothing of the record's message, arguments, extras or exception, and nothing of the error's
|
|
239
|
+
own message: any of them may be what holds the credential.
|
|
240
|
+
"""
|
|
241
|
+
withheld = logging.LogRecord(
|
|
242
|
+
record.name, record.levelno, record.pathname, record.lineno,
|
|
243
|
+
f'log record withheld: redaction failed ({type(error).__name__})', None, None, record.funcName)
|
|
244
|
+
withheld.created, withheld.msecs, withheld.relativeCreated = record.created, record.msecs, record.relativeCreated
|
|
245
|
+
return withheld
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class RedactingHandlerMixin:
|
|
249
|
+
"""Hands the handler a redacted copy of every record; see ``redact_log_record``.
|
|
250
|
+
|
|
251
|
+
Mix it in before the handler class::
|
|
252
|
+
|
|
253
|
+
class RedactingLoggingHandler(RedactingHandlerMixin, LoggingHandler):
|
|
254
|
+
pass
|
|
255
|
+
|
|
256
|
+
Written the other way round, the handler class would answer ``emit`` first and every record
|
|
257
|
+
would be exported as it was, so such a class is refused when it is defined.
|
|
258
|
+
|
|
259
|
+
The other handlers of the same logger keep receiving the original record.
|
|
260
|
+
|
|
261
|
+
A record that cannot be redacted is never handed on as it was, and the failure never leaves
|
|
262
|
+
the logging call: the handler gets a line that says a record was withheld.
|
|
263
|
+
"""
|
|
264
|
+
|
|
265
|
+
def __init_subclass__(cls, **kwargs):
|
|
266
|
+
super().__init_subclass__(**kwargs)
|
|
267
|
+
# The class whose emit() a record reaches first.
|
|
268
|
+
first = next(klass for klass in cls.__mro__ if 'emit' in vars(klass))
|
|
269
|
+
if not issubclass(first, RedactingHandlerMixin):
|
|
270
|
+
raise TypeError(
|
|
271
|
+
f'{cls.__name__}: RedactingHandlerMixin must come before {first.__name__} in its bases, '
|
|
272
|
+
'or records are exported without redaction')
|
|
273
|
+
|
|
274
|
+
def emit(self, record):
|
|
275
|
+
try:
|
|
276
|
+
redacted = redact_log_record(record)
|
|
277
|
+
except Exception as error:
|
|
278
|
+
redacted = _withheld(record, error)
|
|
279
|
+
super().emit(redacted)
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""The LOGGING dict of an FN service, built in one place.
|
|
2
|
+
|
|
3
|
+
# settings.py
|
|
4
|
+
from base_api_utils.logging_config import build_logging
|
|
5
|
+
|
|
6
|
+
LOGGING = build_logging(
|
|
7
|
+
log_file=os.path.join(BASE_DIR, 'logs/api.log'),
|
|
8
|
+
loggers={
|
|
9
|
+
'django': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
|
|
10
|
+
'api': os.getenv('API_LOG_LEVEL', 'DEBUG'),
|
|
11
|
+
},
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
The service names its loggers and their levels. The rest is the same in every service:
|
|
15
|
+
|
|
16
|
+
- ``LOG_HANDLERS`` picks the local sinks, ``file`` and ``console``, of the root logger and of every
|
|
17
|
+
logger the service names. Both by default, for development. A deployed service keeps ``console``
|
|
18
|
+
until its OTLP bridge is on, then sets the variable empty and logs only through OTLP.
|
|
19
|
+
- The loggers the service names do not propagate: root has the same sinks, and in a Celery worker
|
|
20
|
+
it also carries Celery's own stderr handler, so a record that travelled up would be written twice.
|
|
21
|
+
- The OTLP bridge's own loggers keep the console whatever ``LOG_HANDLERS`` says.
|
|
22
|
+
|
|
23
|
+
settings.py imports this module, so it imports nothing but the standard library:
|
|
24
|
+
``base_api_utils.utils`` reads REST_FRAMEWORK when it is imported, which fails before the settings
|
|
25
|
+
exist. The handler classes are named by their dotted path and loaded when logging is configured.
|
|
26
|
+
"""
|
|
27
|
+
import os
|
|
28
|
+
|
|
29
|
+
LOCAL_SINKS = ('file', 'console')
|
|
30
|
+
|
|
31
|
+
DEFAULT_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
|
|
32
|
+
|
|
33
|
+
# The OTLP bridge's own loggers, and the level each is held at: audit.otlp is where
|
|
34
|
+
# base_api_utils.otel_logging reports (enabled, flush timed out) and opentelemetry is the SDK's
|
|
35
|
+
# (failed export, retry). They are never bridged, since a pipeline cannot report its own failure
|
|
36
|
+
# through itself, so they keep the console: with no sink left, a collector that rejects the exports
|
|
37
|
+
# would otherwise leave no trace anywhere. WARNING keeps the SDK's routine lines out.
|
|
38
|
+
DIAGNOSTIC_LOGGERS = {'audit.otlp': 'INFO', 'opentelemetry': 'WARNING'}
|
|
39
|
+
|
|
40
|
+
# Bridged in every service: ftn-audit and base_api_utils.security log on the first two, Django on
|
|
41
|
+
# the others.
|
|
42
|
+
PLATFORM_BRIDGE_LOGGERS = ('audit', 'oauth2', 'django.request', 'django.server')
|
|
43
|
+
|
|
44
|
+
# django.request and django.server propagate to django: a handler on the parent as well would
|
|
45
|
+
# export each of their records twice.
|
|
46
|
+
_NEVER_BRIDGED = ('django', *DIAGNOSTIC_LOGGERS)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def selected_sinks(environ=None):
|
|
50
|
+
"""The handlers ``LOG_HANDLERS`` leaves on a logger.
|
|
51
|
+
|
|
52
|
+
A name other than ``file`` or ``console`` is ignored, so a stale value cannot stop the service
|
|
53
|
+
booting: dictConfig refuses a handler it does not know. With no sink left the logger gets a
|
|
54
|
+
NullHandler, because a logger with no handler at all hands WARNING and above to
|
|
55
|
+
``logging.lastResort``, which writes them to stderr.
|
|
56
|
+
"""
|
|
57
|
+
environ = os.environ if environ is None else environ
|
|
58
|
+
names = [name.strip() for name in environ.get('LOG_HANDLERS', ','.join(LOCAL_SINKS)).split(',')]
|
|
59
|
+
return list(dict.fromkeys(name for name in names if name in LOCAL_SINKS)) or ['null']
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_logging(*, log_file, loggers, root_level='WARNING', fmt=DEFAULT_FORMAT, environ=None):
|
|
63
|
+
"""The dict for ``settings.LOGGING``.
|
|
64
|
+
|
|
65
|
+
``loggers`` maps each logger the service logs to onto its level. ``log_file`` is where the
|
|
66
|
+
``file`` sink writes; its directory is created when ``LOG_HANDLERS`` selects that sink.
|
|
67
|
+
``root_level`` is the level of the root logger, which receives the
|
|
68
|
+
loggers the service does not name (third-party libraries). ``fmt`` is the line format of both
|
|
69
|
+
sinks. ``environ`` is read for ``LOG_HANDLERS`` and defaults to ``os.environ``.
|
|
70
|
+
|
|
71
|
+
The result is a plain dict: a service that needs something of its own (a filter, one logger
|
|
72
|
+
with other handlers) changes it after the call.
|
|
73
|
+
"""
|
|
74
|
+
taken = sorted(set(loggers) & ({''} | set(DIAGNOSTIC_LOGGERS)))
|
|
75
|
+
if taken:
|
|
76
|
+
raise ValueError(f'build_logging declares these loggers itself: {taken!r}')
|
|
77
|
+
|
|
78
|
+
sinks = selected_sinks(environ)
|
|
79
|
+
if 'file' in sinks:
|
|
80
|
+
# The file opens on the first line written. Without its directory that logging call
|
|
81
|
+
# raises, in the code that logs. Created here, a directory that cannot be created stops
|
|
82
|
+
# the boot instead.
|
|
83
|
+
directory = os.path.dirname(os.fspath(log_file))
|
|
84
|
+
if directory:
|
|
85
|
+
os.makedirs(directory, exist_ok=True)
|
|
86
|
+
# A list of its own for each logger: a service may change one after the call.
|
|
87
|
+
declared = {'': {'handlers': list(sinks), 'level': root_level}}
|
|
88
|
+
for name, level in loggers.items():
|
|
89
|
+
declared[name] = {'handlers': list(sinks), 'level': level, 'propagate': False}
|
|
90
|
+
for name, level in DIAGNOSTIC_LOGGERS.items():
|
|
91
|
+
declared[name] = {'handlers': ['console'], 'level': level, 'propagate': False}
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
'version': 1,
|
|
95
|
+
'disable_existing_loggers': False,
|
|
96
|
+
'formatters': {
|
|
97
|
+
'console': {'format': fmt},
|
|
98
|
+
'file': {'format': fmt},
|
|
99
|
+
},
|
|
100
|
+
'handlers': {
|
|
101
|
+
'null': {'class': 'logging.NullHandler'},
|
|
102
|
+
# No require_debug_true: it would silence the console wherever DEBUG is off.
|
|
103
|
+
'console': {
|
|
104
|
+
'class': 'base_api_utils.log_handlers.RedactingStreamHandler',
|
|
105
|
+
'formatter': 'console',
|
|
106
|
+
},
|
|
107
|
+
'file': {
|
|
108
|
+
'class': 'base_api_utils.log_handlers.RedactingFileHandler',
|
|
109
|
+
'formatter': 'file',
|
|
110
|
+
'filename': os.fspath(log_file),
|
|
111
|
+
# dictConfig builds every handler declared here, selected or not, and a
|
|
112
|
+
# FileHandler opens its file when it is built.
|
|
113
|
+
'delay': True,
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
'loggers': declared,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def bridge_logger_names(logging_config):
|
|
121
|
+
"""The loggers that get the OTLP handler when ``OTEL_BRIDGE_LOGGERS`` names none.
|
|
122
|
+
|
|
123
|
+
The platform loggers plus every logger ``logging_config`` declares, so a logger added to
|
|
124
|
+
``settings.LOGGING`` is exported without a second list to keep in step. Left out: root,
|
|
125
|
+
``django``, the bridge's own diagnostics, and a logger that propagates to one already in the
|
|
126
|
+
list, whose records reach that handler anyway.
|
|
127
|
+
"""
|
|
128
|
+
declared = (logging_config or {}).get('loggers', {})
|
|
129
|
+
candidates = list(PLATFORM_BRIDGE_LOGGERS)
|
|
130
|
+
for name in declared:
|
|
131
|
+
if name and name not in _NEVER_BRIDGED and name not in candidates:
|
|
132
|
+
candidates.append(name)
|
|
133
|
+
|
|
134
|
+
def reaches_a_bridged_ancestor(name):
|
|
135
|
+
if not declared.get(name, {}).get('propagate', True):
|
|
136
|
+
return False
|
|
137
|
+
parts = name.split('.')
|
|
138
|
+
return any('.'.join(parts[:depth]) in candidates for depth in range(1, len(parts)))
|
|
139
|
+
|
|
140
|
+
return [name for name in candidates if not reaches_a_bridged_ancestor(name)]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""What a Celery worker needs for its telemetry to survive the prefork pool.
|
|
2
|
+
|
|
3
|
+
# backend/celery.py
|
|
4
|
+
from base_api_utils.otel_celery import connect_worker_hooks
|
|
5
|
+
|
|
6
|
+
connect_worker_hooks()
|
|
7
|
+
|
|
8
|
+
- A pool child is forked after the parent imported Django, so the Celery instrumentation is
|
|
9
|
+
installed again in each child, from ``worker_process_init``.
|
|
10
|
+
- A child leaves through ``os._exit``, which skips the ``atexit`` hooks that flush the batch
|
|
11
|
+
processors: the spans and log records still queued when the worker stops, or when a child is
|
|
12
|
+
recycled, would be lost. Celery sends ``worker_process_shutdown`` in the child just before that
|
|
13
|
+
exit, and both providers are flushed from there.
|
|
14
|
+
|
|
15
|
+
``backend/celery.py`` is imported with the ``backend`` package, before the settings exist, so this
|
|
16
|
+
module imports nothing but Celery's signals until a signal fires.
|
|
17
|
+
"""
|
|
18
|
+
import logging
|
|
19
|
+
import sys
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
from celery.signals import worker_process_init, worker_process_shutdown
|
|
24
|
+
|
|
25
|
+
# Overall budget for flushing both providers when a worker process exits. The SDK does not bound
|
|
26
|
+
# that flush on its own: force_flush ignores its timeout and shutdown waits for the export thread,
|
|
27
|
+
# so a collector that accepts the connection but never answers would hold the child well past it.
|
|
28
|
+
WORKER_EXIT_FLUSH_DEADLINE_SECONDS = 5
|
|
29
|
+
|
|
30
|
+
_TRACES_MODULE = 'base_api_utils.otel_instrumentation'
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def connect_worker_hooks():
|
|
34
|
+
"""Connect both receivers. Calling it again changes nothing."""
|
|
35
|
+
worker_process_init.connect(
|
|
36
|
+
_instrument_celery_worker, weak=False, dispatch_uid='base_api_utils.otel_celery.init')
|
|
37
|
+
worker_process_shutdown.connect(
|
|
38
|
+
_flush_otel_on_worker_process_exit, weak=False, dispatch_uid='base_api_utils.otel_celery.shutdown')
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _instrument_celery_worker(**kwargs):
|
|
42
|
+
# The tracer provider itself is set up by settings.py (OTEL_INSTRUMENTATION_ENABLED).
|
|
43
|
+
from django.conf import settings
|
|
44
|
+
|
|
45
|
+
if getattr(settings, 'OTEL_INSTRUMENTATION_ENABLED', False):
|
|
46
|
+
from base_api_utils.otel_instrumentation import DjangoTelemetry
|
|
47
|
+
|
|
48
|
+
DjangoTelemetry.instrument_celery()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _flush_otel_on_worker_process_exit(**kwargs):
|
|
52
|
+
# Each flush runs in a daemon thread, and the receiver waits for both until the deadline; an
|
|
53
|
+
# export still blocked after that ends with the os._exit. Spans go first, since their shutdown
|
|
54
|
+
# logs a line, but get only half the budget before the log flush starts anyway: a stalled span
|
|
55
|
+
# export must not cost the log records.
|
|
56
|
+
from base_api_utils.otel_logging import shutdown_otel_logging
|
|
57
|
+
|
|
58
|
+
deadline = time.monotonic() + WORKER_EXIT_FLUSH_DEADLINE_SECONDS
|
|
59
|
+
flushers = {}
|
|
60
|
+
# Only when tracing was set up in this process: a service that exports logs alone need not
|
|
61
|
+
# have the instrumentation packages installed.
|
|
62
|
+
traces = sys.modules.get(_TRACES_MODULE)
|
|
63
|
+
if traces is not None:
|
|
64
|
+
flushers['spans'] = _start_exit_flush(traces.DjangoTelemetry.shutdown, 'spans')
|
|
65
|
+
flushers['spans'].join(WORKER_EXIT_FLUSH_DEADLINE_SECONDS / 2)
|
|
66
|
+
flushers['logs'] = _start_exit_flush(shutdown_otel_logging, 'logs')
|
|
67
|
+
for signal, flusher in flushers.items():
|
|
68
|
+
flusher.join(max(0.0, deadline - time.monotonic()))
|
|
69
|
+
if flusher.is_alive():
|
|
70
|
+
logging.getLogger('audit.otlp').warning(
|
|
71
|
+
'OTLP: %s flush did not finish within %s s; dropping what is still queued.',
|
|
72
|
+
signal,
|
|
73
|
+
WORKER_EXIT_FLUSH_DEADLINE_SECONDS,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _start_exit_flush(target, signal):
|
|
78
|
+
flusher = threading.Thread(target=target, name=f'otel-worker-exit-flush-{signal}', daemon=True)
|
|
79
|
+
flusher.start()
|
|
80
|
+
return flusher
|