feat(logging): expand debug-logging coverage, add primitives, redaction & tests

Instrument the full download pipeline in the structured JSONL debug logger and make adding logging to new features a one-liner.

Coverage:
- DRM license request/response, content keys (incl. remote-CDM seam) and decrypt timing across Widevine/PlayReady/ClearKey
- DASH/HLS/ISM manifest fetch + parse milestones (HLS.to_tracks also covers the m3u8_parser path used by iTunes/ATV-style services)
- Per-backend vault get/add via the Vaults manager, track selection, subtitle conversion, repackage, normalize_vui, and full mkvmerge mux (command, duration, output size, warnings)
- All external tooling (ffmpeg, ffprobe, mkvmerge, mkvpropedit, dovi_tool, SubtitleEdit, ccextractor) via a unified `tool_run` op, centralised in run_step/ffprobe + log_tool_run

DX:
- Add log_event() / timed_operation() primitives (no-op when disabled); retrofit ~91 guard/timing blocks onto them
- Fix message= collision in log_drm_operation/log_vault_query/log_service_call that raised TypeError on the live decrypt path

Redaction (redact_all = redact_text -> redact_url -> redact_path):
- Collapse content/CDN/api URLs to `redacted[.ext]`
- Strip local path prefixes (install root -> <unshackle>, venv -> <venv>, home -> ~)
- Apply to every logged string so shared logs leak no URLs, paths or usernames
- Drop per-request service_call logging (manifest parse is the request seam)
This commit is contained in:
imSp4rky
2026-06-09 22:12:05 -06:00
parent 7064d261c2
commit 394ed67e28
24 changed files with 1763 additions and 793 deletions
+74 -16
View File
@@ -30,7 +30,7 @@ from unidecode import unidecode
from unshackle.core.config import config
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE
from unshackle.core.utils.redact import redact_text
from unshackle.core.utils.redact import redact_all
"""
Utility functions for the unshackle media archival tool.
@@ -837,7 +837,7 @@ class DebugLogger:
if operation:
entry["operation"] = operation
if message:
entry["message"] = redact_text(message)
entry["message"] = redact_all(message)
if service:
entry["service"] = service
if context:
@@ -854,9 +854,9 @@ class DebugLogger:
if error:
entry["error"] = {
"type": type(error).__name__,
"message": redact_text(str(error)),
"message": redact_all(str(error)),
"traceback": [
redact_text(line) for line in traceback.format_exception(type(error), error, error.__traceback__)
redact_all(line) for line in traceback.format_exception(type(error), error, error.__traceback__)
],
}
@@ -879,9 +879,8 @@ class DebugLogger:
return None
if isinstance(data, str):
# mask URL userinfo and secret-bearing query params that key-based
# redaction can't catch (e.g. a proxy URL inside a non-sensitive field)
return redact_text(data)
# mask secrets, collapse content/CDN URLs, and strip local path prefixes
return redact_all(data)
if isinstance(data, (int, float, bool)):
return data
@@ -920,7 +919,7 @@ class DebugLogger:
return "[BINARY_DATA]"
if isinstance(data, Path):
return str(data)
return redact_all(str(data))
try:
return str(data)
@@ -980,7 +979,9 @@ class DebugLogger:
url: Request URL
**kwargs: Additional request details (headers, body, etc.)
"""
self.log(level="DEBUG", operation="service_call", request={"method": method, "url": url, **kwargs})
message = kwargs.pop("message", "")
level = kwargs.pop("level", "DEBUG")
self.log(level=level, operation="service_call", message=message, request={"method": method, "url": url, **kwargs})
def log_drm_operation(self, drm_type: str, operation: str, **kwargs):
"""
@@ -989,11 +990,11 @@ class DebugLogger:
Args:
drm_type: DRM type (Widevine, PlayReady, etc.)
operation: DRM operation name
**kwargs: Additional context (PSSH, KIDs, keys, etc.)
**kwargs: Additional context. Pass ``message=``/``level=`` to override the defaults.
"""
self.log(
level="DEBUG", operation=f"drm_{operation}", message=f"{drm_type} {operation}", drm_type=drm_type, **kwargs
)
message = kwargs.pop("message", None) or f"{drm_type} {operation}"
level = kwargs.pop("level", "DEBUG")
self.log(level=level, operation=f"drm_{operation}", message=message, drm_type=drm_type, **kwargs)
def log_vault_query(self, vault_name: str, operation: str, **kwargs):
"""
@@ -1002,12 +1003,14 @@ class DebugLogger:
Args:
vault_name: Name of the vault
operation: Vault operation (get_key, add_key, etc.)
**kwargs: Additional context (KID, key, success, etc.)
**kwargs: Additional context. Pass ``message=``/``level=`` to override the defaults.
"""
message = kwargs.pop("message", None) or f"Vault {vault_name}: {operation}"
level = kwargs.pop("level", "DEBUG")
self.log(
level="DEBUG",
level=level,
operation=f"vault_{operation}",
message=f"Vault {vault_name}: {operation}",
message=message,
vault=vault_name,
**kwargs,
)
@@ -1047,6 +1050,59 @@ def get_debug_logger() -> Optional[DebugLogger]:
return _debug_logger
def log_event(operation: str, *, level: str = "DEBUG", message: str = "", **kwargs: Any) -> None:
"""Emit a single structured debug-log entry. No-op when debug logging is disabled.
The canonical one-shot logging primitive — replaces the
``if dl := get_debug_logger(): dl.log(...)`` guard boilerplate. To add logging to a new
feature, call ``log_event("my_feature_event", message="...", context={...})``.
"""
dl = _debug_logger
if dl:
dl.log(level=level, operation=operation, message=message, **kwargs)
@contextlib.contextmanager
def timed_operation(operation: str, *, level: str = "DEBUG", message: str = "", **kwargs: Any):
"""Time a block and log ``operation`` once it finishes, with ``duration_ms``.
Logs at ``level`` with ``success=True`` on normal exit, or at ERROR with the exception and
``success=False`` if the block raises (then re-raises). No-op when debug logging is disabled,
so it is always safe to wrap a block in it.
Example::
with timed_operation("mux", context={"output": str(path)}):
run_mkvmerge(...)
"""
dl = _debug_logger
if not dl:
yield
return
start = time.monotonic()
try:
yield
except Exception as e:
dl.log(
level="ERROR",
operation=operation,
message=message or f"{operation} failed",
error=e,
success=False,
duration_ms=round((time.monotonic() - start) * 1000, 1),
**kwargs,
)
raise
dl.log(
level=level,
operation=operation,
message=message,
success=True,
duration_ms=round((time.monotonic() - start) * 1000, 1),
**kwargs,
)
def init_debug_logger(log_path: Optional[Path] = None, enabled: bool = False, log_keys: bool = False):
"""
Initialize the global debug logger.
@@ -1075,4 +1131,6 @@ __all__ = (
"get_debug_logger",
"init_debug_logger",
"close_debug_logger",
"log_event",
"timed_operation",
)