Skip to content

Commit

Permalink
Fix logging middleware exception handling
Browse files Browse the repository at this point in the history
Signed-off-by: jamshale <[email protected]>
  • Loading branch information
jamshale committed Sep 18, 2023
1 parent 136314c commit 4a896a3
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions oidc-controller/api/main.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# import api.core.logconfig
import logging
import logging.config

import traceback
import structlog
import os
import time
import uuid
from pathlib import Path
from fastapi import status as http_status

import uvicorn
from api.core.config import settings
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
from fastapi.responses import HTMLResponse
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware

from .routers import acapy_handler, oidc, presentation_request, well_known_oid_config
Expand Down Expand Up @@ -90,14 +90,24 @@ async def logging_middleware(request: Request, call_next) -> Response:
start_time = time.time()
try:
response: Response = await call_next(request)
return response
finally:
process_time = time.time() - start_time
logger.info(
"processed a request",
status_code=response.status_code,
process_time=process_time,
)
return response
# If we have a response object, log the details
if 'response' in locals():
logger.info("processed a request",status_code=response.status_code,process_time=process_time)
# Otherwise, extract the exception from traceback
else:
logger.info("failed to process a request", status_code=500, process_time=process_time)

if os.environ.get("LOG_WITH_JSON") is True:
logger.error(traceback.format_exc())

base_error_message = f"Failed to execute: {request.method}: {request.url}"
extracted_error = traceback.format_exc().splitlines()[-1].split(": ")[1:][0]
return JSONResponse(
status_code=http_status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"message": f"{base_error_message}", "detail": extracted_error})


@app.on_event("startup")
Expand Down

0 comments on commit 4a896a3

Please sign in to comment.