aboutsummaryrefslogtreecommitdiff
path: root/kennel/main.py
blob: 183fb64c8a9e975fe78669db0516b0d51f4a9501 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import uuid

import structlog
from fastapi import FastAPI, Request, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI(
    servers = [
        {"url": "https://kennel.hatecomputers.club", "description": "prod"}
    ]
)
logger = structlog.get_logger()


@app.middleware("http")
async def logger_middleware(request: Request, call_next):
    structlog.contextvars.clear_contextvars()
    structlog.contextvars.bind_contextvars(
        path=request.url.path,
        method=request.method,
        client_host=request.client.host,
        request_id=str(uuid.uuid4()),
    )
    response = await call_next(request)

    structlog.contextvars.bind_contextvars(
        status_code=response.status_code,
    )

    # Exclude /healthcheck endpoint from producing logs
    if request.url.path != "/healthcheck":
        if 400 <= response.status_code < 500:
            logger.warn("Client error")
        elif response.status_code >= 500:
            logger.error("Server error")
        else:
            logger.info("OK")

    return response

templates = Jinja2Templates(directory="templates")


@app.get("/healthcheck")
async def healthcheck():
    return Response("hello")


@app.get("/")
async def read_main(request: Request):
    return templates.TemplateResponse(
        request=request, name="index.html"
    )

app.mount("/static", StaticFiles(directory = "static"), name = "static")