-
Notifications
You must be signed in to change notification settings - Fork 14
Add opt-in HTTP diagnostics logging with automatic header redaction #135
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 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
cba7b3a
Initial plan
Copilot 0569eb5
feat: add opt-in local file logging of HTTP request/response diagnostics
Copilot 33802d9
Merge branch 'main' into copilot/add-local-file-logging
sagebree 448b150
feat: enhance HTTP logging with precise filename timestamps and impro…
83b9e68
Merge branch 'copilot/add-local-file-logging' of https://github.com/m…
1cb2e4c
refactor: fix black formatting
24b0b77
max_body_bytes default changed from 4096 → 0. Added http disagnostics…
87effc0
docs: update logging section in README for clarity on production use
d92eef1
Merge branch 'main' into copilot/add-local-file-logging
sagebree baf427f
Address PR feeback and add logger headers
dd07b93
Merge branch 'copilot/add-local-file-logging' of https://github.com/m…
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,119 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| """ | ||
| Internal HTTP logger that writes redacted request/response diagnostics to local files. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json as _json | ||
| import logging | ||
| import os | ||
| import uuid | ||
| from datetime import datetime, timezone | ||
| from logging.handlers import RotatingFileHandler | ||
| from typing import Any, Dict, Optional | ||
|
|
||
| from .log_config import LogConfig | ||
|
|
||
|
|
||
| class _HttpLogger: | ||
| """Structured HTTP diagnostic logger with automatic header redaction.""" | ||
|
|
||
| def __init__(self, config: LogConfig) -> None: | ||
| self._config = config | ||
| self._redacted = {h.lower() for h in config.redacted_headers} | ||
|
|
||
| # Ensure folder exists | ||
| os.makedirs(config.log_folder, exist_ok=True) | ||
|
|
||
| # Build timestamped filename | ||
| ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") | ||
| filename = f"{config.log_file_prefix}_{ts}.log" | ||
| filepath = os.path.join(config.log_folder, filename) | ||
|
|
||
| # Create a dedicated named logger (not root) to avoid side effects | ||
| logger_name = f"PowerPlatform.Dataverse.http.{uuid.uuid4().hex[:8]}" | ||
|
sagebree marked this conversation as resolved.
Outdated
|
||
| self._logger = logging.getLogger(logger_name) | ||
| self._logger.setLevel(getattr(logging, config.log_level.upper(), logging.DEBUG)) | ||
| self._logger.propagate = False # don't bubble to root | ||
|
|
||
| handler = RotatingFileHandler( | ||
| filepath, | ||
| maxBytes=config.max_file_bytes, | ||
| backupCount=config.backup_count, | ||
| encoding="utf-8", | ||
| ) | ||
| formatter = logging.Formatter( | ||
| "[%(asctime)s] %(levelname)s %(message)s", | ||
| datefmt="%Y-%m-%dT%H:%M:%S%z", | ||
| ) | ||
| handler.setFormatter(formatter) | ||
| self._logger.addHandler(handler) | ||
|
|
||
| def log_request( | ||
| self, | ||
| method: str, | ||
| url: str, | ||
| headers: Optional[Dict[str, str]] = None, | ||
| body: Any = None, | ||
| ) -> None: | ||
| """Log an outbound HTTP request.""" | ||
| safe_headers = self._redact_headers(headers or {}) | ||
| body_text = self._truncate_body(body) | ||
| lines = [ | ||
| f">>> REQUEST {method.upper()} {url}", | ||
| f" Headers: {safe_headers}", | ||
| ] | ||
| if body_text: | ||
| lines.append(f" Body: {body_text}") | ||
| self._logger.debug("\n".join(lines)) | ||
|
|
||
| def log_response( | ||
| self, | ||
| method: str, | ||
| url: str, | ||
| status_code: int, | ||
| headers: Optional[Dict[str, str]] = None, | ||
| body: Any = None, | ||
| elapsed_ms: Optional[float] = None, | ||
| ) -> None: | ||
| """Log an inbound HTTP response.""" | ||
| safe_headers = self._redact_headers(headers or {}) | ||
| body_text = self._truncate_body(body) | ||
| elapsed_str = f" ({elapsed_ms:.1f}ms)" if elapsed_ms is not None else "" | ||
| lines = [ | ||
| f"<<< RESPONSE {status_code} {method.upper()} {url}{elapsed_str}", | ||
| f" Headers: {safe_headers}", | ||
| ] | ||
| if body_text: | ||
| lines.append(f" Body: {body_text}") | ||
| self._logger.debug("\n".join(lines)) | ||
|
|
||
| def log_error(self, method: str, url: str, error: Exception) -> None: | ||
| """Log an HTTP transport error.""" | ||
| self._logger.error(f"!!! ERROR {method.upper()} {url} - {type(error).__name__}: {error}") | ||
|
|
||
| def _redact_headers(self, headers: Dict[str, str]) -> Dict[str, str]: | ||
| return {k: ("[REDACTED]" if k.lower() in self._redacted else v) for k, v in headers.items()} | ||
|
|
||
| def _truncate_body(self, body: Any) -> str: | ||
| if body is None: | ||
| return "" | ||
| if isinstance(body, (bytes, bytearray)): | ||
| text = body.decode("utf-8", errors="replace") | ||
| elif not isinstance(body, str): | ||
| try: | ||
| text = _json.dumps(body, default=str, ensure_ascii=False) | ||
| except (TypeError, ValueError): | ||
| text = str(body) | ||
| else: | ||
| text = body | ||
|
|
||
| limit = self._config.max_body_bytes | ||
| if limit == 0: | ||
| return "" | ||
| if len(text) > limit: | ||
| return text[:limit] + f"... [truncated, {len(text)} bytes total]" | ||
| return text | ||
|
sagebree marked this conversation as resolved.
|
||
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,64 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| """ | ||
| Local file logging configuration for Dataverse SDK HTTP diagnostics. | ||
|
|
||
| Provides :class:`LogConfig`, an opt-in configuration for writing request/response | ||
| traces to ``.log`` files with automatic header redaction and timestamped filenames. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass, field | ||
| from typing import FrozenSet | ||
|
|
||
| __all__ = ["LogConfig"] | ||
|
|
||
| # Headers whose values must never appear in log files | ||
| _DEFAULT_REDACTED_HEADERS: FrozenSet[str] = frozenset( | ||
| { | ||
| "authorization", | ||
| "proxy-authorization", | ||
| "x-ms-authorization-auxiliary", | ||
| "ocp-apim-subscription-key", | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def _default_redacted_headers() -> FrozenSet[str]: | ||
| return _DEFAULT_REDACTED_HEADERS | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class LogConfig: | ||
| """ | ||
| Configuration for local HTTP diagnostics logging. | ||
|
|
||
| When provided to :class:`~PowerPlatform.Dataverse.client.DataverseClient` via | ||
| :class:`~PowerPlatform.Dataverse.core.config.DataverseConfig`, every HTTP request | ||
| and response is logged to timestamped ``.log`` files in the specified folder. | ||
| Sensitive headers (e.g. ``Authorization``) are automatically redacted. | ||
|
|
||
| :param log_folder: Directory path for log files. Created automatically if missing. | ||
| Default: ``"./dataverse_logs"`` | ||
| :param log_file_prefix: Filename prefix. Timestamp is appended automatically. | ||
| Default: ``"dataverse"`` → ``dataverse_20260310_143022.log`` | ||
| :param max_body_bytes: Maximum bytes of request/response body to capture. | ||
| ``0`` disables body logging. Default: ``4096``. | ||
| :param redacted_headers: Header names (case-insensitive) whose values are | ||
| replaced with ``"[REDACTED]"`` in logs. Defaults include | ||
| ``Authorization``, ``Proxy-Authorization``, etc. | ||
| :param log_level: Python logging level name. Default: ``"DEBUG"``. | ||
| :param max_file_bytes: Max size per log file before rotation (bytes). | ||
| Default: ``10_485_760`` (10 MB). | ||
| :param backup_count: Number of rotated backup files to keep. Default: ``5``. | ||
| """ | ||
|
|
||
| log_folder: str = "./dataverse_logs" | ||
| log_file_prefix: str = "dataverse" | ||
| max_body_bytes: int = 4096 | ||
| redacted_headers: FrozenSet[str] = field(default_factory=_default_redacted_headers) | ||
| log_level: str = "DEBUG" | ||
|
sagebree marked this conversation as resolved.
|
||
| max_file_bytes: int = 10_485_760 # 10 MB | ||
| backup_count: int = 5 | ||
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.