40 lines
1.4 KiB
Python
40 lines
1.4 KiB
Python
# utils/boxapi_log.py
|
|
import orjson, os, datetime
|
|
from typing import Any, Dict, Optional
|
|
|
|
LOG_ROOT = os.environ.get("BOXAPI_LOG_DIR", "/app/logs/boxapi")
|
|
LOG_LEVEL = os.environ.get("BOXAPI_LOG_LEVEL", "all") # "all", "error", "none"
|
|
|
|
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:
|
|
# Skip logging if level is "none" or if level is "error" and this is not an error
|
|
if LOG_LEVEL == "none" or (LOG_LEVEL == "error" and "error" not in note.lower()):
|
|
return ""
|
|
|
|
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, "wb") as f:
|
|
f.write(orjson.dumps(doc, option=orjson.OPT_INDENT_2))
|
|
return filepath |