diff --git a/pyproject.toml b/pyproject.toml index de517fc..e2b88d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "factuges-document-signing-service" -version = "0.2.7" +version = "0.3.1" description = "FastAPI service for signing PDF documents using external secret managers" requires-python = ">=3.11" diff --git a/src/signing_service/main.py b/src/signing_service/main.py index fa8b5c6..7e7af09 100644 --- a/src/signing_service/main.py +++ b/src/signing_service/main.py @@ -1,9 +1,13 @@ -from fastapi import FastAPI +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from starlette.middleware.base import BaseHTTPMiddleware + from dotenv import load_dotenv from pathlib import Path from datetime import datetime from dateutil import tz + from signing_service.application.settings.container import get_settings from signing_service.application.settings.setup_logger import create_logger from signing_service.api.routes.sign_document import router as sign_router @@ -43,13 +47,55 @@ logger.info("Infisical project ID: %s", settings.infisical_project_id) logger.info("Infisical environment: %s", settings.infisical_env_slug) logger.info("") + +async def http_exception_handler(request: Request, exc: HTTPException): + logger.error( + "HTTPException %s %s | status=%s | detail=%s", + request.method, + request.url.path, + exc.status_code, + exc.detail, + ) + + return JSONResponse( + status_code=exc.status_code, + content={"detail": exc.detail}, + ) + + +# Define logging middleware +class LoggingMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + # Log request details + client_ip = request.client.host + method = request.method + url = request.url.path + + logger.info(f"Request: {method} {url} from {client_ip}") + + # Process the request + response = await call_next(request) + + # Log response details + status_code = response.status_code + logger.info( + f"Response: {method} {url} returned {status_code} to {client_ip}") + + return response + + app = FastAPI(title="FactuGES Document Signing Service", version=version) + app.add_event_handler("startup", lambda: logger.info( "Application startup complete")) + app.add_event_handler("shutdown", lambda: logger.info( "Application shutdown complete")) -app.add_exception_handler(Exception, lambda request, - exc: logger.error(f"Unhandled exception: {exc}")) + +app.add_exception_handler(HTTPException, http_exception_handler) + +# Add middleware to the app +app.add_middleware(LoggingMiddleware) # Register routers