Add comprehensive logging and debugging features

- Add request logging middleware to track all incoming requests
- Add startup/shutdown event handlers with detailed logging
- Enhance debug endpoint with server and request information
- Add catch-all route to identify unhandled requests
- Improve logging to help diagnose reverse proxy issues

🤖 Generated with BackendIM

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Automated Action 2025-06-27 15:24:48 +00:00
parent 7e123eab23
commit 8f6a26603c

88
main.py
View File

@ -1,13 +1,22 @@
from fastapi import FastAPI
import logging
import time
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.router import api_router
from app.db.session import engine
from app.db.base import Base
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create database tables
Base.metadata.create_all(bind=engine)
logger.info(f"Starting {settings.APP_NAME} v{settings.APP_VERSION}")
logger.info("Database tables created successfully")
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
@ -17,6 +26,16 @@ app = FastAPI(
redoc_url="/redoc"
)
# Add request logging middleware
@app.middleware("http")
async def log_requests(request: Request, call_next):
start_time = time.time()
logger.info(f"Incoming request: {request.method} {request.url}")
response = await call_next(request)
process_time = time.time() - start_time
logger.info(f"Request completed: {request.method} {request.url} - Status: {response.status_code} - Time: {process_time:.4f}s")
return response
# Configure CORS
app.add_middleware(
CORSMiddleware,
@ -30,6 +49,27 @@ app.add_middleware(
app.include_router(api_router, prefix="/api/v1")
@app.on_event("startup")
async def startup_event():
logger.info("=== FastAPI Application Started ===")
logger.info(f"App Name: {settings.APP_NAME}")
logger.info(f"Version: {settings.APP_VERSION}")
logger.info("Available endpoints:")
logger.info(" GET / - Root endpoint")
logger.info(" GET /health - Health check")
logger.info(" GET /debug - Debug information")
logger.info(" GET /docs - Swagger UI documentation")
logger.info(" GET /redoc - ReDoc documentation")
logger.info(" GET /openapi.json - OpenAPI schema")
logger.info(" * /api/v1/* - API endpoints")
logger.info("=====================================")
@app.on_event("shutdown")
async def shutdown_event():
logger.info("FastAPI Application shutting down...")
@app.get("/")
async def root():
"""Root endpoint providing service information"""
@ -60,14 +100,27 @@ async def health_check():
@app.get("/debug")
async def debug_info():
async def debug_info(request: Request):
"""Debug endpoint to verify FastAPI is running"""
import os
import socket
return {
"message": "FastAPI application is running",
"message": "FastAPI application is running correctly",
"service": settings.APP_NAME,
"version": settings.APP_VERSION,
"python_version": os.sys.version,
"timestamp": time.time(),
"server_info": {
"hostname": socket.gethostname(),
"python_version": os.sys.version.split()[0],
"platform": os.sys.platform
},
"request_info": {
"client_host": request.client.host if request.client else "unknown",
"method": request.method,
"url": str(request.url),
"headers": dict(request.headers)
},
"available_endpoints": [
"/",
"/health",
@ -75,6 +128,29 @@ async def debug_info():
"/docs",
"/redoc",
"/openapi.json",
"/api/v1/*"
]
"/api/v1/auth/register",
"/api/v1/auth/login",
"/api/v1/resumes/upload",
"/api/v1/jobs/",
"/api/v1/matching/analyze"
],
"docs_urls": {
"swagger_ui": "/docs",
"redoc": "/redoc",
"openapi_json": "/openapi.json"
}
}
# Add a catch-all route to log any unhandled requests
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
async def catch_all(request: Request, path: str):
"""Catch-all endpoint to log unhandled requests"""
logger.warning(f"Unhandled request: {request.method} /{path}")
return {
"error": "Endpoint not found",
"path": path,
"method": request.method,
"message": "This endpoint does not exist. Check /debug for available endpoints.",
"available_docs": ["/docs", "/redoc", "/openapi.json"]
}