added logging middleware to log to stdout

This commit is contained in:
Linus Vogel 2026-02-02 21:22:03 +01:00
parent cea5a8df94
commit b37f78b961
4 changed files with 20 additions and 3 deletions

View File

@ -1,5 +1,8 @@
# load config so everything else can work
from http.server import BaseHTTPRequestHandler
from pillar_tool.db.base_model import as_dict
from pillar_tool.middleware.logging import request_logging_middleware
from pillar_tool.schemas import HostCreateParams
from pillar_tool.util import load_config, config
load_config()
@ -59,6 +62,7 @@ def on_general_error(request: Request, exc: Exception):
app = FastAPI()
app.add_middleware(AuthenticationMiddleware, backend=BasicAuthBackend(), on_error=on_auth_error)
app.add_middleware(BaseHTTPMiddleware, dispatch=db_connection_middleware)
app.add_middleware(BaseHTTPMiddleware, dispatch=request_logging_middleware)
app.exception_handler(Exception)(on_general_error)

View File

@ -32,8 +32,7 @@ class BasicAuthBackend(AuthenticationBackend):
except (ValueError, UnicodeDecodeError, binascii.Error):
raise AuthenticationError('Invalid basic auth credentials')
username, what, password = decoded.partition(":")
print(username, what, password)
username, _this_should_be_a_colon, password = decoded.partition(":")
user = verify_user(conn.state.db, username, password)
if user is None:

View File

@ -7,7 +7,6 @@ from pillar_tool.db.database import get_connection
async def db_connection_middleware(request: Request, call_next: Callable) -> Response:
session = get_connection()
print("test 1")
request.state.db = session
try:

View File

@ -0,0 +1,15 @@
from datetime import datetime, timezone
from typing import Callable
from starlette.requests import Request
from starlette.responses import Response
async def request_logging_middleware(request: Request, call_next: Callable) -> Response:
timestamp = datetime.now(timezone.utc).astimezone()
response: Response = await call_next(request)
print(f"{timestamp.isoformat()} {request.method} {request.url.path} {response.status_code} {response.headers.get("content-length")} \"{request.headers.get("user-agent") or '-'}\"")
return response