feat: 增加结构化日志和服务就绪检查

This commit is contained in:
2026-07-10 12:14:19 +08:00
parent ebaf3defa2
commit d7d9514348
7 changed files with 184 additions and 4 deletions

View File

@@ -1,8 +1,13 @@
from __future__ import annotations
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from sqlalchemy import text
from app.core.config import get_settings
from app.core.database import SessionLocal
from app.core.responses import api_success
from app.services.redis_client import get_sync_redis_client
router = APIRouter()
@@ -10,3 +15,31 @@ router = APIRouter()
@router.get("/health")
def health() -> dict:
return api_success({"status": "ok"})
@router.get("/ready")
def ready():
checks = {"database": _database_ready(), "redis": _redis_ready()}
redis_required = get_settings().readiness_requires_redis
ready_state = checks["database"] and (checks["redis"] or not redis_required)
payload = api_success({"status": "ready" if ready_state else "not_ready", "checks": checks})
return payload if ready_state else JSONResponse(status_code=503, content=payload)
def _database_ready() -> bool:
try:
with SessionLocal() as db:
db.execute(text("SELECT 1"))
return True
except Exception:
return False
def _redis_ready() -> bool:
client = get_sync_redis_client()
if client is None:
return False
try:
return bool(client.ping())
except Exception:
return False