Skip to content

Commit

Permalink
Merge pull request Lazarus-org#125 from MEHRSHAD-MIRSHEKARY/feat/sett…
Browse files Browse the repository at this point in the history
…ings-manager

✨ 🔨 Feat/settings manager
  • Loading branch information
ARYAN-NIKNEZHAD authored Oct 15, 2024
2 parents 7eb7f8e + 4c4e9f5 commit a630d4c
Show file tree
Hide file tree
Showing 20 changed files with 296 additions and 391 deletions.
4 changes: 2 additions & 2 deletions django_logging/constants/config_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
FormatOption = Union[int, str]

# Type Aliases for configurations
LogFileFormatType = Literal["JSON", "XML", "FLAT", "LOG"]
LogFileFormatType = Literal["JSON", "XML", "FLAT", "NORMAL"]
LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
LogDir = str
LogLevels = List[LogLevel]
NotifierLogLevels = List[Literal["ERROR", "CRITICAL"]]
NotifierLogLevels = List[Union[Literal["ERROR", "CRITICAL"], None]]
LogDateFormat = str


Expand Down
9 changes: 2 additions & 7 deletions django_logging/management/commands/generate_pretty_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
import os
from typing import Dict, Tuple

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.settings import settings_manager
from django_logging.utils.command.process_file import process_files, setup_directories


Expand All @@ -33,10 +31,7 @@ def handle(self, *args: Tuple, **kwargs: Dict) -> None:
**kwargs: Additional keyword arguments (not used).
"""
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

try:
json_dir, pretty_dir = setup_directories(log_dir, "json")
Expand Down
9 changes: 2 additions & 7 deletions django_logging/management/commands/generate_pretty_xml.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import os
from typing import Any, Dict, Tuple

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.settings import settings_manager
from django_logging.utils.command.process_file import process_files, setup_directories


Expand All @@ -31,10 +29,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

try:
xml_dir, pretty_dir = setup_directories(log_dir, "xml")
Expand Down
8 changes: 2 additions & 6 deletions django_logging/management/commands/logs_size_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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):
Expand Down
10 changes: 2 additions & 8 deletions django_logging/management/commands/send_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand

from django_logging.constants import DefaultLoggingSettings
from django_logging.constants.config_types import LogDir
from django_logging.settings import settings_manager
from django_logging.validators.email_settings_validator import check_email_settings

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -50,12 +49,7 @@ def handle(self, *args: Tuple, **kwargs: Dict) -> None:
"""
email: str = kwargs["email"] # type: ignore

default_settings = DefaultLoggingSettings()
log_settings = getattr(settings, "DJANGO_LOGGING", {})

log_dir: LogDir = log_settings.get(
"LOG_DIR", os.path.join(os.getcwd(), default_settings.log_dir)
)
log_dir = settings_manager.log_dir

if not os.path.exists(log_dir):
self.stdout.write(
Expand Down
17 changes: 0 additions & 17 deletions django_logging/middleware/monitor_log_size.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
from datetime import timedelta
from typing import Awaitable, Callable, Union

from asgiref.sync import sync_to_async
from django.core.cache import cache
Expand Down Expand Up @@ -28,22 +27,6 @@ class MonitorLogSizeMiddleware(BaseMiddleware):
"""

# pylint: disable=useless-parent-delegation
def __init__(
self,
get_response: Callable[
[HttpRequest], Union[HttpResponseBase, Awaitable[HttpResponseBase]]
],
) -> None:
"""Initializes the middleware with the provided get_response callable.
Args:
----
get_response (callable): The next middleware or view to be called in the chain.
"""
super().__init__(get_response)

def __sync_call__(self, request: HttpRequest) -> HttpResponseBase:
"""Synchronous request processing.
Expand Down
1 change: 1 addition & 0 deletions django_logging/settings/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .manager import settings_manager
60 changes: 27 additions & 33 deletions django_logging/settings/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -75,25 +68,21 @@ 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
)
)

# 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:
Expand All @@ -117,75 +106,80 @@ 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"],
)
)

# 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
Expand Down
2 changes: 1 addition & 1 deletion django_logging/settings/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from django_logging.filters.log_level_filter import LoggingLevelFilter


# pylint: disable=too-many-instance-attributes, too-many-arguments
# pylint: disable=too-many-instance-attributes, too-many-arguments, too-many-positional-arguments
class LogConfig:
"""Configuration class for django_logging.
Expand Down
Loading

0 comments on commit a630d4c

Please sign in to comment.