Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /TrueSelph_jvspatial /jvspatial /logging /__init__.py
| """Logging system for jvspatial applications. | |
| This module provides: | |
| 1. Structured logging for console output (JVSpatialLogger) | |
| 2. Database logging service for automatic persistence (BaseLoggingService) | |
| 3. Custom log levels support (AUDIT, SECURITY, CUSTOM, etc.) | |
| 4. Configuration utilities for both systems | |
| The logging system is designed to be extensible - implementations can extend | |
| the BaseLoggingService to add custom functionality and use custom log levels | |
| for domain-specific categorization. | |
| """ | |
| import logging | |
| import sys | |
| from typing import Any, List, Optional | |
| # Import error logging components | |
| from jvspatial.logging.config import get_logging_config, initialize_logging_database | |
| from jvspatial.logging.custom_levels import ( | |
| CUSTOM_LEVEL_NUMBER, | |
| add_custom_log_level, | |
| get_custom_levels, | |
| is_custom_level, | |
| ) | |
| from jvspatial.logging.handler import ( | |
| DBLogHandler, | |
| install_db_log_handler, | |
| install_exception_hook, | |
| ) | |
| from jvspatial.logging.models import DBLog | |
| from jvspatial.logging.service import BaseLoggingService, get_logging_service | |
| try: | |
| import structlog | |
| STRUCTLOG_AVAILABLE = True | |
| except ImportError: | |
| STRUCTLOG_AVAILABLE = False | |
| class JVSpatialLogger: | |
| """Enhanced logger with structured logging capabilities. | |
| Provides structured logging with context and performance tracking, | |
| falling back to standard logging if structlog is not available. | |
| """ | |
| def __init__(self, name: str, enable_structured: bool = True): | |
| """Initialize the logger. | |
| Args: | |
| name: Logger name | |
| enable_structured: Whether to enable structured logging | |
| """ | |
| self.name = name | |
| self.enable_structured = enable_structured and STRUCTLOG_AVAILABLE | |
| if self.enable_structured: | |
| self.logger = structlog.get_logger(name) | |
| else: | |
| self.logger = logging.getLogger(name) | |
| def info(self, message: str, **context: Any) -> None: | |
| """Log info message with structured context. | |
| Args: | |
| message: Log message | |
| **context: Additional context data | |
| """ | |
| if self.enable_structured: | |
| self.logger.info(message, **context) | |
| else: | |
| formatted_context = " ".join([f"{k}={v}" for k, v in context.items()]) | |
| self.logger.info(f"{message} {formatted_context}".strip()) | |
| def error(self, message: str, **context: Any) -> None: | |
| """Log error message with structured context. | |
| Args: | |
| message: Log message | |
| **context: Additional context data | |
| """ | |
| if self.enable_structured: | |
| self.logger.error(message, **context) | |
| else: | |
| formatted_context = " ".join([f"{k}={v}" for k, v in context.items()]) | |
| self.logger.error(f"{message} {formatted_context}".strip()) | |
| def warning(self, message: str, **context: Any) -> None: | |
| """Log warning message with structured context. | |
| Args: | |
| message: Log message | |
| **context: Additional context data | |
| """ | |
| if self.enable_structured: | |
| self.logger.warning(message, **context) | |
| else: | |
| formatted_context = " ".join([f"{k}={v}" for k, v in context.items()]) | |
| self.logger.warning(f"{message} {formatted_context}".strip()) | |
| def debug(self, message: str, **context: Any) -> None: | |
| """Log debug message with structured context. | |
| Args: | |
| message: Log message | |
| **context: Additional context data | |
| """ | |
| if self.enable_structured: | |
| self.logger.debug(message, **context) | |
| else: | |
| formatted_context = " ".join([f"{k}={v}" for k, v in context.items()]) | |
| self.logger.debug(f"{message} {formatted_context}".strip()) | |
| def critical(self, message: str, **context: Any) -> None: | |
| """Log critical message with structured context. | |
| Args: | |
| message: Log message | |
| **context: Additional context data | |
| """ | |
| if self.enable_structured: | |
| self.logger.critical(message, **context) | |
| else: | |
| formatted_context = " ".join([f"{k}={v}" for k, v in context.items()]) | |
| self.logger.critical(f"{message} {formatted_context}".strip()) | |
| def custom(self, message: str, **context: Any) -> None: | |
| """Log custom level message with structured context. | |
| Args: | |
| message: Log message | |
| **context: Additional context data | |
| """ | |
| # Import here to avoid circular dependency | |
| from jvspatial.logging.custom_levels import CUSTOM_LEVEL_NUMBER | |
| if self.enable_structured: | |
| # structlog doesn't have a custom method, use log() with level | |
| self.logger.log(CUSTOM_LEVEL_NUMBER, message, **context) | |
| else: | |
| formatted_context = " ".join([f"{k}={v}" for k, v in context.items()]) | |
| self.logger.custom(f"{message} {formatted_context}".strip()) | |
| class StructuredLoggingConfig: | |
| """Configuration for structured logging system.""" | |
| def __init__(self, enable_json: bool = True, enable_colors: bool = True): | |
| """Initialize structured logging configuration. | |
| Args: | |
| enable_json: Whether to use JSON formatting | |
| enable_colors: Whether to enable colored output | |
| """ | |
| self.enable_json = enable_json | |
| self.enable_colors = enable_colors | |
| def configure(self) -> None: | |
| """Configure structured logging system.""" | |
| if not STRUCTLOG_AVAILABLE: | |
| self._configure_fallback() | |
| return | |
| processors = [ | |
| structlog.stdlib.filter_by_level, | |
| structlog.stdlib.add_logger_name, | |
| structlog.stdlib.add_log_level, | |
| structlog.stdlib.PositionalArgumentsFormatter(), | |
| structlog.processors.TimeStamper(fmt="iso"), | |
| structlog.processors.StackInfoRenderer(), | |
| structlog.processors.format_exc_info, | |
| structlog.processors.UnicodeDecoder(), | |
| ] | |
| if self.enable_colors and not self.enable_json: | |
| processors.append(structlog.dev.ConsoleRenderer(colors=True)) | |
| elif self.enable_json: | |
| processors.append(structlog.processors.JSONRenderer()) | |
| else: | |
| processors.append(structlog.dev.ConsoleRenderer(colors=False)) | |
| structlog.configure( | |
| processors=processors, | |
| context_class=dict, | |
| logger_factory=structlog.stdlib.LoggerFactory(), | |
| wrapper_class=structlog.stdlib.BoundLogger, | |
| cache_logger_on_first_use=True, | |
| ) | |
| def _configure_fallback(self) -> None: | |
| """Configure fallback logging when structlog is not available.""" | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| stream=sys.stdout, | |
| ) | |
| class PerformanceLogger: | |
| """Logger specifically for performance metrics.""" | |
| def __init__(self, logger_name: str = "jvspatial.performance"): | |
| """Initialize performance logger. | |
| Args: | |
| logger_name: Name for the performance logger | |
| """ | |
| self.logger = JVSpatialLogger(logger_name) | |
| def log_operation( | |
| self, operation_name: str, duration: float, **metrics: Any | |
| ) -> None: | |
| """Log performance metrics for an operation. | |
| Args: | |
| operation_name: Name of the operation | |
| duration: Duration in seconds | |
| **metrics: Additional performance metrics | |
| """ | |
| self.logger.info( | |
| f"Operation completed: {operation_name}", | |
| operation=operation_name, | |
| duration=duration, | |
| duration_ms=duration * 1000, | |
| **metrics, | |
| ) | |
| def log_database_operation( | |
| self, operation: str, collection: str, duration: float, **metrics: Any | |
| ) -> None: | |
| """Log database operation performance. | |
| Args: | |
| operation: Database operation type | |
| collection: Collection name | |
| duration: Duration in seconds | |
| **metrics: Additional metrics | |
| """ | |
| self.logger.info( | |
| f"Database operation: {operation}", | |
| operation=operation, | |
| collection=collection, | |
| duration=duration, | |
| duration_ms=duration * 1000, | |
| **metrics, | |
| ) | |
| def log_cache_operation( | |
| self, operation: str, key: str, hit: bool, duration: float | |
| ) -> None: | |
| """Log cache operation performance. | |
| Args: | |
| operation: Cache operation type | |
| key: Cache key | |
| hit: Whether it was a cache hit | |
| duration: Duration in seconds | |
| """ | |
| self.logger.info( | |
| f"Cache operation: {operation}", | |
| operation=operation, | |
| key=key, | |
| hit=hit, | |
| duration=duration, | |
| duration_ms=duration * 1000, | |
| ) | |
| class SecurityLogger: | |
| """Logger specifically for security events.""" | |
| def __init__(self, logger_name: str = "jvspatial.security"): | |
| """Initialize security logger. | |
| Args: | |
| logger_name: Name for the security logger | |
| """ | |
| self.logger = JVSpatialLogger(logger_name) | |
| def log_auth_attempt( | |
| self, username: str, success: bool, client_ip: str, **context: Any | |
| ) -> None: | |
| """Log authentication attempt. | |
| Args: | |
| username: Username attempting authentication | |
| success: Whether authentication was successful | |
| client_ip: Client IP address | |
| **context: Additional context | |
| """ | |
| self.logger.info( | |
| f"Authentication attempt: {username}", | |
| username=username, | |
| success=success, | |
| client_ip=client_ip, | |
| event_type="auth_attempt", | |
| **context, | |
| ) | |
| def log_rate_limit( | |
| self, client_ip: str, user_agent: str = "", **context: Any | |
| ) -> None: | |
| """Log rate limiting event. | |
| Args: | |
| client_ip: Client IP address | |
| user_agent: Client user agent | |
| **context: Additional context | |
| """ | |
| self.logger.warning( | |
| f"Rate limit exceeded: {client_ip}", | |
| client_ip=client_ip, | |
| user_agent=user_agent, | |
| event_type="rate_limit", | |
| **context, | |
| ) | |
| def log_brute_force(self, username: str, client_ip: str, **context: Any) -> None: | |
| """Log brute force attack attempt. | |
| Args: | |
| username: Username under attack | |
| client_ip: Client IP address | |
| **context: Additional context | |
| """ | |
| self.logger.warning( | |
| f"Brute force attempt detected: {username}", | |
| username=username, | |
| client_ip=client_ip, | |
| event_type="brute_force", | |
| **context, | |
| ) | |
| def get_logger(name: str) -> JVSpatialLogger: | |
| """Get a structured logger instance. | |
| Args: | |
| name: Logger name | |
| Returns: | |
| JVSpatialLogger instance | |
| """ | |
| return JVSpatialLogger(name) | |
| def configure_logging(enable_json: bool = True, enable_colors: bool = True) -> None: | |
| """Configure structured logging system. | |
| Args: | |
| enable_json: Whether to use JSON formatting | |
| enable_colors: Whether to enable colored output | |
| """ | |
| config = StructuredLoggingConfig( | |
| enable_json=enable_json, enable_colors=enable_colors | |
| ) | |
| config.configure() | |
| # --------------------------------------------------------------------------- # | |
| # Standard console logging (shared across jvspatial and consumer applications) | |
| # --------------------------------------------------------------------------- # | |
| def configure_standard_logging( | |
| level: str = "INFO", | |
| enable_colors: bool = True, | |
| preserve_handler_class_names: Optional[List[str]] = None, | |
| ) -> None: | |
| """Configure a consistent console logger with optional colored level names. | |
| This sets a root handler with a stable format and optionally colors only the | |
| level name (message/body remains plain for readability). | |
| Args: | |
| level: Logging level name (e.g., "INFO", "DEBUG"). | |
| enable_colors: Whether to colorize the level name. | |
| preserve_handler_class_names: Optional list of handler class names to preserve | |
| when clearing and reconfiguring logging. This allows consumers to preserve | |
| custom handlers (e.g., database logging handlers) across reconfigurations. | |
| """ | |
| class _LevelColorFormatter(logging.Formatter): | |
| _LEVEL_COLORS = { | |
| "DEBUG": "\033[36m", # Cyan | |
| "INFO": "\033[32m", # Green | |
| "WARNING": "\033[33m", # Yellow | |
| "ERROR": "\033[31m", # Red | |
| "CRITICAL": "\033[41m\033[97m", # White on red background | |
| } | |
| _RESET = "\033[0m" | |
| def format(self, record: logging.LogRecord) -> str: # type: ignore[override] | |
| color = ( | |
| self._LEVEL_COLORS.get(record.levelname, "") if enable_colors else "" | |
| ) | |
| original_levelname = record.levelname | |
| if color: | |
| record.levelname = f"{color}{record.levelname}{self._RESET}" | |
| try: | |
| return super().format(record) | |
| finally: | |
| record.levelname = original_levelname | |
| root = logging.getLogger() | |
| # Preserve specified handlers before clearing | |
| preserved_handlers = [] | |
| if preserve_handler_class_names: | |
| for handler in root.handlers: | |
| handler_class_name = type(handler).__name__ | |
| if handler_class_name in preserve_handler_class_names: | |
| preserved_handlers.append(handler) | |
| root.handlers.clear() | |
| # Re-add preserved handlers | |
| for handler in preserved_handlers: | |
| root.addHandler(handler) | |
| handler = logging.StreamHandler(stream=sys.stdout) | |
| handler.setFormatter( | |
| _LevelColorFormatter( | |
| fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", | |
| datefmt="%H:%M:%S", | |
| ) | |
| ) | |
| root.addHandler(handler) | |
| root.setLevel(getattr(logging, level.upper(), logging.INFO)) | |
| # Global loggers | |
| performance_logger = PerformanceLogger() | |
| security_logger = SecurityLogger() | |
| __all__ = [ | |
| # Error logging service (database persistence) | |
| "BaseLoggingService", | |
| "get_logging_service", | |
| "DBLog", | |
| "get_logging_config", | |
| "initialize_logging_database", | |
| "DBLogHandler", | |
| "install_db_log_handler", | |
| "install_exception_hook", | |
| # Custom log levels | |
| "add_custom_log_level", | |
| "get_custom_levels", | |
| "is_custom_level", | |
| "CUSTOM_LEVEL_NUMBER", | |
| # Structured console logging | |
| "JVSpatialLogger", | |
| "StructuredLoggingConfig", | |
| "PerformanceLogger", | |
| "SecurityLogger", | |
| "get_logger", | |
| "configure_logging", | |
| "configure_standard_logging", | |
| "performance_logger", | |
| "security_logger", | |
| ] | |
Xet Storage Details
- Size:
- 15 kB
- Xet hash:
- 0fc3ddf2e82f430d83412163b9a1edd8e1aa6e06f61d96d6494e9a476433bc49
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.