File size: 1,821 Bytes
1d9ae63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdf9fc1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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"}