Skip to content

Commit 23b90be

Browse files
committed
MP-432 fix formatter and logger
1 parent 43693a6 commit 23b90be

File tree

5 files changed

+45
-45
lines changed

5 files changed

+45
-45
lines changed

django_google_structured_logger/formatter.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,10 @@ def add_fields(self, log_record: Dict, record, message_dict: Dict):
4040
def _set_labels(self, log_record: Dict, current_request: Optional[RequestStorage]):
4141
"""Set the Google labels in the log record."""
4242
labels = {
43-
"user_id": getattr(current_request, "user_id", None),
44-
"user_display_field": getattr(current_request, "user_display_field", None),
43+
"user_id": current_request.user_id() if current_request else None,
44+
"user_display_field": current_request.user_display_field()
45+
if current_request
46+
else None,
4547
**log_record.get(self.google_labels_field, {}),
4648
**log_record.pop("labels", {}),
4749
}
@@ -54,14 +56,15 @@ def _set_operation(
5456
"""Set the Google operation details in the log record."""
5557
operation = {
5658
"id": getattr(current_request, "uuid", None),
57-
**{
58-
k: v
59-
for k, v in log_record.items()
60-
if k in ["first_operation", "last_operation"] and v
61-
},
6259
**log_record.get(self.google_operation_field, {}),
6360
**log_record.pop("operation", {}),
6461
}
62+
63+
if "first_operation" in log_record:
64+
operation["first"] = log_record.pop("first_operation")
65+
if "last_operation" in log_record:
66+
operation["last"] = log_record.pop("last_operation")
67+
6568
log_record[self.google_operation_field] = operation
6669

6770
def _set_source_location(self, log_record: Dict, record):

django_google_structured_logger/graphene_middlewares.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@
1414

1515
class GrapheneSetUserContextMiddleware:
1616
def resolve(self, next, root, info, **args):
17-
user = info.context.user
18-
1917
_current_request.set(
2018
RequestStorage(
21-
user_id=self._get_user_attribute(user, settings.LOG_USER_ID_FIELD),
22-
user_display_field=self._get_user_attribute(
23-
user, settings.LOG_USER_DISPLAY_FIELD
24-
),
2519
uuid=str(uuid.uuid4()),
20+
user_id=lambda: self._get_user_attribute(
21+
info.context.user, settings.LOG_USER_ID_FIELD
22+
),
23+
user_display_field=lambda: self._get_user_attribute(
24+
info.context.user, settings.LOG_USER_DISPLAY_FIELD
25+
),
2626
)
2727
)
2828

django_google_structured_logger/middlewares.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,18 @@ def __init__(self, get_response):
1818
self.get_response = get_response
1919

2020
def __call__(self, request):
21-
response = self.get_response(request)
22-
user = request.user
23-
2421
_current_request.set(
2522
RequestStorage(
26-
user_id=self._get_user_attribute(user, settings.LOG_USER_ID_FIELD),
27-
user_display_field=self._get_user_attribute(
28-
user, settings.LOG_USER_DISPLAY_FIELD
29-
),
3023
uuid=str(uuid.uuid4()),
24+
user_id=lambda: self._get_user_attribute(
25+
request.user, settings.LOG_USER_ID_FIELD
26+
),
27+
user_display_field=lambda: self._get_user_attribute(
28+
request.user, settings.LOG_USER_DISPLAY_FIELD
29+
),
3130
)
3231
)
33-
return response
32+
return self.get_response(request)
3433

3534
@staticmethod
3635
def _get_user_attribute(user, attribute) -> Any:

django_google_structured_logger/settings.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -25,32 +25,30 @@
2525
"^otp.*", # One-Time Passwords or related values
2626
]
2727

28-
DEFAULT_SENSITIVE_HEADERS = (
29-
[
30-
"Authorization", # Tokens and credentials
31-
"Cookie", # User session identifiers
32-
"Set-Cookie", # Server set session identifiers
33-
"X-API-Key", # API keys
34-
"X-CSRFToken", # CSRF tokens
35-
"Proxy-Authorization", # Credentials for a proxy connection
36-
"If-None-Match", # Can be used for cache fingerprinting
37-
"Server", # Can reveal specifics about the server
38-
"WWW-Authenticate", # Authentication method details
39-
"X-Correlation-ID", # Correlation IDs for logging
40-
"X-Frame-Options", # Security-related header
41-
"Strict-Transport-Security", # Security-related header
42-
"X-XSS-Protection", # Security-related header
43-
"X-Content-Type-Options", # Security-related header
44-
"X-Download-Options", # Security-related header
45-
"X-Permitted-Cross-Domain-Policies", # Security-related header
46-
],
47-
)
28+
DEFAULT_SENSITIVE_HEADERS = [
29+
"Authorization", # Tokens and credentials
30+
"Cookie", # User session identifiers
31+
"Set-Cookie", # Server set session identifiers
32+
"X-API-Key", # API keys
33+
"X-CSRFToken", # CSRF tokens
34+
"Proxy-Authorization", # Credentials for a proxy connection
35+
"If-None-Match", # Can be used for cache fingerprinting
36+
"Server", # Can reveal specifics about the server
37+
"WWW-Authenticate", # Authentication method details
38+
"X-Correlation-ID", # Correlation IDs for logging
39+
"X-Frame-Options", # Security-related header
40+
"Strict-Transport-Security", # Security-related header
41+
"X-XSS-Protection", # Security-related header
42+
"X-Content-Type-Options", # Security-related header
43+
"X-Download-Options", # Security-related header
44+
"X-Permitted-Cross-Domain-Policies", # Security-related header
45+
]
4846

4947
LOG_MAX_STR_LEN = getattr(settings, "LOG_MAX_STR_LEN", 200)
5048
LOG_MAX_LIST_LEN = getattr(settings, "LOG_MAX_LIST_LEN", 10)
5149
LOG_EXCLUDED_ENDPOINTS = getattr(settings, "LOG_EXCLUDED_ENDPOINTS", [])
5250
LOG_SENSITIVE_KEYS = getattr(settings, "LOG_SENSITIVE_KEYS", DEFAULT_SENSITIVE_KEYS)
53-
LOG_MASK_STYLE = getattr(settings, "LOG_MASK_STYLE", "partially")
51+
LOG_MASK_STYLE = getattr(settings, "LOG_MASK_STYLE", "partial")
5452
LOG_MIDDLEWARE_ENABLED = getattr(settings, "LOG_MIDDLEWARE_ENABLED", True)
5553
LOG_EXCLUDED_HEADERS = getattr(
5654
settings, "LOG_EXCLUDED_HEADERS", DEFAULT_SENSITIVE_HEADERS

django_google_structured_logger/storages.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
from contextvars import ContextVar
22
from dataclasses import dataclass
3-
from typing import Optional
3+
from typing import Callable, Optional
44

55

66
@dataclass(frozen=True)
77
class RequestStorage:
88
uuid: str
9-
user_id: Optional[int] = None
10-
user_display_field: Optional[str] = None
9+
user_id: Callable[[], Optional[int]] = lambda: None
10+
user_display_field: Callable[[], Optional[str]] = lambda: None
1111

1212

1313
_current_request: ContextVar[Optional[RequestStorage]] = ContextVar(

0 commit comments

Comments
 (0)