Bytt till klassbaserad lösning för globala varabler

This commit is contained in:
Joakim Persson
2024-07-27 23:49:23 +02:00
parent 5245e53954
commit 807a766a63
+24 -24
View File
@@ -2,36 +2,36 @@
# imported to more than one other module. The rational for defining these things here
# is that it is easier to avoid circular imports when they are defined in a central location.
import logging
global log_level # Remember, in Python globals are only global in the module it is defined in
log_level = 'INFO' # Default logging level if not specified in config file
def configure_logging(level=log_level):
class GlobalState:
"""
Set up logging for the project. This is the root logger instance.
All child loggers inherit from this logger.
This class holds various variables and methods which are accessible across
different modules in the Python project using the Singleton design pattern.
This ensures that only one instance of the class is created and shared among
all modules, preventing circular imports and providing a centralized location
for managing shared resources.
"""
numeric_level = getattr(logging, level.upper()) # Convert string to numeric level
logger = logging.getLogger() # Get the root logger
logger.setLevel(numeric_level)
_instance = None # Private class attribute to hold the single instance of the class
def __new__(cls):
if cls._instance is None:
cls._instance = super(GlobalState, cls).__new__(cls)
cls._instance.log_level = 'INFO' # Default logging level
cls._instance.logger = logging.getLogger(__name__) # Get logger for the caller module
handler = logging.StreamHandler() # Or other handler (FileHandler for logs to file)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
cls._instance.logger.addHandler(handler)
return cls._instance
# To be removed?
# def set_local_logger(log_instance):
# """
# Configure logging based on the global variable log_level
# Logging is controlled by integer values, where DEBUG < INFO < WARNING < ERROR < CRITICAL.
# To turn off logging completely, set numeric_log_level to at least CRITICAL + 1.
# """
# global log_level
# numeric_log_level = getattr(logging, log_level, None)
# if not isinstance(numeric_log_level, int):
# raise ValueError('Invalid log level: %s' % log_level)
# log_instance.basicConfig(level=numeric_log_level) # Set the root logger level to the configured level
# log_instance.info('Current log level set to {}'.format(log_instance.getLogger().getEffectiveLevel())) # Example usage of the logger
def configure_logging(self, level=None):
"""Set up logging for the project."""
if level is None:
level = self.log_level
numeric_level = getattr(logging, level.upper()) # Convert string to numeric level
self.logger.setLevel(numeric_level)
def set_log_level(self, level):
"""Set the logging level."""
self.log_level = level
self.configure_logging()