Source code for automated_document_parser.logging_config
"""Structured logging helpers for applications using Automated Document Parser."""
from __future__ import annotations
import json
import logging
import re
import sys
from collections.abc import Iterator, Mapping, Sequence
from contextlib import contextmanager
from contextvars import ContextVar, Token
from datetime import UTC, datetime
from typing import IO, Any
correlation_id_var: ContextVar[str | None] = ContextVar(
"adp_correlation_id", default=None
)
_STANDARD_FIELDS = {
"name",
"msg",
"args",
"levelname",
"levelno",
"pathname",
"filename",
"module",
"exc_info",
"exc_text",
"stack_info",
"lineno",
"funcName",
"created",
"msecs",
"relativeCreated",
"thread",
"threadName",
"processName",
"process",
"message",
"taskName",
}
_SENSITIVE_KEY = re.compile(
r"(?:api.?key|access.?token|refresh.?token|password|passwd|secret|authorization|credential|document.?content|raw.?text|request.?body)",
re.IGNORECASE,
)
_SECRET_PATTERNS = (
re.compile(r"(?i)(\bauthorization\b\s*[:=]\s*)(?:Bearer\s+)?[^\s,;]+"),
re.compile(
r"(?i)(\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*)([^\s,;]+)"
),
re.compile(r"(?i)(\bBearer\s+)[A-Za-z0-9._~+/-]+=*"),
)
_REDACTED = "[REDACTED]"
def _redact_text(value: str) -> str:
for pattern in _SECRET_PATTERNS:
value = pattern.sub(lambda match: match.group(1) + _REDACTED, value)
return value
def _safe_value(key: str, value: Any) -> Any:
if _SENSITIVE_KEY.search(key):
return _REDACTED
if isinstance(value, str):
return _redact_text(value)
if isinstance(value, Mapping):
return {
str(child_key): _safe_value(str(child_key), child_value)
for child_key, child_value in value.items()
}
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return [_safe_value(key, item) for item in value]
return value
[docs]
class CorrelationIdFilter(logging.Filter):
"""Attach the current request/job correlation ID to each log record."""
[docs]
def filter(self, record: logging.LogRecord) -> bool:
record.correlation_id = correlation_id_var.get()
return True
class _SafeFormatter(logging.Formatter):
@staticmethod
def _safe_message(record: logging.LogRecord) -> str:
try:
message = record.getMessage()
except Exception: # noqa: BLE001 - logging must not break application work.
message = "<unformattable log message>"
return _redact_text(message)
@staticmethod
def _safe_extras(record: logging.LogRecord) -> dict[str, Any]:
return {
key: _safe_value(key, value)
for key, value in record.__dict__.items()
if key not in _STANDARD_FIELDS
and key not in {"correlation_id"}
and not key.startswith("_")
}
def _exception(self, record: logging.LogRecord) -> str | None:
if not record.exc_info:
return None
return _redact_text(self.formatException(record.exc_info))
[docs]
class JsonLogFormatter(_SafeFormatter):
"""Render one JSON object per log record with safe structured context."""
[docs]
def format(self, record: logging.LogRecord) -> str:
payload: dict[str, Any] = {
"timestamp": datetime.fromtimestamp(record.created, UTC).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": self._safe_message(record),
}
correlation_id = getattr(record, "correlation_id", None)
if correlation_id:
payload["correlation_id"] = correlation_id
payload.update(self._safe_extras(record))
exception = self._exception(record)
if exception:
payload["exception"] = exception
if record.stack_info:
payload["stack"] = _redact_text(self.formatStack(record.stack_info))
return json.dumps(
payload, ensure_ascii=False, default=str, separators=(",", ":")
)
[docs]
class HumanLogFormatter(_SafeFormatter):
"""Readable console formatter that preserves safe event context."""
[docs]
def format(self, record: logging.LogRecord) -> str:
timestamp = (
datetime.fromtimestamp(record.created, UTC)
.astimezone()
.isoformat(timespec="seconds")
)
correlation_id = getattr(record, "correlation_id", None)
event = getattr(record, "event", None)
prefix = f"{timestamp} {record.levelname:<8} {record.name}"
if correlation_id:
prefix += f" [correlation_id={_redact_text(str(correlation_id))}]"
if event:
prefix += f" event={_redact_text(str(event))}"
extras = self._safe_extras(record)
extras.pop("event", None)
suffix = ""
if extras:
suffix = " " + json.dumps(
extras, ensure_ascii=False, default=str, sort_keys=True
)
message = self._safe_message(record)
exception = self._exception(record)
if exception:
message += "\n" + exception
return f"{prefix} {message}{suffix}"
[docs]
def configure_logging(
level: str | int = "INFO",
*,
stream: IO[str] | None = None,
log_format: str = "json",
) -> None:
"""Configure package logs as JSON or human-readable output.
The library never configures the root logger. Applications opt in at their
process boundary (for example, the CLI or service entry point). Repeated
calls update the existing package handler rather than adding duplicates.
"""
resolved_level = (
getattr(logging, level.upper(), None) if isinstance(level, str) else level
)
if not isinstance(resolved_level, int):
raise ValueError(f"Unsupported log level: {level!r}") # noqa: TRY004
if log_format not in {"json", "human"}:
raise ValueError("log_format must be 'json' or 'human'")
package_logger = logging.getLogger("automated_document_parser")
package_logger.setLevel(resolved_level)
package_logger.propagate = False
handler = next(
(
item
for item in package_logger.handlers
if getattr(item, "_adp_handler", False)
),
None,
)
if handler is not None and getattr(handler.stream, "closed", False):
package_logger.removeHandler(handler)
handler.close()
handler = None
if handler is None:
handler = logging.StreamHandler(stream or sys.stderr)
handler._adp_handler = True # type: ignore[attr-defined]
handler._adp_json_handler = (
True # Backwards-compatible test/integration marker.
)
handler.addFilter(CorrelationIdFilter())
package_logger.addHandler(handler)
elif stream is not None and handler.stream is not stream:
handler.setStream(stream)
handler.setFormatter(
JsonLogFormatter() if log_format == "json" else HumanLogFormatter()
)
[docs]
@contextmanager
def correlation_context(value: str) -> Iterator[None]:
"""Temporarily bind a correlation ID to logs in the current context."""
token: Token[str | None] = correlation_id_var.set(value)
try:
yield
finally:
correlation_id_var.reset(token)
[docs]
def get_correlation_id() -> str | None:
"""Return the current request/job correlation ID, if one is bound."""
return correlation_id_var.get()