goomba / app.py
Corvius's picture
Update app.py
fdf9fc1 verified
raw
history blame
1.82 kB
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
import logging
import json
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
# CORS (Cross-Origin Resource Sharing) middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow requests from any origin
allow_credentials=True,
allow_methods=["*"], # Allow all HTTP methods
allow_headers=["*"], # Allow all headers
)
@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"])
async def logging_proxy(request: Request, full_path: str):
"""
Logs all incoming requests and their details, then forwards the request.
"""
# Log the request details
log_data = {
"method": request.method,
"url": str(request.url),
"headers": dict(request.headers),
"query_params": dict(request.query_params),
"client_host": request.client.host,
}
try:
# Get the request body (if any) and log it as well
body = await request.body()
if body:
try:
# Attempt to decode JSON body for better logging
json_body = json.loads(body.decode())
log_data["body"] = json_body
except json.JSONDecodeError:
# Log the raw body if it's not JSON
log_data["body"] = body.decode()
logger.info(f"Incoming request: {json.dumps(log_data, indent=2)}")
return {
"message": "Request logged successfully",
"logged_data": log_data
}
except Exception as e:
logger.error(f"Error processing request: {e}")
return {"error": "An error occurred while processing the request"}