-
Notifications
You must be signed in to change notification settings - Fork 0
Add TRACE logging level for verbose payload logging across event writers #61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c95767c
Add TRACE logging level for verbose payload logging across event writers
oto-macenauer-absa e9164ae
Implement TRACE-level logging utilities and safe serialization for se…
oto-macenauer-absa fb6d1fa
Minor changes based on AI comments
oto-macenauer-absa e9a8712
Fix naming inconsistency
oto-macenauer-absa f5b4f0b
Minor update in logging
oto-macenauer-absa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| """Custom logging levels. | ||
|
|
||
| Adds a TRACE level below DEBUG for very verbose payload logging. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
| import logging | ||
|
|
||
| TRACE_LEVEL = 5 | ||
|
|
||
| # Register level name only once (idempotent) | ||
| if not hasattr(logging, "TRACE"): | ||
| logging.addLevelName(TRACE_LEVEL, "TRACE") | ||
|
|
||
| def trace(self: logging.Logger, message: str, *args, **kws): # type: ignore[override] | ||
| """Log a message with TRACE level. | ||
|
|
||
| Args: | ||
| self: Logger instance. | ||
| message: Log message format string. | ||
| *args: Positional arguments for message formatting. | ||
| **kws: Keyword arguments passed to _log. | ||
| """ | ||
| if self.isEnabledFor(TRACE_LEVEL): | ||
| self._log(TRACE_LEVEL, message, args, **kws) # pylint: disable=protected-access | ||
|
|
||
| logging.Logger.trace = trace # type: ignore[attr-defined] | ||
|
|
||
| __all__ = ["TRACE_LEVEL"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # | ||
| # Copyright 2025 ABSA Group Limited | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
|
|
||
| """Safe serialization utilities for logging. | ||
|
|
||
| Provides PII-safe, size-bounded JSON serialization for TRACE logging. | ||
| """ | ||
|
|
||
| import json | ||
| import os | ||
| from typing import Any, List, Set | ||
|
|
||
|
|
||
| def _redact_sensitive_keys(obj: Any, redact_keys: Set[str]) -> Any: | ||
| """Recursively redact sensitive keys from nested structures. | ||
|
|
||
| Args: | ||
| obj: Object to redact (dict, list, or scalar). | ||
| redact_keys: Set of key names to redact (case-insensitive). | ||
|
|
||
| Returns: | ||
| Copy of obj with sensitive values replaced by "***REDACTED***". | ||
| """ | ||
| if isinstance(obj, dict): | ||
| return { | ||
| k: "***REDACTED***" if k.lower() in redact_keys else _redact_sensitive_keys(v, redact_keys) | ||
| for k, v in obj.items() | ||
| } | ||
| if isinstance(obj, list): | ||
| return [_redact_sensitive_keys(item, redact_keys) for item in obj] | ||
| return obj | ||
|
|
||
|
|
||
| def safe_serialize_for_log(message: Any, redact_keys: List[str] | None = None, max_bytes: int | None = None) -> str: | ||
| """Safely serialize a message for logging with redaction and size capping. | ||
|
|
||
| Args: | ||
| message: Object to serialize (typically a dict). | ||
| redact_keys: List of key names to redact (case-insensitive). If None, uses env TRACE_REDACT_KEYS. | ||
| max_bytes: Maximum serialized output size in bytes. If None, uses env TRACE_MAX_BYTES (default 10000). | ||
|
|
||
| Returns: | ||
| JSON string (redacted and truncated if needed), or empty string on serialization error. | ||
| """ | ||
| # Apply configuration defaults | ||
| if redact_keys is None: | ||
| redact_keys_str = os.environ.get("TRACE_REDACT_KEYS", "password,secret,token,key,apikey,api_key") | ||
| redact_keys = [k.strip() for k in redact_keys_str.split(",") if k.strip()] | ||
| if max_bytes is None: | ||
| max_bytes = int(os.environ.get("TRACE_MAX_BYTES", "10000")) | ||
|
|
||
| # Normalize to case-insensitive set | ||
| redact_set = {k.lower() for k in redact_keys} | ||
|
|
||
| try: | ||
| # Redact sensitive keys | ||
| redacted = _redact_sensitive_keys(message, redact_set) | ||
| # Serialize with minimal whitespace | ||
| serialized = json.dumps(redacted, separators=(",", ":")) | ||
| # Truncate if needed | ||
| if len(serialized.encode("utf-8")) > max_bytes: | ||
| # Binary truncate to max_bytes and append marker | ||
| truncated_bytes = serialized.encode("utf-8")[:max_bytes] | ||
| # Ensure we don't break mid-multibyte character | ||
| try: | ||
| return truncated_bytes.decode("utf-8", errors="ignore") + "..." | ||
| except UnicodeDecodeError: # pragma: no cover - defensive | ||
| return "" | ||
| return serialized | ||
| except (TypeError, ValueError, OverflowError): # pragma: no cover - catch serialization errors | ||
| return "" | ||
|
|
||
|
|
||
| __all__ = ["safe_serialize_for_log"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| # | ||
| # Copyright 2025 ABSA Group Limited | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
|
|
||
| """Trace-level logging utilities. | ||
|
|
||
| Provides reusable TRACE-level payload logging for writer modules. | ||
| """ | ||
|
|
||
| import logging | ||
| from typing import Any, Dict | ||
|
|
||
| from .logging_levels import TRACE_LEVEL | ||
| from .safe_serialization import safe_serialize_for_log | ||
|
|
||
|
|
||
| def log_payload_at_trace(logger: logging.Logger, writer_name: str, topic_name: str, message: Dict[str, Any]) -> None: | ||
| """Log message payload at TRACE level with safe serialization. | ||
|
|
||
| Args: | ||
| logger: Logger instance to use for logging. | ||
| writer_name: Name of the writer (e.g., "EventBridge", "Kafka", "Postgres"). | ||
| topic_name: Topic name being written to. | ||
| message: Message payload to log. | ||
| """ | ||
| if not logger.isEnabledFor(TRACE_LEVEL): | ||
| return | ||
|
|
||
| try: | ||
| safe_payload = safe_serialize_for_log(message) | ||
| if safe_payload: | ||
| logger.trace( # type: ignore[attr-defined] | ||
| "%s payload topic=%s payload=%s", writer_name, topic_name, safe_payload | ||
| ) | ||
| except (TypeError, ValueError): # pragma: no cover - defensive serialization guard | ||
| logger.trace("%s payload topic=%s <unserializable>", writer_name, topic_name) # type: ignore[attr-defined] | ||
|
|
||
|
|
||
| __all__ = ["log_payload_at_trace"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.