Skip to content
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
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ POSTGRES_USER = <DB_USER>
POSTGRES_PASSWORD = <DB_PASSWORD>
POSTGRES_DB = <DB_NAME>
DATABASE_URL = <DB_URL>
DEBUG = <True/False>

DEBUG = <True/False>

SLOW_REQUEST_THRESHOLD = <seconds: float>
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ env:
POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
DEBUG: ${{ secrets.DEBUG }}
SLOW_REQUEST_THRESHOLD: ${{ secrets.SLOW_REQUEST_THRESHOLD }}

jobs:
test:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ env:
POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
DEBUG: ${{ secrets.DEBUG }}
SLOW_REQUEST_THRESHOLD: ${{ secrets.SLOW_REQUEST_THRESHOLD }}

jobs:

Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ __pycache__
.pytest_cache
*.db
.env
check-list-docker.md
check-list-docker.md
ideas.md
1 change: 1 addition & 0 deletions app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class Settings(BaseSettings):
POSTGRES_PASSWORD: str
POSTGRES_DB: str
DATABASE_URL: str
SLOW_REQUEST_THRESHOLD: float
DEBUG: bool = True

model_config = ConfigDict(env_file = '.env', case_sensitive = True)
Expand Down
24 changes: 24 additions & 0 deletions app/core/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import sys
from pathlib import Path
from loguru import logger

logger.remove() # removing the old handler to set everything up yourself

log_dir = Path('logs')
log_dir.mkdir(exist_ok = True)

log_format = (
'<green>{time:YYYY-MM-DD HH:mm:ss}</green> | '
'<level>{level: <8}</level> | '
'<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - '
'<level>{message}</level>'
)

logger.add(
sys.stdout,
format = log_format,
level = "DEBUG",
colorize = True
)

__all__ = ["logger"]
29 changes: 29 additions & 0 deletions app/core/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import time
from starlette.middleware.base import BaseHTTPMiddleware
from app.core.logger import logger
from app.core.config import settings


class LoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start_time = time.time()
logger.info(f'-> {request.method} {request.url.path}')
try:
response = await call_next(request)
process_time = time.time() - start_time

if process_time > settings.SLOW_REQUEST_THRESHOLD:
logger.warning(
f"SLOW REQUEST: {request.method} {request.url.path} - "
f"Took {process_time:.2f}s (threshold: {settings.SLOW_REQUEST_THRESHOLD}s)"
)
else:
logger.info(
f'<- {request.method} {request.url.path} - '
f'Status: {response.status_code} - '
f'Process time: {process_time:.2f}s'
)
return response
except Exception as e:
logger.error(f'{request.method} {request.url.path} - Error: {str(e)}')
raise
20 changes: 19 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
from fastapi import FastAPI
import traceback

from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from app.core.database import engine, Base
from app.core.middleware import LoggingMiddleware
from app.api import router
from app.core.logger import logger

@asynccontextmanager
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
logger.info('Application started')
yield

app = FastAPI(lifespan = lifespan)

@app.exception_handler(Exception)
async def global_exeption_handler(request: Request, exc: Exception):
logger.error(
f'Unhandled error on {request.method} {request.url.path}\n'
f'{traceback.format_exc()}'
)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal Server Error."}
)

app.add_middleware(LoggingMiddleware)
app.include_router(router)
4 changes: 4 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,9 @@ docker compose up --build

**You can view the environment variables in the .env.example file.**

**To get logs in file format, use:**

docker compose logs > logs.txt

## License
MIT. You can find it in the root of the project.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ httpcore==1.0.9
httpx==0.28.1
idna==3.18
iniconfig==2.3.0
loguru==0.7.3
packaging==26.2
pluggy==1.6.0
pydantic==2.13.4
Expand Down