Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: rewrite logging middleware as pure ASGI (#6337)
Wasim Yousef Said31943d3c2148
diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex f03af7b40e8..b8691587ac5 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -10,11 +10,9 @@ get_logger (factory for structured loggers).import reimport time-from typing import Callableimport structlog-from fastapi import Request, Response-from starlette.middleware.base import BaseHTTPMiddleware+from starlette.types import ASGIApp, Message, Receive, Scope, Sendfrom utils.native_path_leases import redact_native_paths@@ -22,51 +20,72 @@ logger = structlog.get_logger(__name__)_NATIVE_PATH_LEASE_RE = re.compile(r"(?i)(\b(?:native_path_lease|nativePathLease)[\"']?\s*[:=]\s*[\"']?)[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+")+_EXCLUDED_PATHS = {+ "/api/train/status",+ "/api/train/metrics",+ "/api/train/hardware",+ "/api/system",+}+_EXCLUDED_SUFFIXES = (+ ".png",+ ".jpg",+ ".jpeg",+ ".svg",+ ".ico",+ ".woff",+ ".woff2",+ ".ttf",+)-class LoggingMiddleware(BaseHTTPMiddleware):- async def dispatch(self, request: Request, call_next: Callable) -> Response:- start_time = time.time()+class LoggingMiddleware:+ """ASGI request logger that avoids BaseHTTPMiddleware streaming wrappers."""- try:- response = await call_next(request)+ def __init__(self, app: ASGIApp) -> None:+ self.app = app- process_time = (time.time() - start_time) * 1000+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http":+ await self.app(scope, receive, send)+ return- EXCLUDED_PATHS = {- "/api/train/status",- "/api/train/metrics",- "/api/train/hardware",- "/api/system",- }- is_excluded = (- request.url.path in EXCLUDED_PATHS- or request.url.path.startswith("/assets/")- or request.url.path.endswith(- (".png", ".jpg", ".jpeg", ".ico", ".woff", ".woff2", ".ttf")- )- )+ path = scope["path"]+ excluded = (+ path in _EXCLUDED_PATHS+ or path.startswith("/assets/")+ or path.endswith(_EXCLUDED_SUFFIXES)+ )+ start_time = time.perf_counter()+ status_code = 500- if not is_excluded:- logger.info(- "request_completed",- method = request.method,- path = request.url.path,- status_code = response.status_code,- process_time_ms = round(process_time, 2),- )-- return response+ async def send_wrapper(message: Message) -> None:+ nonlocal status_code+ if message["type"] == "http.response.start":+ status_code = message["status"]+ await send(message)- except Exception as e:+ try:+ await self.app(scope, receive, send_wrapper)+ except Exception as exc:logger.error("request_failed",- path = request.url.path,- method = request.method,- error = str(e),+ path = path,+ method = scope["method"],+ status_code = status_code,+ error = str(exc),+ process_time_ms = round((time.perf_counter() - start_time) * 1000, 2),exc_info = True,)raise+ else:+ if not excluded:+ logger.info(+ "request_completed",+ method = scope["method"],+ path = path,+ status_code = status_code,+ process_time_ms = round((time.perf_counter() - start_time) * 1000, 2),+ )def filter_sensitive_data(logger, method_name, event_dict):diff --git a/studio/backend/tests/test_logging_middleware.py b/studio/backend/tests/test_logging_middleware.pynew file mode 100644index 00000000000..34d43942ef4--- /dev/null+++ b/studio/backend/tests/test_logging_middleware.py@@ -0,0 +1,150 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from starlette.staticfiles import StaticFiles++from loggers import handlers as hmod+from loggers.handlers import LoggingMiddleware+++class _LogCapture:+ def __init__(self):+ self.events = []++ def info(self, event, **kw):+ self.events.append(("info", event, kw))++ def error(self, event, **kw):+ self.events.append(("error", event, kw))+++def logs(monkeypatch):+ capture = _LogCapture()+ monkeypatch.setattr(hmod, "logger", capture)+ return capture+++def _http_scope(path, method = "GET"):+ return {"type": "http", "path": path, "method": method}+++async def _noop_receive():+ return {"type": "http.disconnect"}+++def _run(coro):+ return asyncio.run(coro)+++def test_success_logs_status_and_forwards_chunks(logs):+ async def app(scope, receive, send):+ await send({"type": "http.response.start", "status": 206, "headers": []})+ await send({"type": "http.response.body", "body": b"a", "more_body": True})+ await send({"type": "http.response.body", "body": b"", "more_body": False})++ seen = []++ async def send(message):+ seen.append(message)++ _run(LoggingMiddleware(app)(_http_scope("/api/health"), _noop_receive, send))++ assert [m["type"] for m in seen] == [+ "http.response.start",+ "http.response.body",+ "http.response.body",+ ]+ assert logs.events[0][1] == "request_completed"+ assert logs.events[0][2]["status_code"] == 206+++def test_excluded_asset_success_skips_log(logs):+ async def app(scope, receive, send):+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b"ok"})++ async def send(message):+ pass++ for path in ("/assets/index.css", "/huggingface.svg", "/font.woff2"):+ _run(LoggingMiddleware(app)(_http_scope(path), _noop_receive, send))++ assert logs.events == []+++def test_exception_logs_real_status_and_reraises(logs):+ async def app(scope, receive, send):+ await send({"type": "http.response.start", "status": 418, "headers": []})+ raise RuntimeError("stream failed")++ async def send(message):+ pass++ with pytest.raises(RuntimeError, match = "stream failed"):+ _run(LoggingMiddleware(app)(_http_scope("/api/health"), _noop_receive, send))++ assert logs.events[0][1] == "request_failed"+ assert logs.events[0][2]["status_code"] == 418+ assert logs.events[0][2]["error"] == "stream failed"+ assert "process_time_ms" in logs.events[0][2]+++def test_cancelled_error_propagates_without_error_log(logs):+ async def app(scope, receive, send):+ raise asyncio.CancelledError()++ async def send(message):+ pass++ with pytest.raises(asyncio.CancelledError):+ _run(LoggingMiddleware(app)(_http_scope("/api/health"), _noop_receive, send))++ assert logs.events == []+++def test_non_http_scope_passes_through(logs):+ seen = []++ async def app(scope, receive, send):+ seen.append(scope["type"])++ async def send(message):+ pass++ _run(LoggingMiddleware(app)({"type": "websocket", "path": "/ws"}, _noop_receive, send))++ assert seen == ["websocket"]+ assert logs.events == []+++def test_fastapi_static_asset_success_skips_log(tmp_path, logs):+ assets_dir = tmp_path / "assets"+ assets_dir.mkdir()+ (assets_dir / "app.css").write_text("body { color: black; }", encoding = "utf-8")++ app = FastAPI()+ app.add_middleware(LoggingMiddleware)++ @app.get("/api/health")+ async def health():+ return {"ok": True}++ app.mount("/assets", StaticFiles(directory = assets_dir), name = "assets")+ client = TestClient(app)++ response = client.get("/api/health")+ assert response.status_code == 200+ assert logs.events[0][1] == "request_completed"+ assert logs.events[0][2]["path"] == "/api/health"++ log_count = len(logs.events)+ response = client.get("/assets/app.css")+ assert response.status_code == 200+ assert response.text == "body { color: black; }"+ assert len(logs.events) == log_count