Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/332 fix middleware [2.0] #338

Merged
merged 4 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions oidc-controller/api/core/logger_util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import structlog
import time


from typing import Callable, Any


Expand Down
41 changes: 27 additions & 14 deletions oidc-controller/api/main.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
# import api.core.logconfig
import traceback
import structlog
import os
import time
import uuid
from pathlib import Path

import structlog
import uvicorn
from api.core.config import settings
from api.core.oidc.provider import init_provider
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import Response
from fastapi.exceptions import HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi import status as http_status

from .clientConfigurations.router import router as client_config_router
from .db.session import get_db, init_db
from .routers import acapy_handler, oidc, presentation_request, well_known_oid_config
from .routers.socketio import sio_app
from .verificationConfigs.router import router as ver_configs_router
from .clientConfigurations.router import router as client_config_router
from .db.session import init_db, get_db
from .routers.socketio import sio_app
from api.core.models import GenericErrorMessage
from api.core.oidc.provider import init_provider

logger: structlog.typing.FilteringBoundLogger = structlog.getLogger(__name__)

Expand Down Expand Up @@ -73,9 +78,7 @@ def get_application() -> FastAPI:

@app.middleware("http")
async def logging_middleware(request: Request, call_next) -> Response:
# clear the threadlocal context
structlog.threadlocal.clear_threadlocal()
# bind threadlocal
esune marked this conversation as resolved.
Show resolved Hide resolved
structlog.threadlocal.bind_threadlocal(
logger="uvicorn.access",
request_id=str(uuid.uuid4()),
Expand All @@ -86,14 +89,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, log and return a 500 response
else:
logger.info("failed to process a request", status_code=http_status.HTTP_500_INTERNAL_SERVER_ERROR, process_time=process_time)

# Need to explicitly log the traceback as json here. Not clear as to why.
if os.environ.get("LOG_WITH_JSON", True) is True:
logger.error(traceback.format_exc())

raise HTTPException(
status_code=http_status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal Server Error",
)


@app.on_event("startup")
Expand All @@ -118,4 +131,4 @@ def main():

if __name__ == "__main__":
logger.info("main.")
uvicorn.run(app, host="0.0.0.0", port=5100)
uvicorn.run(app, host="0.0.0.0", port=5100)