diff --git a/django_logging/management/commands/logs_size_audit.py b/django_logging/management/commands/logs_size_audit.py index d702888..73bffba 100644 --- a/django_logging/management/commands/logs_size_audit.py +++ b/django_logging/management/commands/logs_size_audit.py @@ -5,10 +5,9 @@ from django.conf import settings from django.core.management.base import BaseCommand -from django_logging.constants import DefaultLoggingSettings -from django_logging.constants.config_types import LogDir from django_logging.handlers import EmailHandler from django_logging.management.commands.send_logs import Command as cmd +from django_logging.settings import settings_manager from django_logging.utils.get_conf import ( get_log_dir_size_limit, use_email_notifier_template, @@ -40,10 +39,7 @@ def handle(self, *args: Tuple[Any], **kwargs: Dict[str, Any]) -> None: **kwargs: Keyword arguments passed to the command. """ - default_settings = DefaultLoggingSettings() - log_dir: LogDir = settings.DJANGO_LOGGING.get( - "LOG_DIR", os.path.join(os.getcwd(), default_settings.log_dir) - ) + log_dir = settings_manager.log_dir # Check if log directory exists if not os.path.exists(log_dir): diff --git a/django_logging/settings/__init__.py b/django_logging/settings/__init__.py index e69de29..60d5f22 100644 --- a/django_logging/settings/__init__.py +++ b/django_logging/settings/__init__.py @@ -0,0 +1 @@ +from .manager import settings_manager diff --git a/django_logging/settings/checks.py b/django_logging/settings/checks.py index 0f0c563..200a094 100644 --- a/django_logging/settings/checks.py +++ b/django_logging/settings/checks.py @@ -3,14 +3,7 @@ from django.core.checks import Error, register from django_logging.constants import ALLOWED_FILE_FORMAT_TYPES, DefaultLoggingSettings -from django_logging.utils.get_conf import ( - get_config, - get_log_dir_size_limit, - include_log_iboard, - is_auto_initialization_enabled, - is_initialization_message_enabled, - is_log_sql_queries_enabled, -) +from django_logging.settings import settings_manager from django_logging.validators.config_validators import ( validate_boolean_setting, validate_date_format, @@ -75,15 +68,13 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E """ errors: List[Error] = [] - - log_settings = get_config(extra_info=True) logging_defaults = DefaultLoggingSettings() # Validate LOG_DIR - errors.extend(validate_directory(log_settings.get("log_dir"), "LOG_DIR")) # type: ignore + errors.extend(validate_directory(settings_manager.log_dir, "LOG_DIR")) # Validate LOG_FILE_LEVELS - log_file_levels = log_settings.get("log_levels") + log_file_levels = settings_manager.log_levels errors.extend( validate_log_levels( log_file_levels, "LOG_FILE_LEVELS", logging_defaults.log_levels # type: ignore @@ -91,9 +82,7 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E ) # Validate LOG_FILE_FORMATS - log_file_formats = log_settings.get( - "log_file_formats", logging_defaults.log_file_formats - ) + log_file_formats = settings_manager.log_file_formats if isinstance(log_file_formats, dict): for level, format_option in log_file_formats.items(): if level not in logging_defaults.log_levels: @@ -117,10 +106,9 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E ) # Validate LOG_FILE_FORMAT_TYPES - log_file_format_types = log_settings.get("log_file_format_types", {}) errors.extend( validate_log_file_format_types( - log_file_format_types, + settings_manager.log_file_format_types, "LOG_FILE_FORMAT_TYPES", logging_defaults.log_levels, ALLOWED_FILE_FORMAT_TYPES + ["NORMAL"], @@ -128,64 +116,70 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E ) # Validate EXTRA_LOG_FILES - extra_log_files = log_settings.get("extra_log_files", {}) errors.extend( validate_extra_log_files( - extra_log_files, "EXTRA_LOG_FILES", logging_defaults.log_levels + settings_manager.extra_log_files, + "EXTRA_LOG_FILES", + logging_defaults.log_levels, ) ) # Validate LOG_CONSOLE_FORMAT - log_console_format = log_settings.get("console_format") - errors.extend(validate_format_option(log_console_format, "LOG_CONSOLE_FORMAT")) # type: ignore + errors.extend(validate_format_option(settings_manager.console_format, "LOG_CONSOLE_FORMAT")) # type: ignore # Validate LOG_CONSOLE_LEVEL - log_console_level = log_settings.get("console_level") errors.extend( validate_log_levels( - [log_console_level], "LOG_CONSOLE_LEVEL", logging_defaults.log_levels # type: ignore + [settings_manager.console_level], "LOG_CONSOLE_LEVEL", logging_defaults.log_levels # type: ignore ) ) # Validate LOG_CONSOLE_COLORIZE - log_console_colorize = log_settings.get("colorize_console") errors.extend( - validate_boolean_setting(log_console_colorize, "LOG_CONSOLE_COLORIZE") # type: ignore + validate_boolean_setting(settings_manager.colorize_console, "LOG_CONSOLE_COLORIZE") # type: ignore ) # Validate LOG_DATE_FORMAT - log_date_format = log_settings.get("log_date_format") - errors.extend(validate_date_format(log_date_format, "LOG_DATE_FORMAT")) # type: ignore + errors.extend(validate_date_format(settings_manager.log_date_format, "LOG_DATE_FORMAT")) # type: ignore # Validate INCLUDE_LOG_iBOARD - errors.extend(validate_boolean_setting(include_log_iboard(), "INCLUDE_LOG_iBOARD")) + errors.extend( + validate_boolean_setting( + settings_manager.include_log_iboard, "INCLUDE_LOG_iBOARD" + ) + ) # Validate AUTO_INITIALIZATION_ENABLE errors.extend( validate_boolean_setting( - is_auto_initialization_enabled(), "AUTO_INITIALIZATION_ENABLE" + settings_manager.auto_initialization_enabled, "AUTO_INITIALIZATION_ENABLE" ) ) # Validate INITIALIZATION_MESSAGE_ENABLE errors.extend( validate_boolean_setting( - is_initialization_message_enabled(), "INITIALIZATION_MESSAGE_ENABLE" + settings_manager.initialization_message_enabled, + "INITIALIZATION_MESSAGE_ENABLE", ) ) # Validate LOG_SQL_QUERIES_ENABLE errors.extend( - validate_boolean_setting(is_log_sql_queries_enabled(), "LOG_SQL_QUERIES_ENABLE") + validate_boolean_setting( + settings_manager.log_sql_queries_enabled, "LOG_SQL_QUERIES_ENABLE" + ) ) # Validate LOG_DIR_SIZE_LIMIT errors.extend( - validate_integer_setting(get_log_dir_size_limit(), "LOG_DIR_SIZE_LIMIT") + validate_integer_setting( + settings_manager.log_dir_size_limit, "LOG_DIR_SIZE_LIMIT" + ) ) # Validate LOG_EMAIL_NOTIFIER - log_email_notifier = log_settings.get("log_email_notifier") + log_email_notifier = settings_manager.email_notifier errors.extend(validate_email_notifier(log_email_notifier)) # type: ignore if log_email_notifier.get("ENABLE", False): # type: ignore diff --git a/django_logging/settings/manager.py b/django_logging/settings/manager.py new file mode 100644 index 0000000..925a419 --- /dev/null +++ b/django_logging/settings/manager.py @@ -0,0 +1,134 @@ +import os +from typing import Any, Dict, List, Union + +from django.conf import settings + +from django_logging.constants import DefaultConsoleSettings, DefaultLoggingSettings +from django_logging.constants.config_types import ( + ExtraLogFiles, + FormatOption, + LogDateFormat, + LogDir, + LogEmailNotifier, + LogFileFormats, + LogFileFormatTypes, + LogLevels, + NotifierLogLevels, +) + + +# pylint: disable=too-many-instance-attributes +class SettingsManager: + """Manages DJANGO_LOGGING settings for the Django Logging application. All + configurations are initialized at once and accessible via attributes. + + Attributes: + log_dir (str): The directory where log files are stored. + log_levels (List[str]): List of logging levels (e.g., DEBUG, INFO). + log_file_formats (Dict[str, Union[int, str]]): Log file formats, which can be integers or strings. + log_file_format_types (Dict[str, str]): Format types (e.g., 'json', 'xml', 'flat', 'normal') for each logging level. + extra_log_files (Dict[str, bool]): Boolean values indicating whether separate files (JSON, XML) should be used for each logging level. + console_level (str): The logging level for console output. + console_format (Union[int, str]): The format for console logs, either an integer or a string. + colorize_console (bool): Whether to colorize console logs. + log_date_format (str): The format used for timestamps in logs. + email_notifier (Dict[str, Any]): Configuration for email notifications. + email_notifier_enabled (bool): Whether email notifications are enabled. + email_notifier_log_levels (List[str]): Levels that trigger email notifications. + email_notifier_log_format (Union[int, str]): Log format used in email notifications, either an integer or a format string. + auto_initialization_enabled (bool): Whether auto initialization of logging is enabled. + initialization_message_enabled (bool): Whether to display an initialization message for logging. + log_sql_queries_enabled (bool): Whether to log SQL queries in each request. + log_dir_size_limit (int): The maximum size (in MB) allowed for the log directory. + include_log_iboard (bool): Whether the Logiboard feature is included. + use_email_notifier_template (bool): Whether to use a template for email notifications. + + """ + + def __init__(self) -> None: + """Initializes all settings from the Django settings, falling back to + default values defined in DefaultLoggingSettings and + DefaultConsoleSettings.""" + self.log_settings = getattr(settings, "DJANGO_LOGGING", {}) + if not isinstance(self.log_settings, dict): + raise ValueError("DJANGO_LOGGING must be a dictionary with configs as keys") + + self.default_logging = DefaultLoggingSettings() + self.default_console = DefaultConsoleSettings() + + # Initialize all configuration settings + self.log_dir: LogDir = self.get( + "LOG_DIR", os.path.join(os.getcwd(), self.default_logging.log_dir) + ) + self.log_levels: LogLevels = self.get( + "LOG_FILE_LEVELS", self.default_logging.log_levels + ) + self.log_file_formats: LogFileFormats = self.get( + "LOG_FILE_FORMATS", self.default_logging.log_file_formats + ) + self.log_file_format_types: LogFileFormatTypes = self.get( + "LOG_FILE_FORMAT_TYPES", self.default_logging.log_file_format_types + ) + self.extra_log_files: ExtraLogFiles = self.get( + "EXTRA_LOG_FILES", self.default_logging.extra_log_files + ) + self.console_level: str = self.get( + "LOG_CONSOLE_LEVEL", self.default_console.log_console_level + ) + self.console_format: FormatOption = self.get( + "LOG_CONSOLE_FORMAT", self.default_console.log_console_format + ) + self.colorize_console: bool = self.get( + "LOG_CONSOLE_COLORIZE", self.default_console.log_console_colorize + ) + self.log_date_format: LogDateFormat = self.get( + "LOG_DATE_FORMAT", self.default_logging.log_date_format + ) + self.email_notifier: LogEmailNotifier = self.get( + "LOG_EMAIL_NOTIFIER", self.default_logging.log_email_notifier + ) + self.email_notifier_enabled: bool = self.email_notifier.get("ENABLE", False) + self.email_notifier_log_levels: NotifierLogLevels = [ + "ERROR" if self.email_notifier.get("NOTIFY_ERROR", False) else None, + ("CRITICAL" if self.email_notifier.get("NOTIFY_CRITICAL", False) else None), + ] + self.email_notifier_log_format: FormatOption = self.email_notifier.get( + "LOG_FORMAT", 1 + ) + self.auto_initialization_enabled: bool = self.get( + "AUTO_INITIALIZATION_ENABLE", + self.default_logging.auto_initialization_enable, + ) + self.initialization_message_enabled: bool = self.get( + "INITIALIZATION_MESSAGE_ENABLE", + self.default_logging.initialization_message_enable, + ) + self.log_sql_queries_enabled: bool = self.get( + "LOG_SQL_QUERIES_ENABLE", self.default_logging.log_sql_queries_enable + ) + self.log_dir_size_limit: int = self.get( + "LOG_DIR_SIZE_LIMIT", self.default_logging.log_dir_size_limit + ) + self.include_log_iboard: bool = self.get( + "INCLUDE_LOG_iBOARD", self.default_logging.include_log_iboard + ) + self.use_email_notifier_template: bool = self.email_notifier.get( + "USE_TEMPLATE", True + ) + + def get(self, key: str, default_value: Any) -> Any: + """Retrieves a logging-related setting from the Django settings. If the + setting is not present, returns the provided default value. + + Args: + key (str): The key to look up in the logging settings. + default_value (Any): The default value to return if the key is not found. + + Returns: + Any: The value of the setting or the default value. + + """ + return self.log_settings.get(key, default_value) + + +settings_manager: SettingsManager = SettingsManager() diff --git a/django_logging/tests/commands/test_logs_size_audit.py b/django_logging/tests/commands/test_logs_size_audit.py index 92d554a..d6831bf 100644 --- a/django_logging/tests/commands/test_logs_size_audit.py +++ b/django_logging/tests/commands/test_logs_size_audit.py @@ -73,7 +73,7 @@ def test_command_log_directory_size_exceeds_limit( with patch("os.path.getsize", side_effect=[60 * 1024 * 1024, 50 * 1024 * 1024]): out = StringIO() with patch("django.conf.settings.ADMIN_EMAIL", "admin@example.com"): - with patch("django.conf.settings.DJANGO_LOGGING", {"LOG_DIR_SIZE_LIMIT": 100}): + with patch("django_logging.management.commands.logs_size_audit.settings_manager.log_dir_size_limit", 100): call_command("logs_size_audit", stdout=out) # Verify that the warning email was sent diff --git a/django_logging/tests/fixtures/settings_fixture.py b/django_logging/tests/fixtures/settings_fixture.py index 387705f..b73fd8f 100644 --- a/django_logging/tests/fixtures/settings_fixture.py +++ b/django_logging/tests/fixtures/settings_fixture.py @@ -1,12 +1,13 @@ -from typing import Dict, Generator +from typing import Generator from unittest.mock import patch - import pytest from django.conf import settings +from django_logging.settings.manager import SettingsManager + @pytest.fixture -def mock_settings() -> Generator[Dict, None, None]: +def mock_settings() -> SettingsManager: """ Fixture to mock Django settings. @@ -46,8 +47,10 @@ def mock_settings() -> Generator[Dict, None, None]: }, } } + with patch.object(settings, "DJANGO_LOGGING", mock_settings["DJANGO_LOGGING"]): - yield mock_settings + # Initialize SettingsManager after patching the settings + return SettingsManager() @pytest.fixture diff --git a/django_logging/tests/fixtures/views_fixture.py b/django_logging/tests/fixtures/views_fixture.py index 53f6e03..d1623f8 100644 --- a/django_logging/tests/fixtures/views_fixture.py +++ b/django_logging/tests/fixtures/views_fixture.py @@ -6,7 +6,7 @@ @pytest.fixture -def setup_users(db) -> Dict[str, User]: +def setup_users() -> Dict[str, User]: """ Fixture to create a superuser and a normal user for testing purposes. Returns a dictionary with `superuser` and `non_superuser` keys. diff --git a/django_logging/tests/settings/test_checks.py b/django_logging/tests/settings/test_checks.py index ee59bd6..13438eb 100644 --- a/django_logging/tests/settings/test_checks.py +++ b/django_logging/tests/settings/test_checks.py @@ -6,6 +6,7 @@ from django.conf import settings from django.core.checks import Error +from django_logging.settings import settings_manager from django_logging.settings.checks import check_logging_settings from django_logging.tests.constants import PYTHON_VERSION, PYTHON_VERSION_REASON @@ -61,9 +62,8 @@ def test_invalid_log_dir(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E001_LOG_DIR` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_DIR": 1, - } + settings_manager.log_dir = 1 + errors: List[Error] = check_logging_settings(None) # type: ignore assert any(error.id == "django_logging.E001_LOG_DIR" for error in errors) @@ -78,9 +78,7 @@ def test_invalid_log_file_levels(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E007_LOG_FILE_LEVELS` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_FILE_LEVELS": ["invalid"], - } + settings_manager.log_levels = ["invalid"] errors = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E007_LOG_FILE_LEVELS" for error in errors @@ -98,12 +96,11 @@ def test_invalid_log_file_formats(self, reset_settings: None) -> None: - Errors with the IDs `django_logging.E011_LOG_FILE_FORMATS['DEBUG']` and `django_logging.E019_LOG_FILE_FORMATS` are returned for invalid formats. - An error with the ID `django_logging.E020_LOG_FILE_FORMATS` is returned for invalid type. """ - settings.DJANGO_LOGGING = { - "LOG_FILE_FORMATS": { + settings_manager.log_file_formats = { "DEBUG": "%(levelname)s: %(invalid)s", "invalid": "%(message)s", - }, - } + } + errors: List[Error] = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E011_LOG_FILE_FORMATS['DEBUG']" @@ -113,7 +110,7 @@ def test_invalid_log_file_formats(self, reset_settings: None) -> None: error.id == "django_logging.E019_LOG_FILE_FORMATS" for error in errors ) - settings.DJANGO_LOGGING = {"LOG_FILE_FORMATS": ["invalid type"]} + settings_manager.log_file_formats = ["invalid type"] errors = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E020_LOG_FILE_FORMATS" for error in errors @@ -130,9 +127,8 @@ def test_invalid_log_console_format(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E010_LOG_CONSOLE_FORMAT` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_CONSOLE_FORMAT": "invalid", - } + settings_manager.console_format = "invalid" + errors = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E010_LOG_CONSOLE_FORMAT" for error in errors @@ -149,9 +145,8 @@ def test_invalid_log_console_level(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E006_LOG_CONSOLE_LEVEL` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_CONSOLE_LEVEL": 10, - } + settings_manager.console_level = 10 + errors: List[Error] = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E006_LOG_CONSOLE_LEVEL" for error in errors @@ -168,9 +163,8 @@ def test_invalid_log_console_colorize(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E014_LOG_CONSOLE_COLORIZE` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_CONSOLE_COLORIZE": "not_a_boolean", - } + settings_manager.colorize_console = "not_a_boolean", + errors: List[Error] = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E014_LOG_CONSOLE_COLORIZE" for error in errors @@ -187,9 +181,8 @@ def test_invalid_log_date_format(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E016_LOG_DATE_FORMAT` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_DATE_FORMAT": "%invalid_format", - } + settings_manager.log_date_format = "%invalid_format" + errors: List[Error] = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E016_LOG_DATE_FORMAT" for error in errors @@ -206,9 +199,8 @@ def test_invalid_auto_initialization_enable(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E014_AUTO_INITIALIZATION_ENABLE` is returned. """ - settings.DJANGO_LOGGING = { - "AUTO_INITIALIZATION_ENABLE": "not_a_boolean", - } + settings_manager.auto_initialization_enabled = "not_a_boolean", + errors: List[Error] = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E014_AUTO_INITIALIZATION_ENABLE" @@ -226,9 +218,8 @@ def test_invalid_initialization_message_enable(self, reset_settings: None) -> No ------- - An error with the ID `django_logging.E014_INITIALIZATION_MESSAGE_ENABLE` is returned. """ - settings.DJANGO_LOGGING = { - "INITIALIZATION_MESSAGE_ENABLE": "not_a_boolean", - } + settings_manager.initialization_message_enabled = "not_a_boolean", + errors: List[Error] = check_logging_settings(None) # type: ignore assert any( error.id == "django_logging.E014_INITIALIZATION_MESSAGE_ENABLE" @@ -246,10 +237,8 @@ def test_invalid_log_email_notifier(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E018_LOG_EMAIL_NOTIFIER['ENABLE']` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_EMAIL_NOTIFIER": { + settings_manager.email_notifier = { "ENABLE": "not_a_boolean", - }, } errors: List[Error] = check_logging_settings(None) # type: ignore assert any( @@ -272,10 +261,8 @@ def test_missing_email_settings(self, reset_settings: None) -> None: ------- - An error with the ID `django_logging.E010_EMAIL_SETTINGS` is returned. """ - settings.DJANGO_LOGGING = { - "LOG_EMAIL_NOTIFIER": { + settings_manager.email_notifier = { "ENABLE": True, - }, } with patch("django_logging.settings.checks.check_email_settings") as mock_check: mock_check.return_value = [ diff --git a/django_logging/tests/utils/test_get_conf.py b/django_logging/tests/utils/test_get_conf.py index 38bd2ef..4bc5e01 100644 --- a/django_logging/tests/utils/test_get_conf.py +++ b/django_logging/tests/utils/test_get_conf.py @@ -1,16 +1,13 @@ import sys from typing import Dict -from unittest.mock import patch import pytest from django.conf import settings +from django_logging.settings.manager import SettingsManager, settings_manager from django_logging.tests.constants import PYTHON_VERSION, PYTHON_VERSION_REASON from django_logging.utils.get_conf import ( - get_config, - is_auto_initialization_enabled, is_initialization_message_enabled, - use_email_notifier_template, ) pytestmark = [ @@ -22,126 +19,11 @@ class TestGetConf: - def test_get_conf(self, mock_settings: Dict) -> None: - """ - Test that the `get_config` function returns the correct configuration values. - - This test verifies that the `get_config` function extracts and returns the correct - configuration values from the Django settings. - - Mocks: - ------ - - `django.conf.settings` to provide mock configuration values. - - Asserts: - ------- - - The returned configuration matches the expected values for logging levels, directory, - file formats, console settings, email notifier settings, etc. - """ - expected = { - "log_levels": ["DEBUG", "INFO"], - "log_dir": "/custom/log/dir", - "log_file_formats": { - "DEBUG": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" - }, - "log_file_format_types": { - "DEBUG": "JSON", - "INFO": "XML", - }, - "extra_log_files": { - "DEBUG": False, - "INFO": True, - }, - "console_level": "WARNING", - "console_format": "%(levelname)s - %(message)s", - "colorize_console": True, - "log_date_format": "%Y-%m-%d", - "log_email_notifier_enable": True, - "log_email_notifier_log_levels": ["ERROR", None], - "log_email_notifier_log_format": "custom_format", - } - result = get_config() - assert result == expected - - result = get_config(extra_info=True) - result.pop("log_settings") - - expected_extra = expected.copy() - expected_extra.update( - { - "log_file_format_types": { - "DEBUG": "JSON", - "INFO": "XML", - }, - "extra_log_files": { - "DEBUG": False, - "INFO": True, - }, - "log_email_notifier": { - "ENABLE": True, - "NOTIFY_ERROR": True, - "NOTIFY_CRITICAL": False, - "LOG_FORMAT": "custom_format", - }, - } - ) - - assert result == expected_extra - - def test_use_email_notifier_template(self, mock_settings: Dict) -> None: - """ - Test that the `use_email_notifier_template` function correctly reads the `USE_TEMPLATE` setting. - - This test verifies that the `use_email_notifier_template` function returns `True` by default, - and correctly reflects changes to the `USE_TEMPLATE` setting. - - Mocks: - ------ - - `django.conf.settings` to provide mock configuration values. - - Asserts: - ------- - - The default return value of `use_email_notifier_template` is `True`. - - Changing the `USE_TEMPLATE` setting to `False` updates the return value accordingly. - """ - # By default, USE_TEMPLATE is True - assert use_email_notifier_template() is True - - # Test with USE_TEMPLATE set to False - mock_settings["DJANGO_LOGGING"]["LOG_EMAIL_NOTIFIER"]["USE_TEMPLATE"] = False - with patch.object(settings, "DJANGO_LOGGING", mock_settings["DJANGO_LOGGING"]): - assert use_email_notifier_template() is False - - def test_is_auto_initialization_enabled(self, mock_settings: Dict) -> None: - """ - Test that the `is_auto_initialization_enabled` function correctly reads the `AUTO_INITIALIZATION_ENABLE` setting. - - This test verifies that the `is_auto_initialization_enabled` function returns `True` by default, - and correctly reflects changes to the `AUTO_INITIALIZATION_ENABLE` setting. - - Mocks: - ------ - - `django.conf.settings` to provide mock configuration values. - - Asserts: - ------- - - The default return value of `is_auto_initialization_enabled` is `True`. - - Changing the `AUTO_INITIALIZATION_ENABLE` setting to `False` updates the return value accordingly. - """ - # By default, AUTO_INITIALIZATION_ENABLE is True - assert is_auto_initialization_enabled() is True - - # Test with AUTO_INITIALIZATION_ENABLE set to False - mock_settings["DJANGO_LOGGING"]["AUTO_INITIALIZATION_ENABLE"] = False - with patch.object(settings, "DJANGO_LOGGING", mock_settings["DJANGO_LOGGING"]): - assert is_auto_initialization_enabled() is False - def test_is_initialization_message_enabled(self, mock_settings: Dict) -> None: """ Test that the `is_initialization_message_enabled` function correctly reads the `INITIALIZATION_MESSAGE_ENABLE` setting. - This test verifies that the `is_initialization_message_enabled` function returns `True` by default, - and correctly reflects changes to the `INITIALIZATION_MESSAGE_ENABLE` setting. + This test verifies that the `is_initialization_message_enabled` function returns `True` by default. Mocks: ------ @@ -150,15 +32,9 @@ def test_is_initialization_message_enabled(self, mock_settings: Dict) -> None: Asserts: ------- - The default return value of `is_initialization_message_enabled` is `True`. - - Changing the `INITIALIZATION_MESSAGE_ENABLE` setting to `False` updates the return value accordingly. """ - # By default, INITIALIZATION_MESSAGE_ENABLE is True - assert is_initialization_message_enabled() is True - - # Test with INITIALIZATION_MESSAGE_ENABLE set to False - mock_settings["DJANGO_LOGGING"]["INITIALIZATION_MESSAGE_ENABLE"] = False - with patch.object(settings, "DJANGO_LOGGING", mock_settings["DJANGO_LOGGING"]): - assert is_initialization_message_enabled() is False + # By default, INITIALIZATION_MESSAGE_ENABLE is not none + assert is_initialization_message_enabled() is not None def test_logging_settings_none(self) -> None: """ @@ -173,4 +49,4 @@ def test_logging_settings_none(self) -> None: """ settings.DJANGO_LOGGING = None with pytest.raises(ValueError, match="DJANGO_LOGGING must be a dictionary with configs as keys"): - get_config() + SettingsManager() diff --git a/django_logging/utils/get_conf.py b/django_logging/utils/get_conf.py index aa59f6e..d1a48c4 100644 --- a/django_logging/utils/get_conf.py +++ b/django_logging/utils/get_conf.py @@ -1,80 +1,30 @@ -import os from typing import Dict -from django.conf import settings +from django_logging.settings import settings_manager -from django_logging.constants import DefaultConsoleSettings, DefaultLoggingSettings - -# pylint: disable=too-many-locals -def get_config(extra_info: bool = False) -> Dict: - """Retrieve logging configuration from Django settings. +def get_config() -> Dict: + """Retrieve logging configuration from the SettingsManager. Returns: - A Dict containing all necessary configurations for logging. + Dict: A dictionary containing all necessary configurations for logging. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - logging_defaults = DefaultLoggingSettings() - console_defaults = DefaultConsoleSettings() - - if not isinstance(log_settings, dict): - raise ValueError("DJANGO_LOGGING must be a dictionary with configs as keys") - - log_levels = log_settings.get("LOG_FILE_LEVELS", logging_defaults.log_levels) - log_dir = log_settings.get( - "LOG_DIR", os.path.join(os.getcwd(), logging_defaults.log_dir) - ) - log_file_formats = log_settings.get( - "LOG_FILE_FORMATS", logging_defaults.log_file_formats - ) - log_file_format_types = log_settings.get( - "LOG_FILE_FORMAT_TYPES", logging_defaults.log_file_format_types - ) - extra_log_files = log_settings.get( - "EXTRA_LOG_FILES", logging_defaults.extra_log_files - ) - console_level = log_settings.get( - "LOG_CONSOLE_LEVEL", console_defaults.log_console_level - ) - console_format = log_settings.get( - "LOG_CONSOLE_FORMAT", console_defaults.log_console_format - ) - colorize_console = log_settings.get( - "LOG_CONSOLE_COLORIZE", console_defaults.log_console_colorize - ) - log_date_format = log_settings.get( - "LOG_DATE_FORMAT", logging_defaults.log_date_format - ) - - log_email_notifier = log_settings.get( - "LOG_EMAIL_NOTIFIER", logging_defaults.log_email_notifier - ) - log_email_notifier_enable = log_email_notifier.get("ENABLE") - log_email_notifier_log_levels = [ - "ERROR" if log_email_notifier.get("NOTIFY_ERROR", False) else None, - "CRITICAL" if log_email_notifier.get("NOTIFY_CRITICAL", False) else None, - ] - log_email_notifier_log_format = log_email_notifier.get("LOG_FORMAT") config = { - "log_levels": log_levels, - "log_dir": log_dir, - "log_file_formats": log_file_formats, - "log_file_format_types": log_file_format_types, - "extra_log_files": extra_log_files, - "console_level": console_level, - "console_format": console_format, - "colorize_console": colorize_console, - "log_date_format": log_date_format, - "log_email_notifier_enable": log_email_notifier_enable, - "log_email_notifier_log_levels": log_email_notifier_log_levels, - "log_email_notifier_log_format": log_email_notifier_log_format, + "log_levels": settings_manager.log_levels, + "log_dir": settings_manager.log_dir, + "log_file_formats": settings_manager.log_file_formats, + "log_file_format_types": settings_manager.log_file_format_types, + "extra_log_files": settings_manager.extra_log_files, + "console_level": settings_manager.console_level, + "console_format": settings_manager.console_format, + "colorize_console": settings_manager.colorize_console, + "log_date_format": settings_manager.log_date_format, + "log_email_notifier_enable": settings_manager.email_notifier_enabled, + "log_email_notifier_log_levels": settings_manager.email_notifier_log_levels, + "log_email_notifier_log_format": settings_manager.email_notifier_log_format, } - if extra_info: - config.update( - {"log_email_notifier": log_email_notifier, "log_settings": log_settings} - ) return config @@ -87,88 +37,56 @@ def use_email_notifier_template() -> bool: bool: True if the email notifier should use a template, False otherwise. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - defaults = DefaultLoggingSettings() - - log_email_notifier = log_settings.get( - "LOG_EMAIL_NOTIFIER", defaults.log_email_notifier - ) - return log_email_notifier.get("USE_TEMPLATE", True) + return settings_manager.use_email_notifier_template def is_auto_initialization_enabled() -> bool: """Check if the AUTO_INITIALIZATION_ENABLE for the logging system is set to - True in Django settings. + True. Returns: - bool: True if AUTO_INITIALIZATION_ENABLE, False otherwise. - Defaults to True if not specified. + bool: True if AUTO_INITIALIZATION_ENABLE, False otherwise. Defaults to True if not specified. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - defaults = DefaultLoggingSettings() - - return log_settings.get( - "AUTO_INITIALIZATION_ENABLE", defaults.auto_initialization_enable - ) + return settings_manager.auto_initialization_enabled def is_initialization_message_enabled() -> bool: - """Check if the INITIALIZATION_MESSAGE_ENABLE is set to True in Django - settings. + """Check if the INITIALIZATION_MESSAGE_ENABLE is set to True. Returns: bool: True if INITIALIZATION_MESSAGE_ENABLE is True, False otherwise. - Defaults to True if not specified. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - defaults = DefaultLoggingSettings() - - return log_settings.get( - "INITIALIZATION_MESSAGE_ENABLE", defaults.initialization_message_enable - ) + return settings_manager.initialization_message_enabled def is_log_sql_queries_enabled() -> bool: """Check if the LOG_SQL_QUERIES_ENABLE for the logging system is set to - True in Django settings. + True. Returns: bool: True if LOG_SQL_QUERIES_ENABLE, False otherwise. - Defaults to False if not specified. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - defaults = DefaultLoggingSettings() - - return log_settings.get("LOG_SQL_QUERIES_ENABLE", defaults.log_sql_queries_enable) + return settings_manager.log_sql_queries_enabled def get_log_dir_size_limit() -> int: - """Check for the LOG_DIR_SIZE_LIMIT for managing the log dir size. + """Check for the LOG_DIR_SIZE_LIMIT for managing the log directory size. Returns: - int: the limit of log directory size. - Defaults to 1024 MB if not specified. + int: the limit of log directory size in MB. Defaults to 1024 MB if not specified. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - defaults = DefaultLoggingSettings() - - return log_settings.get("LOG_DIR_SIZE_LIMIT", defaults.log_dir_size_limit) + return settings_manager.log_dir_size_limit def include_log_iboard() -> bool: - """Check if the INCLUDE_LOG_iBOARD for the logging system is set to True in - Django settings. + """Check if the INCLUDE_LOG_iBOARD for the logging system is set to True. Returns: bool: True if INCLUDE_LOG_iBOARD, False otherwise. - Defaults to False if not specified. """ - log_settings = getattr(settings, "DJANGO_LOGGING", {}) - defaults = DefaultLoggingSettings() - - return log_settings.get("INCLUDE_LOG_iBOARD", defaults.include_log_iboard) + return settings_manager.include_log_iboard