11# -*- encoding: utf-8 -*-
2+ import atexit
23import logging
34import threading
45import time
@@ -28,6 +29,23 @@ class LoggerFactory:
2829 # Memory optimization settings
2930 _max_loggers = 100 # Maximum number of cached loggers
3031 _logger_ttl = 3600 # Logger TTL in seconds (1 hour)
32+ _initialized = False # Flag to track if memory limits have been initialized
33+ _atexit_registered = False # Flag to track if atexit cleanup is registered
34+
35+ @classmethod
36+ def _ensure_initialized (cls ) -> None :
37+ """Ensure memory limits are initialized from settings on first use."""
38+ if not cls ._initialized :
39+ from pythonLogs .settings import get_log_settings
40+ settings = get_log_settings ()
41+ cls ._max_loggers = settings .max_loggers
42+ cls ._logger_ttl = settings .logger_ttl_seconds
43+ cls ._initialized = True
44+
45+ # Register atexit cleanup on first use
46+ if not cls ._atexit_registered :
47+ atexit .register (cls ._atexit_cleanup )
48+ cls ._atexit_registered = True
3149
3250 @classmethod
3351 def get_or_create_logger (
@@ -54,6 +72,9 @@ def get_or_create_logger(
5472
5573 # Thread-safe check-and-create operation
5674 with cls ._registry_lock :
75+ # Initialize memory limits from settings on first use
76+ cls ._ensure_initialized ()
77+
5778 # Clean up expired loggers first
5879 cls ._cleanup_expired_loggers ()
5980
@@ -114,7 +135,7 @@ def _enforce_size_limit(cls) -> None:
114135
115136 @classmethod
116137 def set_memory_limits (cls , max_loggers : int = 100 , ttl_seconds : int = 3600 ) -> None :
117- """Configure memory management limits for the logger registry.
138+ """Configure memory management limits for the logger registry at runtime .
118139
119140 Args:
120141 max_loggers: Maximum number of cached loggers
@@ -123,10 +144,20 @@ def set_memory_limits(cls, max_loggers: int = 100, ttl_seconds: int = 3600) -> N
123144 with cls ._registry_lock :
124145 cls ._max_loggers = max_loggers
125146 cls ._logger_ttl = ttl_seconds
147+ cls ._initialized = True # Mark as manually configured
126148 # Clean up immediately with new settings
127149 cls ._cleanup_expired_loggers ()
128150 cls ._enforce_size_limit ()
129151
152+ @classmethod
153+ def _atexit_cleanup (cls ) -> None :
154+ """Cleanup function registered with atexit to ensure proper resource cleanup."""
155+ try :
156+ cls .clear_registry ()
157+ except Exception :
158+ # Silently ignore exceptions during shutdown cleanup
159+ pass
160+
130161 @staticmethod
131162 def _cleanup_logger (logger : logging .Logger ) -> None :
132163 """Clean up logger resources by closing all handlers."""
0 commit comments