|
| 1 | +"""Logging estruturado (JSON ou texto) para auditoria e debugging do ACL. |
| 2 | +
|
| 3 | +Campos estáveis em ``metadata`` (snake_case): |
| 4 | + query, top_score, second_score, score_margin, decision, reason, confidence, |
| 5 | + mode, discipline_filter, informative_terms, coverage, coverage_weighted, |
| 6 | + candidate_count, selected_sources, llm_called, tokens_used, model, ... |
| 7 | +
|
| 8 | +Variável de ambiente: ACL_LOG_FORMAT=json | text (default: text). |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import datetime as _dt |
| 14 | +import json |
| 15 | +import logging |
| 16 | +import os |
| 17 | +from typing import Any, Mapping |
| 18 | + |
| 19 | +# Módulos lógicos (filtro em ferramentas: module=...) |
| 20 | +ACL_MOD_SEARCH = "search" |
| 21 | +ACL_MOD_CONTEXT = "context" |
| 22 | +ACL_MOD_DECISION = "decision" |
| 23 | +ACL_MOD_PROVIDER = "provider" |
| 24 | +ACL_MOD_EVALUATION = "evaluation" |
| 25 | +ACL_MOD_DATABASE = "database" |
| 26 | + |
| 27 | +ACL_EXTRA = "acl_payload" |
| 28 | +_MAX_QUERY_META = 512 |
| 29 | +_MAX_LIST_META = 24 |
| 30 | + |
| 31 | + |
| 32 | +def _truncate(s: str, n: int) -> str: |
| 33 | + s = str(s) |
| 34 | + if len(s) <= n: |
| 35 | + return s |
| 36 | + return s[: n - 3] + "..." |
| 37 | + |
| 38 | + |
| 39 | +def _sanitize_metadata(meta: Mapping[str, Any] | None) -> dict[str, Any]: |
| 40 | + if not meta: |
| 41 | + return {} |
| 42 | + out: dict[str, Any] = {} |
| 43 | + for k, v in meta.items(): |
| 44 | + if k == "query" and isinstance(v, str): |
| 45 | + out[k] = _truncate(v, _MAX_QUERY_META) |
| 46 | + elif k == "debug" and isinstance(v, dict): |
| 47 | + keys = list(v.keys())[:18] |
| 48 | + out[k] = {kk: v[kk] for kk in keys} |
| 49 | + if len(v) > len(keys): |
| 50 | + out[k]["_truncated"] = len(v) - len(keys) |
| 51 | + elif isinstance(v, (list, tuple)) and len(v) > _MAX_LIST_META: |
| 52 | + out[k] = list(v[:_MAX_LIST_META]) + [f"...(+{len(v) - _MAX_LIST_META})"] |
| 53 | + else: |
| 54 | + out[k] = v |
| 55 | + return out |
| 56 | + |
| 57 | + |
| 58 | +def log_event( |
| 59 | + logger: logging.Logger, |
| 60 | + level: int, |
| 61 | + module: str, |
| 62 | + event: str, |
| 63 | + message: str, |
| 64 | + metadata: Mapping[str, Any] | None = None, |
| 65 | +) -> None: |
| 66 | + """Um evento ACL = um registo com payload em ``extra`` (Formatter consome).""" |
| 67 | + payload = { |
| 68 | + "module": module, |
| 69 | + "event": event, |
| 70 | + "message": message, |
| 71 | + "metadata": _sanitize_metadata(dict(metadata) if metadata else None), |
| 72 | + } |
| 73 | + logger.log(level, message, extra={ACL_EXTRA: payload}) |
| 74 | + |
| 75 | + |
| 76 | +class AclLogFormatter(logging.Formatter): |
| 77 | + """Se o record tiver ``acl_payload``, formata JSON ou linha compacta; senão legado.""" |
| 78 | + |
| 79 | + def __init__(self, json_mode: bool, datefmt: str | None = None) -> None: |
| 80 | + super().__init__( |
| 81 | + fmt="%(asctime)s %(levelname)s [%(name)s] %(message)s", |
| 82 | + datefmt=datefmt or "%H:%M:%S", |
| 83 | + ) |
| 84 | + self._json_mode = json_mode |
| 85 | + |
| 86 | + def format(self, record: logging.LogRecord) -> str: |
| 87 | + pl = getattr(record, ACL_EXTRA, None) |
| 88 | + if isinstance(pl, dict): |
| 89 | + ts = _dt.datetime.fromtimestamp( |
| 90 | + record.created, tz=_dt.timezone.utc |
| 91 | + ).isoformat(timespec="milliseconds") |
| 92 | + if self._json_mode: |
| 93 | + line: dict[str, Any] = { |
| 94 | + "timestamp": ts, |
| 95 | + "level": record.levelname, |
| 96 | + "module": pl["module"], |
| 97 | + "event": pl["event"], |
| 98 | + "message": pl["message"], |
| 99 | + "metadata": pl.get("metadata") or {}, |
| 100 | + } |
| 101 | + return json.dumps(line, ensure_ascii=False, default=str) |
| 102 | + meta = pl.get("metadata") or {} |
| 103 | + parts = [f"{k}={v!r}" for k, v in list(meta.items())[:14]] |
| 104 | + tail = " ".join(parts) |
| 105 | + return ( |
| 106 | + f"{ts} {record.levelname:7} [{pl['module']}] {pl['event']} | {pl['message']}" |
| 107 | + + (f" | {tail}" if tail else "") |
| 108 | + ) |
| 109 | + return super().format(record) |
0 commit comments