import logging import sys from pathlib import Path from logging.handlers import TimedRotatingFileHandler from core.config import get_settings import asyncio from typing import Coroutine settings = get_settings() def safe_create_task(coro: Coroutine, name: str = "background_task") -> asyncio.Task: """ Fire-and-forget an async task with automatic error logging. Prevents silent failures in un-awaited tasks. """ task = asyncio.create_task(coro) def handle_result(t: asyncio.Task): try: t.result() except asyncio.CancelledError: pass except Exception as e: logging.getLogger("safe_task").error(f"❌ Background task '{name}' failed: {str(e)}", exc_info=True) task.add_done_callback(handle_result) return task # Ensure logs directory exists LOGS_DIR = Path(settings.effective_log_dir) LOGS_DIR.mkdir(parents=True, exist_ok=True) # Standard logging format used by all handlers LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" # Filter to suppress frequent health check logs in production to stay within cloud log quotas class HealthCheckFilter(logging.Filter): def filter(self, record): return "/health" not in record.getMessage() def setup_logging(): """ Configure global logging settings for the application. """ log_level = logging.DEBUG if settings.DEBUG else logging.INFO # Root logger configuration root_logger = logging.getLogger() root_logger.setLevel(log_level) # Remove existing handlers to avoid duplicates if root_logger.hasHandlers(): root_logger.handlers.clear() # 1. Console Handler console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(logging.Formatter(LOG_FORMAT)) # Add health check filter to console handler if not in DEBUG if not settings.DEBUG: console_handler.addFilter(HealthCheckFilter()) root_logger.addHandler(console_handler) # 2. File Handler (Timed Rotating - Daily) # We include the PID in the filename in production to prevent race conditions # when multiple workers attempt to rotate the same file at midnight. import os log_filename = "app.log" if settings.DEBUG else f"app.{os.getpid()}.log" file_handler = TimedRotatingFileHandler( LOGS_DIR / log_filename, when="midnight", interval=1, backupCount=30, # Keep 30 days of logs encoding="utf-8" ) file_handler.setFormatter(logging.Formatter(LOG_FORMAT)) root_logger.addHandler(file_handler) # 3. Suppress noisy third-party libraries if not in DEBUG if not settings.DEBUG: # Keep uvicorn.access at INFO but the filter will catch /health noise logging.getLogger("uvicorn.access").setLevel(logging.INFO) logging.getLogger("uvicorn.access").addFilter(HealthCheckFilter()) # Suppress heavy debug noise from core libraries logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING) logging.getLogger("httpx").setLevel(logging.WARNING) logging.getLogger("langchain_ollama").setLevel(logging.INFO) logging.getLogger("arq").setLevel(logging.INFO) # Prevent double logging logging.getLogger("uvicorn.access").propagate = False logging.getLogger("uvicorn.error").propagate = False def get_logger(name: str): """ Utility to get a logger instance for a specific module. """ return logging.getLogger(name)