|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +""" |
| 5 | +Internal HTTP logger that writes redacted request/response diagnostics to local files. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json as _json |
| 11 | +import logging |
| 12 | +import os |
| 13 | +import uuid |
| 14 | +from datetime import datetime, timezone |
| 15 | +from logging.handlers import RotatingFileHandler |
| 16 | +from typing import Any, Dict, Optional |
| 17 | + |
| 18 | +from .log_config import LogConfig |
| 19 | + |
| 20 | + |
| 21 | +class _HttpLogger: |
| 22 | + """Structured HTTP diagnostic logger with automatic header redaction.""" |
| 23 | + |
| 24 | + def __init__(self, config: LogConfig) -> None: |
| 25 | + self._config = config |
| 26 | + self._redacted = {h.lower() for h in config.redacted_headers} |
| 27 | + |
| 28 | + # Ensure folder exists |
| 29 | + os.makedirs(config.log_folder, exist_ok=True) |
| 30 | + |
| 31 | + # Build timestamped filename |
| 32 | + ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") |
| 33 | + filename = f"{config.log_file_prefix}_{ts}.log" |
| 34 | + filepath = os.path.join(config.log_folder, filename) |
| 35 | + |
| 36 | + # Create a dedicated named logger (not root) to avoid side effects |
| 37 | + logger_name = f"PowerPlatform.Dataverse.http.{uuid.uuid4().hex[:8]}" |
| 38 | + self._logger = logging.getLogger(logger_name) |
| 39 | + self._logger.setLevel(getattr(logging, config.log_level.upper(), logging.DEBUG)) |
| 40 | + self._logger.propagate = False # don't bubble to root |
| 41 | + |
| 42 | + handler = RotatingFileHandler( |
| 43 | + filepath, |
| 44 | + maxBytes=config.max_file_bytes, |
| 45 | + backupCount=config.backup_count, |
| 46 | + encoding="utf-8", |
| 47 | + ) |
| 48 | + formatter = logging.Formatter( |
| 49 | + "[%(asctime)s] %(levelname)s %(message)s", |
| 50 | + datefmt="%Y-%m-%dT%H:%M:%S%z", |
| 51 | + ) |
| 52 | + handler.setFormatter(formatter) |
| 53 | + self._logger.addHandler(handler) |
| 54 | + |
| 55 | + def log_request( |
| 56 | + self, |
| 57 | + method: str, |
| 58 | + url: str, |
| 59 | + headers: Optional[Dict[str, str]] = None, |
| 60 | + body: Any = None, |
| 61 | + ) -> None: |
| 62 | + """Log an outbound HTTP request.""" |
| 63 | + safe_headers = self._redact_headers(headers or {}) |
| 64 | + body_text = self._truncate_body(body) |
| 65 | + lines = [ |
| 66 | + f">>> REQUEST {method.upper()} {url}", |
| 67 | + f" Headers: {safe_headers}", |
| 68 | + ] |
| 69 | + if body_text: |
| 70 | + lines.append(f" Body: {body_text}") |
| 71 | + self._logger.debug("\n".join(lines)) |
| 72 | + |
| 73 | + def log_response( |
| 74 | + self, |
| 75 | + method: str, |
| 76 | + url: str, |
| 77 | + status_code: int, |
| 78 | + headers: Optional[Dict[str, str]] = None, |
| 79 | + body: Any = None, |
| 80 | + elapsed_ms: Optional[float] = None, |
| 81 | + ) -> None: |
| 82 | + """Log an inbound HTTP response.""" |
| 83 | + safe_headers = self._redact_headers(headers or {}) |
| 84 | + body_text = self._truncate_body(body) |
| 85 | + elapsed_str = f" ({elapsed_ms:.1f}ms)" if elapsed_ms is not None else "" |
| 86 | + lines = [ |
| 87 | + f"<<< RESPONSE {status_code} {method.upper()} {url}{elapsed_str}", |
| 88 | + f" Headers: {safe_headers}", |
| 89 | + ] |
| 90 | + if body_text: |
| 91 | + lines.append(f" Body: {body_text}") |
| 92 | + self._logger.debug("\n".join(lines)) |
| 93 | + |
| 94 | + def log_error(self, method: str, url: str, error: Exception) -> None: |
| 95 | + """Log an HTTP transport error.""" |
| 96 | + self._logger.error(f"!!! ERROR {method.upper()} {url} - {type(error).__name__}: {error}") |
| 97 | + |
| 98 | + def _redact_headers(self, headers: Dict[str, str]) -> Dict[str, str]: |
| 99 | + return {k: ("[REDACTED]" if k.lower() in self._redacted else v) for k, v in headers.items()} |
| 100 | + |
| 101 | + def _truncate_body(self, body: Any) -> str: |
| 102 | + if body is None: |
| 103 | + return "" |
| 104 | + if isinstance(body, (bytes, bytearray)): |
| 105 | + text = body.decode("utf-8", errors="replace") |
| 106 | + elif not isinstance(body, str): |
| 107 | + try: |
| 108 | + text = _json.dumps(body, default=str, ensure_ascii=False) |
| 109 | + except (TypeError, ValueError): |
| 110 | + text = str(body) |
| 111 | + else: |
| 112 | + text = body |
| 113 | + |
| 114 | + limit = self._config.max_body_bytes |
| 115 | + if limit == 0: |
| 116 | + return "" |
| 117 | + if len(text) > limit: |
| 118 | + return text[:limit] + f"... [truncated, {len(text)} bytes total]" |
| 119 | + return text |
0 commit comments