Dmitry Beresnev commited on
Commit
7d65cc9
·
1 Parent(s): 90f1c82

fix app to handle exceptions

Browse files
Files changed (1) hide show
  1. app.py +16 -4
app.py CHANGED
@@ -423,10 +423,17 @@ async def log_received_request(request: Request, call_next):
423
  start = time.perf_counter()
424
 
425
  body_text = ""
 
426
  if LOG_REQUEST_BODY:
427
  body_bytes = await request.body()
428
  body_text = _format_body_for_log(request.headers.get("content-type", ""), body_bytes)
429
 
 
 
 
 
 
 
430
  headers = _redact_headers(dict(request.headers))
431
  client_host = request.client.host if request.client else "-"
432
  query = f"?{request.url.query}" if request.url.query else ""
@@ -438,10 +445,15 @@ async def log_received_request(request: Request, call_next):
438
  if body_text:
439
  logger.info(f" body={body_text}")
440
 
441
- response = await call_next(request)
442
- elapsed_ms = (time.perf_counter() - start) * 1000
443
- logger.info(f"⬅️ {request_id} {response.status_code} {elapsed_ms:.1f}ms")
444
- return response
 
 
 
 
 
445
 
446
 
447
  class ModelSwitchRequest(BaseModel):
 
423
  start = time.perf_counter()
424
 
425
  body_text = ""
426
+ body_bytes = b""
427
  if LOG_REQUEST_BODY:
428
  body_bytes = await request.body()
429
  body_text = _format_body_for_log(request.headers.get("content-type", ""), body_bytes)
430
 
431
+ async def receive():
432
+ return {"type": "http.request", "body": body_bytes, "more_body": False}
433
+
434
+ # Recreate request so downstream can read body again
435
+ request = Request(request.scope, receive)
436
+
437
  headers = _redact_headers(dict(request.headers))
438
  client_host = request.client.host if request.client else "-"
439
  query = f"?{request.url.query}" if request.url.query else ""
 
445
  if body_text:
446
  logger.info(f" body={body_text}")
447
 
448
+ try:
449
+ response = await call_next(request)
450
+ elapsed_ms = (time.perf_counter() - start) * 1000
451
+ logger.info(f"⬅️ {request_id} {response.status_code} {elapsed_ms:.1f}ms")
452
+ return response
453
+ except Exception as exc:
454
+ elapsed_ms = (time.perf_counter() - start) * 1000
455
+ logger.error(f"⬅️ {request_id} 500 {elapsed_ms:.1f}ms error={exc}")
456
+ raise
457
 
458
 
459
  class ModelSwitchRequest(BaseModel):