|
| 1 | +"""Logging configuration using loguru with category-based control.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import sys |
| 6 | +from enum import Flag, auto |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +from loguru import logger |
| 10 | + |
| 11 | + |
| 12 | +class LogCategory(Flag): |
| 13 | + """Bit flags for logging categories. |
| 14 | +
|
| 15 | + Allows combining multiple categories. |
| 16 | + """ |
| 17 | + |
| 18 | + NONE = 0 |
| 19 | + REQUESTS = auto() # HTTP request/response logging |
| 20 | + AUTH = auto() # Authentication, login, token operations |
| 21 | + DATABASE = auto() # Database CRUD operations |
| 22 | + EMAIL = auto() # Email sending operations |
| 23 | + ERRORS = auto() # Error conditions (always recommended) |
| 24 | + ADMIN = auto() # Admin panel operations |
| 25 | + API_KEYS = auto() # API key operations |
| 26 | + ALL = REQUESTS | AUTH | DATABASE | EMAIL | ERRORS | ADMIN | API_KEYS |
| 27 | + |
| 28 | + |
| 29 | +class LogConfig: |
| 30 | + """Logging configuration from environment variables.""" |
| 31 | + |
| 32 | + def __init__(self) -> None: |
| 33 | + """Initialize logging configuration from settings.""" |
| 34 | + # Import here to avoid circular dependency |
| 35 | + from app.config.settings import get_settings # noqa: PLC0415 |
| 36 | + |
| 37 | + settings = get_settings() |
| 38 | + |
| 39 | + # Get configuration from .env |
| 40 | + self.log_path = Path(getattr(settings, "log_path", "./logs")) |
| 41 | + self.log_level = getattr(settings, "log_level", "INFO") |
| 42 | + self.log_rotation = getattr(settings, "log_rotation", "1 day") |
| 43 | + self.log_retention = getattr(settings, "log_retention", "30 days") |
| 44 | + self.log_compression = getattr(settings, "log_compression", "zip") |
| 45 | + self.log_filename = getattr(settings, "log_filename", "api.log") |
| 46 | + self.console_enabled = getattr(settings, "log_console_enabled", False) |
| 47 | + |
| 48 | + # Validate filename doesn't contain path separators |
| 49 | + if "/" in self.log_filename or "\\" in self.log_filename: |
| 50 | + msg = ( |
| 51 | + "log_filename cannot contain path separators. " |
| 52 | + "Use log_path to set the directory." |
| 53 | + ) |
| 54 | + raise ValueError(msg) |
| 55 | + |
| 56 | + # Parse enabled categories (comma-separated string or ALL) |
| 57 | + categories_str = getattr(settings, "log_categories", "ALL") |
| 58 | + self.enabled_categories = self._parse_categories(categories_str) |
| 59 | + |
| 60 | + def _parse_categories(self, categories_str: str) -> LogCategory: |
| 61 | + """Parse comma-separated category string into LogCategory flags.""" |
| 62 | + if categories_str.upper() == "ALL": |
| 63 | + return LogCategory.ALL |
| 64 | + if categories_str.upper() == "NONE": |
| 65 | + return LogCategory.NONE |
| 66 | + |
| 67 | + result = LogCategory.NONE |
| 68 | + for cat_str in categories_str.split(","): |
| 69 | + cat_name = cat_str.strip().upper() |
| 70 | + if hasattr(LogCategory, cat_name): |
| 71 | + result |= getattr(LogCategory, cat_name) |
| 72 | + return result |
| 73 | + |
| 74 | + def is_enabled(self, category: LogCategory) -> bool: |
| 75 | + """Check if a logging category is enabled.""" |
| 76 | + return bool(self.enabled_categories & category) |
| 77 | + |
| 78 | + |
| 79 | +def setup_logging() -> LogConfig: |
| 80 | + """Configure loguru with rotation, retention, and formatting.""" |
| 81 | + config = LogConfig() |
| 82 | + |
| 83 | + # Remove default handler |
| 84 | + logger.remove() |
| 85 | + |
| 86 | + # Add console handler only if enabled |
| 87 | + if config.console_enabled: |
| 88 | + logger.add( |
| 89 | + sys.stderr, |
| 90 | + format="<level>{level: <8}</level> <level>{message}</level>", |
| 91 | + level=config.log_level, |
| 92 | + colorize=True, |
| 93 | + ) |
| 94 | + |
| 95 | + # Add file handler with rotation - more detail for file logs |
| 96 | + log_file = config.log_path / config.log_filename |
| 97 | + config.log_path.mkdir(parents=True, exist_ok=True) |
| 98 | + |
| 99 | + logger.add( |
| 100 | + str(log_file), |
| 101 | + format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {message}", |
| 102 | + level=config.log_level, |
| 103 | + rotation=config.log_rotation, |
| 104 | + retention=config.log_retention, |
| 105 | + compression=config.log_compression, |
| 106 | + enqueue=True, # Async logging |
| 107 | + ) |
| 108 | + |
| 109 | + return config |
| 110 | + |
| 111 | + |
| 112 | +# Global logger instance - lazy initialization to avoid circular imports |
| 113 | +_log_config: LogConfig | None = None |
| 114 | + |
| 115 | + |
| 116 | +def get_log_config() -> LogConfig: |
| 117 | + """Get or initialize the logging configuration.""" |
| 118 | + global _log_config # noqa: PLW0603 |
| 119 | + if _log_config is None: |
| 120 | + _log_config = setup_logging() |
| 121 | + return _log_config |
| 122 | + |
| 123 | + |
| 124 | +# For backwards compatibility, create a property-like object |
| 125 | +class _LogConfigProxy: |
| 126 | + """Proxy object that lazily initializes log config.""" |
| 127 | + |
| 128 | + def is_enabled(self, category: LogCategory) -> bool: |
| 129 | + """Check if a logging category is enabled.""" |
| 130 | + return get_log_config().is_enabled(category) |
| 131 | + |
| 132 | + |
| 133 | +log_config = _LogConfigProxy() |
0 commit comments