Buckets:

download
raw
6.35 kB
# SPDX-License-Identifier: MIT
"""
A comprehensive logging tool for the application.
"""
import sys
from pathlib import Path
from loguru import logger
from fastlib.config._log_config import LogConfig
from fastlib.config.manager import ConfigManager
class Logger:
"""
Enhanced logging tool with loguru-compatible ``str.format`` messages.
"""
_instances: dict[str, "Logger"] = {}
_config: LogConfig | None = None
_is_configured: bool = False
@classmethod
def initialize(cls) -> "Logger":
"""
Initialize the logging system.
Returns:
Logger instance
"""
if not cls._is_configured:
# Load configuration first
cls._config = cls._get_config()
# Create and configure the logger
instance = cls.get_instance()
cls._is_configured = True
return instance
return cls.get_instance()
@classmethod
def _get_config(cls) -> LogConfig:
"""Lazy load configuration."""
if cls._config is None:
cls._config = ConfigManager.get_log_config()
return cls._config
@classmethod
def get_instance(
cls,
name: str | None = None,
) -> "Logger":
"""
Get or create a named logger instance.
Args:
name: Logger instance name
Returns:
Logger instance
"""
# Ensure config is loaded
if cls._config is None:
cls._config = cls._get_config()
if not name:
name = cls._config.app_name
if name not in cls._instances:
cls._instances[name] = cls(name)
return cls._instances[name]
def __init__(self, name: str):
"""Initialize the Logger with optional overrides."""
self.name = name
# Get configuration
self._config = self._get_config()
# Only setup logging once globally
if not self.__class__._is_configured:
self._setup_logging()
def _setup_logging(self) -> None:
"""Configure loguru logger with handlers based on configuration."""
# Remove default handler
logger.remove()
config = self._config
# Create log directory
Path(config.log_dir).mkdir(parents=True, exist_ok=True)
# Console handler
if config.enable_console_log:
logger.add(
sys.stderr,
format=self._get_format_string(),
level=config.log_level,
colorize=True,
)
# Main file handler
rotation = config.max_file_size or config.log_rotation
logger.add(
str(config.log_file_path),
format=self._get_format_string(),
level=config.log_level,
rotation=rotation,
retention=config.log_retention,
compression="zip",
serialize=config.enable_json_logs,
enqueue=config.enable_async,
)
# Error log handler - only add if log level is not ERROR or CRITICAL
if config.log_level not in ["ERROR", "CRITICAL"]:
logger.add(
str(config.error_log_file_path),
format=self._get_format_string(),
level="ERROR",
rotation=config.error_log_rotation,
retention=config.error_log_retention,
compression="zip",
serialize=config.enable_json_logs,
enqueue=config.enable_async,
)
def _get_format_string(self) -> str:
"""Get the log format string."""
config = self._config
if config.enable_json_logs:
# JSON logs don't need format string
return "{message}"
return config.default_format
def _bound(self):
"""Return a loguru logger bound to this instance.
``opt(depth=1)`` skips this wrapper so ``{name}:{function}:{line}``
points at the caller, matching loguru's own logging methods.
"""
return logger.bind(logger_name=self.name).opt(depth=1)
def bind(self, **kwargs):
"""Bind extra fields onto the loguru ``extra`` dict, like ``logger.bind()``."""
return logger.bind(logger_name=self.name, **kwargs)
def trace(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``TRACE``."""
self._bound().trace(message, *args, **kwargs)
def debug(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``DEBUG``."""
self._bound().debug(message, *args, **kwargs)
def info(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``INFO``."""
self._bound().info(message, *args, **kwargs)
def success(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``SUCCESS``."""
self._bound().success(message, *args, **kwargs)
def warning(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``WARNING``."""
self._bound().warning(message, *args, **kwargs)
def error(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``ERROR``."""
self._bound().error(message, *args, **kwargs)
def critical(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with severity ``CRITICAL``."""
self._bound().critical(message, *args, **kwargs)
def exception(self, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` as ``ERROR`` with traceback."""
self._bound().exception(message, *args, **kwargs)
def log(self, level, message: str, *args, **kwargs) -> None:
"""Log ``message.format(*args, **kwargs)`` with the given severity."""
self._bound().log(level, message, *args, **kwargs)
@classmethod
def reset(cls) -> None:
"""Reset all logger instances and configuration (useful for testing)."""
cls._instances.clear()
cls._config = None
cls._is_configured = False
logger.remove()

Xet Storage Details

Size:
6.35 kB
·
Xet hash:
ed3256d5b68d83e0ea4ed0ddb105e1f24373575ae47c16a4768195caf68463e8

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.