background tasks

This commit is contained in:
rUv committed 2025-06-13 23:38:46 +00:00
1 parent e1afe444d4
commit 9811b78b5b
215 files changed
+39531 -2917

No files matched your search

@@ -0,0 +1,14 @@
"""Utils package for Hello World application"""
from .logger import Logger, get_logger
from .decorators import timer, validate_args, retry, memoize, singleton, deprecated
__all__ = [
'Logger',
'get_logger',
'timer',
'validate_args',
'retry',
'memoize',
'singleton',
'deprecated'
]
@@ -0,0 +1,130 @@
"""
Utility decorators for Hello World application
"""
import functools
import time
from typing import Callable, Any
from utils.logger import get_logger
def timer(func: Callable) -> Callable:
"""Decorator to measure function execution time"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger = get_logger()
start_time = time.time()
logger.debug(f"Starting {func.__name__}...")
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
logger.debug(
f"Completed {func.__name__} in {execution_time:.4f} seconds"
)
return result
return wrapper
def validate_args(func: Callable) -> Callable:
"""Decorator to validate function arguments"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger = get_logger()
# Log function call with arguments
logger.debug(
f"Calling {func.__name__} with args={args[1:]} kwargs={kwargs}"
)
# Basic validation example
if 'name' in kwargs and kwargs['name']:
if not isinstance(kwargs['name'], str):
raise TypeError(f"Name must be a string, got {type(kwargs['name'])}")
if len(kwargs['name']) > 50:
raise ValueError("Name must be 50 characters or less")
return func(*args, **kwargs)
return wrapper
def retry(max_attempts: int = 3, delay: float = 1.0):
"""Decorator to retry function on failure"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger = get_logger()
attempts = 0
last_error = None
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
last_error = e
if attempts < max_attempts:
logger.warning(
f"Attempt {attempts} failed for {func.__name__}: {str(e)}. "
f"Retrying in {delay} seconds..."
)
time.sleep(delay)
else:
logger.error(
f"All {max_attempts} attempts failed for {func.__name__}"
)
raise last_error
return wrapper
return decorator
def memoize(func: Callable) -> Callable:
"""Decorator to cache function results"""
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Create a cache key from arguments
cache_key = str(args) + str(sorted(kwargs.items()))
if cache_key not in cache:
cache[cache_key] = func(*args, **kwargs)
return cache[cache_key]
# Add method to clear cache
wrapper.clear_cache = lambda: cache.clear()
return wrapper
def singleton(cls):
"""Decorator to make a class a singleton"""
instances = {}
@functools.wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
def deprecated(message: str = ""):
"""Decorator to mark functions as deprecated"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger = get_logger()
warning_msg = f"{func.__name__} is deprecated"
if message:
warning_msg += f": {message}"
logger.warning(warning_msg)
return func(*args, **kwargs)
return wrapper
return decorator
@@ -0,0 +1,108 @@
"""
Logger module for Hello World application
"""
import logging
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional
class ColoredFormatter(logging.Formatter):
"""Custom formatter with color support"""
COLORS = {
'DEBUG': '\033[36m', # Cyan
'INFO': '\033[32m', # Green
'WARNING': '\033[33m', # Yellow
'ERROR': '\033[31m', # Red
'CRITICAL': '\033[35m', # Magenta
}
RESET = '\033[0m'
def __init__(self, fmt: str = None, enable_colors: bool = True):
super().__init__(fmt)
self.enable_colors = enable_colors
def format(self, record):
if self.enable_colors and record.levelname in self.COLORS:
record.levelname = (
f"{self.COLORS[record.levelname]}"
f"{record.levelname}"
f"{self.RESET}"
)
return super().format(record)
class Logger:
"""Custom logger class for Hello World application"""
def __init__(self, level: str = "INFO", log_file: Optional[str] = None):
self.logger = logging.getLogger("HelloWorld")
self.logger.setLevel(getattr(logging, level.upper()))
# Remove existing handlers
self.logger.handlers.clear()
# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_formatter = ColoredFormatter(
fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
enable_colors=sys.stdout.isatty()
)
console_handler.setFormatter(console_formatter)
self.logger.addHandler(console_handler)
# File handler (optional)
if log_file:
file_handler = logging.FileHandler(log_file)
file_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
file_handler.setFormatter(file_formatter)
self.logger.addHandler(file_handler)
def debug(self, message: str, *args, **kwargs):
"""Log debug message"""
self.logger.debug(message, *args, **kwargs)
def info(self, message: str, *args, **kwargs):
"""Log info message"""
self.logger.info(message, *args, **kwargs)
def warning(self, message: str, *args, **kwargs):
"""Log warning message"""
self.logger.warning(message, *args, **kwargs)
def error(self, message: str, *args, **kwargs):
"""Log error message"""
self.logger.error(message, *args, **kwargs)
def critical(self, message: str, *args, **kwargs):
"""Log critical message"""
self.logger.critical(message, *args, **kwargs)
def log_separator(self, char: str = "-", length: int = 50):
"""Log a separator line"""
self.info(char * length)
def log_banner(self, message: str, char: str = "="):
"""Log a banner message"""
padding = 2
banner_length = len(message) + (padding * 2)
self.info(char * banner_length)
self.info(f"{char}{' ' * padding}{message}{' ' * padding}{char}")
self.info(char * banner_length)
# Singleton logger instance
_logger_instance = None
def get_logger(level: str = "INFO", log_file: Optional[str] = None) -> Logger:
"""Get or create logger instance"""
global _logger_instance
if _logger_instance is None:
_logger_instance = Logger(level, log_file)
return _logger_instance