feat(logging): load dotenv early and improve logging config

This commit is contained in:
Phlogi
2025-08-26 16:55:00 +02:00
parent c54a441228
commit da982e44b8
2 changed files with 21 additions and 15 deletions

31
app.py
View File

@@ -12,16 +12,20 @@ import sys
import redis
import socket
from urllib.parse import urlparse
from dotenv import load_dotenv
load_dotenv()
# Define a mapping from string log levels to logging constants
LOG_LEVELS = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
"NOTSET": logging.NOTSET,
}
# Parse log level from environment as early as possible, default to INFO for visibility
log_level_str = os.getenv("LOG_LEVEL", "WARNING").upper()
log_level = getattr(logging, log_level_str, logging.INFO)
# Set up a very basic logging config immediately, so early logs (including import/migration errors) are visible
logging.basicConfig(
level=log_level,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
stream=sys.stderr,
)
# Run DB migrations as early as possible, before importing any routers that may touch DBs
try:
@@ -37,10 +41,6 @@ except Exception as e:
)
sys.exit(1)
# Get log level from environment variable, default to INFO
log_level_str = os.getenv("LOG_LEVEL", "WARNING").upper()
log_level = LOG_LEVELS.get(log_level_str, logging.INFO)
# Apply process umask from environment as early as possible
_umask_value = os.getenv("UMASK")
if _umask_value:
@@ -139,6 +139,7 @@ def setup_logging():
"uvicorn", # General Uvicorn logger
"uvicorn.access", # Uvicorn access logs
"uvicorn.error", # Uvicorn error logs
"spotizerr",
]:
logger = logging.getLogger(logger_name)
logger.setLevel(log_level)
@@ -146,7 +147,7 @@ def setup_logging():
# if access_log=False is used in uvicorn.run, and to ensure our middleware handles it.
logger.propagate = False if logger_name == "uvicorn.access" else True
logging.info("Logging system initialized")
logger.info("Logging system initialized")
def check_redis_connection():
@@ -197,6 +198,8 @@ async def lifespan(app: FastAPI):
"""Handle application startup and shutdown"""
# Startup
setup_logging()
effective_level = logging.getLevelName(log_level)
logging.getLogger(__name__).info(f"Logging system fully initialized (lifespan startup). Effective log level: {effective_level}")
# Run migrations before initializing services
try: