fix: Add DB Tracing Configuration
This commit is contained in:
parent
cf9e532d14
commit
577c577316
|
|
@ -4,6 +4,7 @@ from typing import Any, Optional
|
|||
|
||||
import tomllib
|
||||
from dotenv import load_dotenv
|
||||
from pydantic.fields import Field
|
||||
from pydantic_settings import (
|
||||
BaseSettings,
|
||||
PydanticBaseSettingsSource,
|
||||
|
|
@ -50,7 +51,8 @@ class TomlConfigSettingsSource(PydanticBaseSettingsSource):
|
|||
"": "app", # For AppSettings with no prefix
|
||||
}
|
||||
|
||||
def get_field_value(self, field_name: str) -> tuple[Any, str, bool]:
|
||||
def get_field_value(self, field: Field) -> tuple[Any, str, bool]:
|
||||
field_name = field.name
|
||||
# Get the env_prefix from the model config
|
||||
prefix = self.settings_cls.model_config.get("env_prefix", "")
|
||||
if prefix.endswith("_"):
|
||||
|
|
@ -118,6 +120,7 @@ class DBSettings(TomlSettings):
|
|||
POOL_RECYCLE: int = 300 # seconds
|
||||
POOL_USE_LIFO: bool = True
|
||||
SQL_DEBUG: bool = False
|
||||
TRACING: bool = False
|
||||
|
||||
|
||||
class AuthSettings(TomlSettings):
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ from fastapi import Depends
|
|||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .db import SessionLocal, request_context
|
||||
from src.config import settings
|
||||
from src.db import SessionLocal, request_context
|
||||
|
||||
|
||||
async def get_db():
|
||||
|
|
@ -15,7 +16,8 @@ async def get_db():
|
|||
|
||||
db: AsyncSession = SessionLocal()
|
||||
try:
|
||||
await db.execute(text(f"SET application_name = '{context}'"))
|
||||
if settings.DB.TRACING:
|
||||
await db.execute(text(f"SET application_name = '{context}'"))
|
||||
yield db
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
|
|
@ -41,9 +43,10 @@ async def tracked_db(operation_name=None):
|
|||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
await db.execute(
|
||||
text(f"SET application_name = '{context or f'task:{operation_name}'}'")
|
||||
)
|
||||
if settings.DB.TRACING:
|
||||
await db.execute(
|
||||
text(f"SET application_name = '{context or f'task:{operation_name}'}'")
|
||||
)
|
||||
|
||||
yield db
|
||||
# Explicitly end transaction if still open
|
||||
|
|
|
|||
|
|
@ -174,6 +174,8 @@ async def global_exception_handler(request: Request, exc: Exception):
|
|||
|
||||
@app.middleware("http")
|
||||
async def track_request(request: Request, call_next):
|
||||
if not settings.DB.TRACING:
|
||||
return await call_next(request)
|
||||
# Create a request ID that includes endpoint information
|
||||
endpoint = re.sub(r"/[A-Za-z0-9_-]{21}", "", request.url.path).replace("/", "_")
|
||||
request_id = f"{request.method}:{endpoint}:{str(uuid.uuid4())[:8]}"
|
||||
|
|
|
|||
Loading…
Reference in New Issue