feat(logging): add debug logging configuration and environment variable support

This commit is contained in:
2026-06-13 11:07:18 +08:00
parent 67ff3e2e4a
commit ac2a0f7c15
7 changed files with 36 additions and 8 deletions
+3
View File
@@ -1,3 +1,6 @@
# Set to true to enable debug logging and SQL echo
DEBUG=false
# OpenAI-compatible API configuration
LLM_BASE_URL=http://localhost:11434/v1
LLM_MODEL=llama
+23 -4
View File
@@ -21,18 +21,34 @@ from backend.routes.users import router as users_router
logger = logging.getLogger("agent_alpha")
def _configure_logging() -> None:
def _configure_logging(*, debug: bool = False) -> None:
"""Configure standard logging to match FastAPI/uvicorn's log format."""
handler = logging.StreamHandler()
handler.setFormatter(DefaultFormatter("%(levelprefix)s %(message)s"))
logging.getLogger("agent_alpha").addHandler(handler)
logging.getLogger("agent_alpha").setLevel(logging.INFO)
logging.getLogger("agent_alpha").propagate = False
logger = logging.getLogger("agent_alpha")
logger.addHandler(handler)
logger.setLevel(logging.DEBUG if debug else logging.INFO)
logger.propagate = False
_configure_logging()
def _reconfigure_logging(*, debug: bool) -> None:
"""Adjust all agent_alpha loggers to the requested level.
Called at startup so the ``debug`` setting from ``.env`` is reflected
even though the module-level logger was configured at import time.
"""
level = logging.DEBUG if debug else logging.INFO
for name in ("agent_alpha", "backend", "backend.core", "backend.routes"):
logging.getLogger(name).setLevel(level)
# Also enable debug for uvicorn when debug mode is on.
if debug:
logging.getLogger("uvicorn.access").setLevel(logging.DEBUG)
logging.getLogger("uvicorn.error").setLevel(logging.DEBUG)
class AppBuilder:
"""Builds and configures the FastAPI application with DI wiring.
@@ -78,6 +94,9 @@ class AppBuilder:
@asynccontextmanager
async def _lifespan(self, _app: FastAPI):
"""Startup / shutdown lifecycle."""
# Apply debug log level from settings (may override module-level default).
_reconfigure_logging(debug=self._settings.debug)
logger.info("Agent Alpha backend starting")
# Create database tables if they don't exist.
+3 -3
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import logfire
from pydantic_ai import Agent
from pydantic_ai.capabilities import MCP, Thinking, ToolSearch, WebSearch
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.models.openai import OpenAIResponsesModel
from pydantic_ai.providers.openai import OpenAIProvider
from pydantic_ai_harness import CodeMode
@@ -32,7 +32,7 @@ class AgentService:
def __init__(self, settings: Settings) -> None:
self._settings = settings
self._agent: Agent | None = None
self._model: OpenAIModel | None = None
self._model: OpenAIResponsesModel | None = None
# ── Lifecycle ──────────────────────────────────────────────────────────
@@ -48,7 +48,7 @@ class AgentService:
except Exception:
pass # Logfire is optional — don't crash if it fails
self._model = OpenAIModel(
self._model = OpenAIResponsesModel(
self._settings.llm_model,
provider=OpenAIProvider(
base_url=self._settings.llm_base_url,
+2
View File
@@ -20,6 +20,8 @@ class Settings(BaseSettings):
extra="ignore",
)
debug: bool = False
llm_base_url: str = "http://localhost:11434/v1"
llm_model: str = "llama"
llm_api_key: str = ""
+1 -1
View File
@@ -52,7 +52,7 @@ _engine = create_async_engine(
settings.database_url,
pool_size=5,
max_overflow=10,
echo=False,
echo=settings.debug,
)
_session_factory = async_sessionmaker(
+3
View File
@@ -9,12 +9,15 @@ import uvicorn
def main() -> None:
"""Start the Uvicorn development server."""
from backend.core.config import settings
uvicorn.run(
"backend.app:create_app",
host="0.0.0.0",
port=8000,
reload=True,
factory=True,
log_level="debug" if settings.debug else "info",
)
+1
View File
@@ -23,6 +23,7 @@ services:
environment:
# NOTE: URLs are hardcoded to container service names so that the
# host .env file (with localhost URLs) does NOT override them.
- DEBUG=${DEBUG:-false}
- LLM_BASE_URL=${LLM_BASE_URL:-http://host.docker.internal:8011/v1}
- LLM_MODEL=${LLM_MODEL:-llama}
- DATABASE_URL=${DATABASE_URL:-postgresql+asyncpg://agent_alpha:agent_alpha@postgres:5432/agent_alpha}