Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
90f1c82
1
Parent(s): 950f41b
add requests logging
Browse files2 unmodified lines34567891011121314151691 unmodified lines108109110111112113247 unmodified lines3613623633643653662 unmodified linesimport osimport timeimport asynciofrom typing import Optional, Dict, Listfrom dataclasses import dataclass, fieldfrom collections import OrderedDictfrom datetime import datetime, timedeltaimport hashlibimport aiohttpfrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.openapi.utils import get_openapifrom pydantic import BaseModel, Fieldfrom duckduckgo_search import DDGS91 unmodified linesPRELOAD_MODELS = os.getenv("PRELOAD_MODELS", "").split(",") if os.getenv("PRELOAD_MODELS") else []WEB_SEARCH_CACHE_TTL = int(os.getenv("WEB_SEARCH_CACHE_TTL", "3600")) # 1 hourREQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "300")) # 5 minutes@dataclass247 unmodified lines# HTTP session for connection pooling (will be initialized in startup)http_session: Optional[aiohttp.ClientSession] = Noneclass ModelSwitchRequest(BaseModel):"""Request to switch the active LLM model."""2 unmodified lines345678910111213141516171891 unmodified lines110111112113114115116117247 unmodified lines3653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474482 unmodified linesimport osimport timeimport asynciofrom typing import Optional, Dict, List, Anyfrom dataclasses import dataclass, fieldfrom collections import OrderedDictfrom datetime import datetime, timedeltaimport hashlibimport jsonimport uuidimport aiohttpfrom fastapi import FastAPI, HTTPException, BackgroundTasks, Requestfrom fastapi.openapi.utils import get_openapifrom pydantic import BaseModel, Fieldfrom duckduckgo_search import DDGS91 unmodified linesPRELOAD_MODELS = os.getenv("PRELOAD_MODELS", "").split(",") if os.getenv("PRELOAD_MODELS") else []WEB_SEARCH_CACHE_TTL = int(os.getenv("WEB_SEARCH_CACHE_TTL", "3600")) # 1 hourREQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "300")) # 5 minutesLOG_REQUEST_BODY = os.getenv("LOG_REQUEST_BODY", "1") == "1"LOG_REQUEST_BODY_MAX_CHARS = int(os.getenv("LOG_REQUEST_BODY_MAX_CHARS", "2000"))@dataclass247 unmodified lines# HTTP session for connection pooling (will be initialized in startup)http_session: Optional[aiohttp.ClientSession] = NoneSENSITIVE_HEADERS = {"authorization", "proxy-authorization", "x-api-key", "api-key"}SENSITIVE_FIELDS = {"authorization", "api_key", "api-key", "password", "token"}def _redact_headers(headers: Dict[str, str]) -> Dict[str, str]:"""Redact sensitive headers before logging."""redacted = {}for key, value in headers.items():if key.lower() in SENSITIVE_HEADERS:redacted[key] = "[redacted]"else:redacted[key] = valuereturn redacteddef _redact_json(obj: Any) -> Any:"""Redact sensitive fields in JSON-like structures."""if isinstance(obj, dict):redacted = {}for key, value in obj.items():if str(key).lower() in SENSITIVE_FIELDS:redacted[key] = "[redacted]"else:redacted[key] = _redact_json(value)return redactedif isinstance(obj, list):return [_redact_json(item) for item in obj]return objdef _format_body_for_log(content_type: str, body: bytes) -> str:"""Format request body for logging with size limits and redaction."""if not body:return ""text_preview: strif "application/json" in (content_type or ""):try:parsed = json.loads(body.decode("utf-8"))redacted = _redact_json(parsed)text_preview = json.dumps(redacted, ensure_ascii=True)except Exception:text_preview = body.decode("utf-8", errors="replace")else:text_preview = body.decode("utf-8", errors="replace")if len(text_preview) > LOG_REQUEST_BODY_MAX_CHARS:text_preview = text_preview[:LOG_REQUEST_BODY_MAX_CHARS] + "...[truncated]"return text_preview@app.middleware("http")async def log_received_request(request: Request, call_next):"""Log incoming requests and responses with basic metadata."""request_id = uuid.uuid4().hex[:12]start = time.perf_counter()body_text = ""if LOG_REQUEST_BODY:body_bytes = await request.body()body_text = _format_body_for_log(request.headers.get("content-type", ""), body_bytes)headers = _redact_headers(dict(request.headers))client_host = request.client.host if request.client else "-"query = f"?{request.url.query}" if request.url.query else ""logger.info(f"➡️ {request_id} {request.method} {request.url.path}{query} "f"from {client_host} ua={headers.get('user-agent', '-')}")if body_text:logger.info(f" body={body_text}")response = await call_next(request)elapsed_ms = (time.perf_counter() - start) * 1000logger.info(f"⬅️ {request_id} {response.status_code} {elapsed_ms:.1f}ms")return responseclass ModelSwitchRequest(BaseModel):"""Request to switch the active LLM model."""
app.py+84-2