import logging import sys import os import certifi from datetime import datetime from pymongo import MongoClient # Fetch MongoDB credentials directly to avoid circular imports with db_connection.py MONGO_URI = os.getenv("MONGO_URI", "mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.5.1") DB_NAME = os.getenv("DB_NAME", "Rankmate") class MongoHandler(logging.Handler): def __init__(self): super().__init__() self.client = None self.collection = None try: # Smart TLS Handling: Don't use TLS/SSL for local development to prevent Handshake errors if "127.0.0.1" in MONGO_URI or "localhost" in MONGO_URI: self.client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=2000) else: self.client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=2000) self.db = self.client[DB_NAME] self.collection = self.db["logs"] except Exception as e: # Fallback print if the database connection fails, so we don't crash the app print(f"⚠️ [LOGGER] Failed to initialize MongoDB logging: {e}") def emit(self, record): if self.collection is not None: try: # Structure the log as a clean, queryable JSON document log_document = { "timestamp": datetime.fromtimestamp(record.created), "level": record.levelname, "module": record.module, "line": record.lineno, "message": record.getMessage() } self.collection.insert_one(log_document) except Exception: # FAIL-SAFE TRIGGERED: If insert fails (e.g., DB goes down or connection is refused), # disable MongoDB logging permanently for this session to stop terminal spam. self.collection = None print(f"⚠️ [LOGGER] MongoDB connection refused. Falling back to terminal-only logging.") # Standard file setup for local development LOG_FILE = f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log" log_dir = os.path.join(os.getcwd(), "logs") os.makedirs(log_dir, exist_ok=True) LOG_FILE_PATH = os.path.join(log_dir, LOG_FILE) # Configure logging handlers file_handler = logging.FileHandler(LOG_FILE_PATH) stream_handler = logging.StreamHandler(sys.stdout) mongo_handler = MongoHandler() # Apply the global configuration logging.basicConfig( level=logging.INFO, format="[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s", handlers=[file_handler, stream_handler, mongo_handler] )