Add logging configuration and middleware for improved request tracking
This commit is contained in:
@@ -16,6 +16,11 @@ class Settings(BaseSettings):
|
||||
RELOAD: bool = True
|
||||
LOG_LEVEL: str = "info"
|
||||
|
||||
LOG_FILE: str = "logs/app.log"
|
||||
LOG_MAX_SIZE: int = 10 * 1024 * 1024
|
||||
LOG_BACKUP_COUNT: int = 5
|
||||
LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
DATABASE_URL: str = "sqlite+aiosqlite:///data/soundboard.db"
|
||||
DATABASE_ECHO: bool = False
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from sqlmodel import SQLModel
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
from app.models import ( # noqa: F401
|
||||
plan,
|
||||
playlist,
|
||||
@@ -23,10 +24,12 @@ engine: AsyncEngine = create_async_engine(
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
logger = get_logger(__name__)
|
||||
async with AsyncSession(engine) as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("Database session error: %s", e)
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
@@ -34,5 +37,12 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(SQLModel.metadata.create_all)
|
||||
logger = get_logger(__name__)
|
||||
try:
|
||||
logger.info("Initializing database tables")
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(SQLModel.metadata.create_all)
|
||||
logger.info("Database tables created successfully")
|
||||
except Exception as e:
|
||||
logger.exception("Failed to initialize database: %s", e)
|
||||
raise
|
||||
|
||||
37
app/core/logging.py
Normal file
37
app/core/logging.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import logging
|
||||
import logging.handlers
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
def setup_logging() -> None:
|
||||
"""Set up logging configuration."""
|
||||
log_dir = Path(settings.LOG_FILE).parent
|
||||
log_dir.mkdir(exist_ok=True)
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(settings.LOG_LEVEL.upper())
|
||||
|
||||
if logger.handlers:
|
||||
logger.handlers.clear()
|
||||
|
||||
formatter = logging.Formatter(settings.LOG_FORMAT)
|
||||
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
settings.LOG_FILE,
|
||||
maxBytes=settings.LOG_MAX_SIZE,
|
||||
backupCount=settings.LOG_BACKUP_COUNT,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setFormatter(formatter)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
"""Get a logger instance."""
|
||||
return logging.getLogger(name)
|
||||
Reference in New Issue
Block a user