FastApi-ISS/utils/boxapi_log.py
2025-08-11 22:07:49 +03:30

35 lines
1.1 KiB
Python

# utils/boxapi_log.py
import json, os, datetime
from typing import Any, Dict, Optional
LOG_ROOT = os.environ.get("BOXAPI_LOG_DIR", "/app/logs/boxapi")
def _ensure_dir(path: str) -> None:
os.makedirs(path, exist_ok=True)
def log_boxapi_response(
username: str,
request_payload: Dict[str, Any],
status_code: Optional[int],
response_json: Optional[Dict[str, Any]] = None,
response_text: Optional[str] = None,
note: str = ""
) -> str:
ts = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
safe_user = (username or "unknown").replace("/", "_")
dirpath = os.path.join(LOG_ROOT, safe_user)
_ensure_dir(dirpath)
filepath = os.path.join(dirpath, f"{ts}.json")
doc = {
"timestamp_utc": ts,
"username": username,
"status_code": status_code,
"note": note,
"request_payload": request_payload, # does NOT include API credentials
"response_json": response_json,
"response_text": response_text if response_json is None else None,
}
with open(filepath, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False, indent=2)
return filepath