Expose DB connection error in /health response for debugging
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -13,10 +13,10 @@ def _params() -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def check_db() -> bool:
|
def check_db() -> tuple[bool, str]:
|
||||||
try:
|
try:
|
||||||
conn = pymysql.connect(**_params())
|
conn = pymysql.connect(**_params())
|
||||||
conn.close()
|
conn.close()
|
||||||
return True
|
return True, "ok"
|
||||||
except Exception:
|
except Exception as e:
|
||||||
return False
|
return False, str(e)
|
||||||
|
|||||||
12
app/main.py
12
app/main.py
@@ -10,10 +10,11 @@ logger = logging.getLogger("pops")
|
|||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
if check_db():
|
ok, msg = check_db()
|
||||||
|
if ok:
|
||||||
logger.info("Database connection OK")
|
logger.info("Database connection OK")
|
||||||
else:
|
else:
|
||||||
logger.warning("Database unreachable — check MYSQL_* environment variables")
|
logger.warning("Database unreachable: %s", msg)
|
||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
@@ -27,8 +28,9 @@ def root():
|
|||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
def health():
|
def health():
|
||||||
db_ok = check_db()
|
ok, msg = check_db()
|
||||||
return {
|
return {
|
||||||
"status": "ok" if db_ok else "degraded",
|
"status": "ok" if ok else "degraded",
|
||||||
"db": "connected" if db_ok else "unreachable",
|
"db": "connected" if ok else "unreachable",
|
||||||
|
"detail": msg,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user