-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfastapi_integration.py
More file actions
440 lines (347 loc) · 13.3 KB
/
Copy pathfastapi_integration.py
File metadata and controls
440 lines (347 loc) · 13.3 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
"""
FastAPI Integration Example for VibeCoding Logger
This example demonstrates how to integrate VibeCoding Logger with FastAPI
applications for enhanced API logging and debugging.
"""
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.middleware.base import BaseHTTPMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional, Dict, Any
import time
import uuid
import logging
from vibelogger import create_file_logger
from vibelogger.handlers import setup_vibe_logging, VibeLoggerAdapter
from vibelogger.formatters import create_structured_logger
# Initialize VibeCoding Logger
vibe_logger = create_file_logger("fastapi_app")
api_logger = setup_vibe_logging(vibe_logger, "fastapi_app")
# Create FastAPI app
app = FastAPI(title="VibeCoding FastAPI Example")
# Pydantic models
class UserCreate(BaseModel):
name: str
email: str
class UserResponse(BaseModel):
id: str
name: str
email: str
class ErrorResponse(BaseModel):
error: str
correlation_id: Optional[str] = None
# Middleware for request logging and correlation tracking
class VibeLoggingMiddleware(BaseHTTPMiddleware):
"""Middleware to add VibeCoding context to all requests."""
def __init__(self, app):
super().__init__(app)
self.logger = create_structured_logger("fastapi_middleware", vibe_logger)
async def dispatch(self, request: Request, call_next):
# Generate correlation ID
correlation_id = str(uuid.uuid4())
request.state.correlation_id = correlation_id
request.state.start_time = time.time()
# Add correlation context
self.logger.add_context(
correlation_id=correlation_id,
path=request.url.path,
method=request.method,
client_ip=request.client.host if request.client else None,
user_agent=request.headers.get("user-agent", "")[:100]
)
# Log request start
with self.logger.operation_context("http_request"):
self.logger.info(
f"Started {request.method} {request.url.path}",
query_params=dict(request.query_params),
headers={k: v for k, v in request.headers.items()
if k.lower() not in ['authorization', 'cookie']}
)
try:
# Process request
response = await call_next(request)
# Log successful response
duration = (time.time() - request.state.start_time) * 1000
self.logger.performance(
"http_request",
duration_ms=duration,
status_code=response.status_code,
response_size=len(response.body) if hasattr(response, 'body') else 0
)
return response
except Exception as e:
# Log request failure
duration = (time.time() - request.state.start_time) * 1000
self.logger.failure(
f"Request failed: {str(e)}",
duration_ms=duration,
error_type=type(e).__name__,
ai_todo=f"Analyze {request.method} {request.url.path} failures"
)
raise
# Add middleware
app.add_middleware(VibeLoggingMiddleware)
# Dependency to get correlation ID
def get_correlation_id(request: Request) -> str:
"""Dependency to extract correlation ID from request."""
return getattr(request.state, 'correlation_id', str(uuid.uuid4()))
# Dependency to get structured logger for endpoint
def get_endpoint_logger(request: Request) -> 'StructuredLogger':
"""Dependency to get a configured logger for the endpoint."""
logger = create_structured_logger("fastapi_endpoint", vibe_logger)
# Add request context
correlation_id = getattr(request.state, 'correlation_id', None)
if correlation_id:
logger.add_context(correlation_id=correlation_id)
return logger
# API Endpoints
@app.get("/health")
async def health_check(
logger: 'StructuredLogger' = Depends(get_endpoint_logger)
):
"""Health check endpoint with logging."""
with logger.operation_context("health_check"):
logger.info("Health check requested")
# Simulate health checks
services_status = {
"database": "healthy",
"cache": "healthy",
"external_api": "healthy"
}
logger.success(
"Health check completed",
services_status=services_status
)
return {"status": "healthy", "services": services_status}
@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(
user_id: str,
logger: 'StructuredLogger' = Depends(get_endpoint_logger),
correlation_id: str = Depends(get_correlation_id)
):
"""Get user by ID with enhanced logging."""
with logger.operation_context("fetch_user"):
logger.info(
f"Fetching user profile for ID: {user_id}",
user_id=user_id
)
try:
# Simulate user lookup
user_data = await _get_user_from_db(user_id, logger)
logger.success(
"User profile retrieved successfully",
user_id=user_id,
profile_fields=list(user_data.keys())
)
return UserResponse(**user_data)
except ValueError as e:
logger.failure(
f"Invalid user ID: {user_id}",
user_id=user_id,
error_type="validation_error",
ai_todo="Analyze user ID validation patterns"
)
raise HTTPException(
status_code=400,
detail={
"error": "Invalid user ID",
"correlation_id": correlation_id
}
)
except Exception as e:
logger.failure(
f"Unexpected error fetching user: {str(e)}",
user_id=user_id,
error_details=str(e),
ai_todo="Investigate root cause of user fetch failures"
)
raise HTTPException(
status_code=500,
detail={
"error": "Internal server error",
"correlation_id": correlation_id
}
)
@app.post("/users", response_model=UserResponse)
async def create_user(
user_data: UserCreate,
logger: 'StructuredLogger' = Depends(get_endpoint_logger),
correlation_id: str = Depends(get_correlation_id)
):
"""Create new user with comprehensive logging."""
with logger.operation_context("create_user"):
logger.info(
"Creating new user",
user_email=user_data.email,
user_name=user_data.name
)
try:
# Validate user data
await _validate_user_data(user_data, logger)
# Create user
created_user = await _create_user_in_db(user_data, logger)
logger.success(
"User created successfully",
user_id=created_user["id"],
user_email=created_user["email"]
)
return UserResponse(**created_user)
except ValueError as e:
logger.failure(
f"User validation failed: {str(e)}",
user_data=user_data.dict(),
error_type="validation_error",
ai_todo="Analyze user validation failures and improve validation rules"
)
raise HTTPException(
status_code=422,
detail={
"error": str(e),
"correlation_id": correlation_id
}
)
except Exception as e:
logger.failure(
f"User creation failed: {str(e)}",
user_data=user_data.dict(),
error_details=str(e),
ai_todo="Investigate user creation failures and suggest improvements"
)
raise HTTPException(
status_code=500,
detail={
"error": "Failed to create user",
"correlation_id": correlation_id
}
)
# Helper functions with logging
async def _get_user_from_db(user_id: str, logger) -> Dict[str, Any]:
"""Simulate database user lookup."""
logger.debug(f"Querying database for user {user_id}")
# Simulate various scenarios
if user_id == "invalid":
raise ValueError("Invalid user ID format")
elif user_id == "999":
raise Exception("Database connection timeout")
elif user_id == "404":
raise HTTPException(status_code=404, detail="User not found")
# Simulate database query
await _simulate_db_query(50, logger) # 50ms query
return {
"id": user_id,
"name": f"User {user_id}",
"email": f"user{user_id}@example.com"
}
async def _validate_user_data(user_data: UserCreate, logger) -> None:
"""Validate user data with logging."""
logger.debug("Validating user data", user_email=user_data.email)
if "@" not in user_data.email:
raise ValueError("Invalid email format")
if len(user_data.name) < 2:
raise ValueError("Name must be at least 2 characters")
# Simulate additional validation
await _simulate_db_query(10, logger) # Email uniqueness check
logger.debug("User data validation passed")
async def _create_user_in_db(user_data: UserCreate, logger) -> Dict[str, Any]:
"""Simulate user creation in database."""
logger.debug("Creating user in database")
# Simulate database insertion
await _simulate_db_query(100, logger) # 100ms insert
user_id = str(uuid.uuid4())
logger.debug(f"User created with ID: {user_id}")
return {
"id": user_id,
"name": user_data.name,
"email": user_data.email
}
async def _simulate_db_query(duration_ms: int, logger) -> None:
"""Simulate database query with performance logging."""
import asyncio
start_time = time.time()
await asyncio.sleep(duration_ms / 1000) # Convert to seconds
actual_duration = (time.time() - start_time) * 1000
logger.metric("db_query_duration", actual_duration, "ms")
# Exception handlers with VibeCoding logging
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""Handle HTTP exceptions with logging."""
correlation_id = getattr(request.state, 'correlation_id', str(uuid.uuid4()))
api_logger.vibe_warning(
operation="http_exception",
message=f"HTTP {exc.status_code}: {exc.detail}",
context={
"status_code": exc.status_code,
"detail": exc.detail,
"path": request.url.path,
"method": request.method,
"correlation_id": correlation_id
}
)
return JSONResponse(
status_code=exc.status_code,
content={
"error": exc.detail,
"correlation_id": correlation_id
}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
"""Handle unexpected exceptions with logging."""
correlation_id = getattr(request.state, 'correlation_id', str(uuid.uuid4()))
api_logger.vibe_exception(
operation="unhandled_exception",
message=f"Unhandled exception: {str(exc)}",
context={
"exception_type": type(exc).__name__,
"path": request.url.path,
"method": request.method,
"correlation_id": correlation_id
},
ai_todo="Investigate unhandled exception and add proper error handling"
)
return JSONResponse(
status_code=500,
content={
"error": "Internal server error",
"correlation_id": correlation_id
}
)
# Startup and shutdown events with logging
@app.on_event("startup")
async def startup_event():
"""Application startup with logging."""
api_logger.vibe_info(
operation="app_startup",
message="FastAPI application starting up",
context={
"app_title": app.title,
"docs_url": "/docs"
}
)
@app.on_event("shutdown")
async def shutdown_event():
"""Application shutdown with logging."""
api_logger.vibe_info(
operation="app_shutdown",
message="FastAPI application shutting down"
)
# Run the application
if __name__ == "__main__":
import uvicorn
# Configure uvicorn logging to use VibeCoding
uvicorn_logger = setup_vibe_logging(vibe_logger, "uvicorn")
uvicorn_logger.vibe_info(
operation="server_start",
message="Starting FastAPI server with VibeCoding logging",
context={
"host": "127.0.0.1",
"port": 8000
}
)
uvicorn.run(
"fastapi_integration:app",
host="127.0.0.1",
port=8000,
reload=True,
log_config=None # Disable default logging to use our VibeCoding setup
)