|
from fastapi import FastAPI, Request |
|
from fastapi.middleware.cors import CORSMiddleware |
|
import logging |
|
import json |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
app = FastAPI() |
|
|
|
|
|
app.add_middleware( |
|
CORSMiddleware, |
|
allow_origins=["*"], |
|
allow_credentials=True, |
|
allow_methods=["*"], |
|
allow_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_data = { |
|
"method": request.method, |
|
"url": str(request.url), |
|
"headers": dict(request.headers), |
|
"query_params": dict(request.query_params), |
|
"client_host": request.client.host, |
|
} |
|
|
|
try: |
|
|
|
body = await request.body() |
|
if body: |
|
try: |
|
|
|
json_body = json.loads(body.decode()) |
|
log_data["body"] = json_body |
|
except json.JSONDecodeError: |
|
|
|
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"} |