From 23b90be8fef6f0c2e8b8631512ea4b288555a40c Mon Sep 17 00:00:00 2001 From: Farruh Sheripov Date: Fri, 15 Sep 2023 23:10:01 +0200 Subject: [PATCH] MP-432 fix formatter and logger --- django_google_structured_logger/formatter.py | 17 ++++---- .../graphene_middlewares.py | 12 +++--- .../middlewares.py | 15 ++++--- django_google_structured_logger/settings.py | 40 +++++++++---------- django_google_structured_logger/storages.py | 6 +-- 5 files changed, 45 insertions(+), 45 deletions(-) diff --git a/django_google_structured_logger/formatter.py b/django_google_structured_logger/formatter.py index 59fa2bd..25d11ec 100644 --- a/django_google_structured_logger/formatter.py +++ b/django_google_structured_logger/formatter.py @@ -40,8 +40,10 @@ def add_fields(self, log_record: Dict, record, message_dict: Dict): def _set_labels(self, log_record: Dict, current_request: Optional[RequestStorage]): """Set the Google labels in the log record.""" labels = { - "user_id": getattr(current_request, "user_id", None), - "user_display_field": getattr(current_request, "user_display_field", None), + "user_id": current_request.user_id() if current_request else None, + "user_display_field": current_request.user_display_field() + if current_request + else None, **log_record.get(self.google_labels_field, {}), **log_record.pop("labels", {}), } @@ -54,14 +56,15 @@ def _set_operation( """Set the Google operation details in the log record.""" operation = { "id": getattr(current_request, "uuid", None), - **{ - k: v - for k, v in log_record.items() - if k in ["first_operation", "last_operation"] and v - }, **log_record.get(self.google_operation_field, {}), **log_record.pop("operation", {}), } + + if "first_operation" in log_record: + operation["first"] = log_record.pop("first_operation") + if "last_operation" in log_record: + operation["last"] = log_record.pop("last_operation") + log_record[self.google_operation_field] = operation def _set_source_location(self, log_record: Dict, record): diff --git a/django_google_structured_logger/graphene_middlewares.py b/django_google_structured_logger/graphene_middlewares.py index 522b2f9..5cb18fc 100644 --- a/django_google_structured_logger/graphene_middlewares.py +++ b/django_google_structured_logger/graphene_middlewares.py @@ -14,15 +14,15 @@ class GrapheneSetUserContextMiddleware: def resolve(self, next, root, info, **args): - user = info.context.user - _current_request.set( RequestStorage( - user_id=self._get_user_attribute(user, settings.LOG_USER_ID_FIELD), - user_display_field=self._get_user_attribute( - user, settings.LOG_USER_DISPLAY_FIELD - ), uuid=str(uuid.uuid4()), + user_id=lambda: self._get_user_attribute( + info.context.user, settings.LOG_USER_ID_FIELD + ), + user_display_field=lambda: self._get_user_attribute( + info.context.user, settings.LOG_USER_DISPLAY_FIELD + ), ) ) diff --git a/django_google_structured_logger/middlewares.py b/django_google_structured_logger/middlewares.py index f029bc8..a235a99 100644 --- a/django_google_structured_logger/middlewares.py +++ b/django_google_structured_logger/middlewares.py @@ -18,19 +18,18 @@ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): - response = self.get_response(request) - user = request.user - _current_request.set( RequestStorage( - user_id=self._get_user_attribute(user, settings.LOG_USER_ID_FIELD), - user_display_field=self._get_user_attribute( - user, settings.LOG_USER_DISPLAY_FIELD - ), uuid=str(uuid.uuid4()), + user_id=lambda: self._get_user_attribute( + request.user, settings.LOG_USER_ID_FIELD + ), + user_display_field=lambda: self._get_user_attribute( + request.user, settings.LOG_USER_DISPLAY_FIELD + ), ) ) - return response + return self.get_response(request) @staticmethod def _get_user_attribute(user, attribute) -> Any: diff --git a/django_google_structured_logger/settings.py b/django_google_structured_logger/settings.py index fe8cfcb..2adee83 100644 --- a/django_google_structured_logger/settings.py +++ b/django_google_structured_logger/settings.py @@ -25,32 +25,30 @@ "^otp.*", # One-Time Passwords or related values ] -DEFAULT_SENSITIVE_HEADERS = ( - [ - "Authorization", # Tokens and credentials - "Cookie", # User session identifiers - "Set-Cookie", # Server set session identifiers - "X-API-Key", # API keys - "X-CSRFToken", # CSRF tokens - "Proxy-Authorization", # Credentials for a proxy connection - "If-None-Match", # Can be used for cache fingerprinting - "Server", # Can reveal specifics about the server - "WWW-Authenticate", # Authentication method details - "X-Correlation-ID", # Correlation IDs for logging - "X-Frame-Options", # Security-related header - "Strict-Transport-Security", # Security-related header - "X-XSS-Protection", # Security-related header - "X-Content-Type-Options", # Security-related header - "X-Download-Options", # Security-related header - "X-Permitted-Cross-Domain-Policies", # Security-related header - ], -) +DEFAULT_SENSITIVE_HEADERS = [ + "Authorization", # Tokens and credentials + "Cookie", # User session identifiers + "Set-Cookie", # Server set session identifiers + "X-API-Key", # API keys + "X-CSRFToken", # CSRF tokens + "Proxy-Authorization", # Credentials for a proxy connection + "If-None-Match", # Can be used for cache fingerprinting + "Server", # Can reveal specifics about the server + "WWW-Authenticate", # Authentication method details + "X-Correlation-ID", # Correlation IDs for logging + "X-Frame-Options", # Security-related header + "Strict-Transport-Security", # Security-related header + "X-XSS-Protection", # Security-related header + "X-Content-Type-Options", # Security-related header + "X-Download-Options", # Security-related header + "X-Permitted-Cross-Domain-Policies", # Security-related header +] LOG_MAX_STR_LEN = getattr(settings, "LOG_MAX_STR_LEN", 200) LOG_MAX_LIST_LEN = getattr(settings, "LOG_MAX_LIST_LEN", 10) LOG_EXCLUDED_ENDPOINTS = getattr(settings, "LOG_EXCLUDED_ENDPOINTS", []) LOG_SENSITIVE_KEYS = getattr(settings, "LOG_SENSITIVE_KEYS", DEFAULT_SENSITIVE_KEYS) -LOG_MASK_STYLE = getattr(settings, "LOG_MASK_STYLE", "partially") +LOG_MASK_STYLE = getattr(settings, "LOG_MASK_STYLE", "partial") LOG_MIDDLEWARE_ENABLED = getattr(settings, "LOG_MIDDLEWARE_ENABLED", True) LOG_EXCLUDED_HEADERS = getattr( settings, "LOG_EXCLUDED_HEADERS", DEFAULT_SENSITIVE_HEADERS diff --git a/django_google_structured_logger/storages.py b/django_google_structured_logger/storages.py index bafaa93..46a7484 100644 --- a/django_google_structured_logger/storages.py +++ b/django_google_structured_logger/storages.py @@ -1,13 +1,13 @@ from contextvars import ContextVar from dataclasses import dataclass -from typing import Optional +from typing import Callable, Optional @dataclass(frozen=True) class RequestStorage: uuid: str - user_id: Optional[int] = None - user_display_field: Optional[str] = None + user_id: Callable[[], Optional[int]] = lambda: None + user_display_field: Callable[[], Optional[str]] = lambda: None _current_request: ContextVar[Optional[RequestStorage]] = ContextVar(