File size: 2,810 Bytes
48322a4 68e3836 48322a4 68e3836 48322a4 68e3836 56d51a5 68e3836 56d51a5 68e3836 48322a4 68e3836 48322a4 56d51a5 48322a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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]
) |