Spaces:
3SCError404
/
Paused

nexus / core /logging.py
dushyantsingh0
backend stabilization
ab8d6bc
Raw History Blame Contribute Delete
2.65 kB
import logging
import sys
from pathlib import Path
from logging.handlers import TimedRotatingFileHandler
from core.config import get_settings
settings = get_settings()
# Ensure logs directory exists
LOGS_DIR = Path("logs")
LOGS_DIR.mkdir(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)
file_handler = TimedRotatingFileHandler(
LOGS_DIR / "app.log",
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)