Skip to content

Commit

Permalink
Merge pull request #33 from MEHRSHAD-MIRSHEKARY/refactor/defaults-and…
Browse files Browse the repository at this point in the history
…-utils

⚡🔨✨ feat: add dataclass in default_settings
  • Loading branch information
ARYAN-NIKNEZHAD authored Aug 22, 2024
2 parents a778c86 + 9e221bb commit c61c08f
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 159 deletions.
13 changes: 1 addition & 12 deletions django_logging/constants/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,3 @@
from .format_options import FORMAT_OPTIONS
from .default_settings import (
DEFAULT_AUTO_INITIALIZATION_ENABLE,
DEFAULT_INITIALIZATION_MESSAGE_ENABLE,
DEFAULT_LOG_FILE_FORMATS,
DEFAULT_LOG_CONSOLE_COLORIZE,
DEFAULT_LOG_CONSOLE_FORMAT,
DEFAULT_LOG_CONSOLE_LEVEL,
DEFAULT_LOG_DATE_FORMAT,
DEFAULT_LOG_DIR,
DEFAULT_LOG_EMAIL_NOTIFIER,
DEFAULT_LOG_FILE_LEVELS,
)
from .defaults import DefaultLoggingSettings
from .format_specifiers import LOG_FORMAT_SPECIFIERS
62 changes: 0 additions & 62 deletions django_logging/constants/default_settings.py

This file was deleted.

48 changes: 48 additions & 0 deletions django_logging/constants/defaults.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import os
from dataclasses import dataclass, field

from django_logging.constants.settings_types import (
LogFileFormatsType,
LOG_DIR_TYPE,
LOG_LEVELS_TYPE,
LOG_CONSOLE_FORMAT_TYPE,
LOG_CONSOLE_LEVEL_TYPE,
LOG_CONSOLE_COLORIZE_TYPE,
LOG_DATE_FORMAT_TYPE,
INITIALIZATION_MESSAGE_ENABLE_TYPE,
LogEmailNotifierType,
)


@dataclass(frozen=True)
class DefaultLoggingSettings:
log_dir: LOG_DIR_TYPE = field(
default_factory=lambda: os.path.join(os.getcwd(), "logs")
)
log_levels: LOG_LEVELS_TYPE = field(
default_factory=lambda: ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
)
log_date_format: LOG_DATE_FORMAT_TYPE = "%Y-%m-%d %H:%M:%S"
auto_initialization_enable: INITIALIZATION_MESSAGE_ENABLE_TYPE = True
initialization_message_enable: INITIALIZATION_MESSAGE_ENABLE_TYPE = True
log_file_formats: LogFileFormatsType = field(
default_factory=lambda: {
"DEBUG": 1,
"INFO": 1,
"WARNING": 1,
"ERROR": 1,
"CRITICAL": 1,
}
)
log_console_level: LOG_CONSOLE_LEVEL_TYPE = "DEBUG"
log_console_format: LOG_CONSOLE_FORMAT_TYPE = 1
log_console_colorize: LOG_CONSOLE_COLORIZE_TYPE = True
log_email_notifier: LogEmailNotifierType = field(
default_factory=lambda: {
"ENABLE": False,
"NOTIFY_ERROR": False,
"NOTIFY_CRITICAL": False,
"LOG_FORMAT": 1,
"USE_TEMPLATE": True,
}
)
2 changes: 1 addition & 1 deletion django_logging/constants/settings_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class LogFileFormatsType(TypedDict, total=False):

# Type Aliases for other configurations
LOG_DIR_TYPE = str
LOG_FILE_LEVELS_TYPE = List[str]
LOG_LEVELS_TYPE = List[str]
LOG_DATE_FORMAT_TYPE = str
AUTO_INITIALIZATION_ENABLE_TYPE = bool
INITIALIZATION_MESSAGE_ENABLE_TYPE = bool
Expand Down
26 changes: 11 additions & 15 deletions django_logging/handlers/email_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,9 @@


class EmailHandler(logging.Handler):
def __init__(self, include_html=True, *args, **kwargs):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

self.include_html = include_html

try:
# Attempt to retrieve the logging settings from the Django settings
logging_settings = settings.DJANGO_LOGGING

self.include_html = use_email_notifier_template()

except Exception as e:
logging.error(f"An unexpected error occurred while initializing EmailHandler: {e}")
self.include_html = use_email_notifier_template()

def emit(self, record):
try:
Expand All @@ -40,13 +30,19 @@ def emit(self, record):
self.handleError(record)

@staticmethod
def render_template(log_entry, request=None, template_path="email_notifier_template.html"):
def render_template(
log_entry, request=None, template_path="email_notifier_template.html"
):
django_engine = engines["django"]
template = django_engine.get_template(template_path)

# Fetch IP address and user agent using middleware methods
ip_address = RequestLogMiddleware.get_ip_address(request) if request else "Unknown"
user_agent = RequestLogMiddleware.get_user_agent(request) if request else "Unknown"
ip_address = (
RequestLogMiddleware.get_ip_address(request) if request else "Unknown"
)
user_agent = (
RequestLogMiddleware.get_user_agent(request) if request else "Unknown"
)

context = {
"message": log_entry,
Expand Down
46 changes: 20 additions & 26 deletions django_logging/settings/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,7 @@
from django.core.checks import Error, register
from typing import Dict, Any, List

from django_logging.constants import (
DEFAULT_LOG_DIR,
DEFAULT_LOG_FILE_LEVELS,
DEFAULT_LOG_DATE_FORMAT,
DEFAULT_LOG_EMAIL_NOTIFIER,
DEFAULT_LOG_CONSOLE_LEVEL,
DEFAULT_LOG_CONSOLE_FORMAT,
DEFAULT_LOG_CONSOLE_COLORIZE,
DEFAULT_LOG_FILE_FORMATS,
DEFAULT_AUTO_INITIALIZATION_ENABLE,
DEFAULT_INITIALIZATION_MESSAGE_ENABLE,
)
from django_logging.constants import DefaultLoggingSettings

from django_logging.validators.config_validators import (
validate_directory,
Expand All @@ -31,26 +20,29 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E
errors: List[Error] = []

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

# Validate LOG_DIR
log_dir = log_settings.get("LOG_DIR", DEFAULT_LOG_DIR)
log_dir = log_settings.get("LOG_DIR", defaults.log_dir)
errors.extend(validate_directory(log_dir, "LOG_DIR"))

# Validate LOG_FILE_LEVELS
log_file_levels = log_settings.get("LOG_FILE_LEVELS", DEFAULT_LOG_FILE_LEVELS)
log_file_levels = log_settings.get("LOG_FILE_LEVELS", defaults.log_levels)
errors.extend(
validate_log_levels(log_file_levels, "LOG_FILE_LEVELS", DEFAULT_LOG_FILE_LEVELS)
validate_log_levels(
log_file_levels, "LOG_FILE_LEVELS", defaults.log_levels
)
)

# Validate LOG_FILE_FORMATS
log_file_formats = log_settings.get("LOG_FILE_FORMATS", DEFAULT_LOG_FILE_FORMATS)
log_file_formats = log_settings.get("LOG_FILE_FORMATS", defaults.log_file_formats)
if isinstance(log_file_formats, dict):
for level, format_option in log_file_formats.items():
if level not in DEFAULT_LOG_FILE_LEVELS:
if level not in defaults.log_levels:
errors.append(
Error(
f"Invalid log level '{level}' in LOG_FILE_FORMATS.",
hint=f"Valid log levels are: {DEFAULT_LOG_FILE_LEVELS}.",
hint=f"Valid log levels are: {defaults.log_levels}.",
id="django_logging.E019_LOG_FILE_FORMATS",
)
)
Expand All @@ -68,33 +60,35 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E

# Validate LOG_CONSOLE_FORMAT
log_console_format = log_settings.get(
"LOG_CONSOLE_FORMAT", DEFAULT_LOG_CONSOLE_FORMAT
"LOG_CONSOLE_FORMAT", defaults.log_console_format
)
errors.extend(validate_format_option(log_console_format, "LOG_CONSOLE_FORMAT"))

# Validate LOG_CONSOLE_LEVEL
log_console_level = log_settings.get("LOG_CONSOLE_LEVEL", DEFAULT_LOG_CONSOLE_LEVEL)
log_console_level = log_settings.get(
"LOG_CONSOLE_LEVEL", defaults.log_console_level
)
errors.extend(
validate_log_levels(
[log_console_level], "LOG_CONSOLE_LEVEL", DEFAULT_LOG_FILE_LEVELS
[log_console_level], "LOG_CONSOLE_LEVEL", defaults.log_levels
)
)

# Validate LOG_CONSOLE_COLORIZE
log_console_colorize = log_settings.get(
"LOG_CONSOLE_COLORIZE", DEFAULT_LOG_CONSOLE_COLORIZE
"LOG_CONSOLE_COLORIZE", defaults.log_console_colorize
)
errors.extend(
validate_boolean_setting(log_console_colorize, "LOG_CONSOLE_COLORIZE")
)

# Validate LOG_DATE_FORMAT
log_date_format = log_settings.get("LOG_DATE_FORMAT", DEFAULT_LOG_DATE_FORMAT)
log_date_format = log_settings.get("LOG_DATE_FORMAT", defaults.log_date_format)
errors.extend(validate_date_format(log_date_format, "LOG_DATE_FORMAT"))

# Validate AUTO_INITIALIZATION_ENABLE
auto_initialization_enable = log_settings.get(
"AUTO_INITIALIZATION_ENABLE", DEFAULT_AUTO_INITIALIZATION_ENABLE
"AUTO_INITIALIZATION_ENABLE", defaults.auto_initialization_enable
)
errors.extend(
validate_boolean_setting(
Expand All @@ -104,7 +98,7 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E

# Validate INITIALIZATION_MESSAGE_ENABLE
initialization_message_enable = log_settings.get(
"INITIALIZATION_MESSAGE_ENABLE", DEFAULT_INITIALIZATION_MESSAGE_ENABLE
"INITIALIZATION_MESSAGE_ENABLE", defaults.initialization_message_enable
)
errors.extend(
validate_boolean_setting(
Expand All @@ -114,7 +108,7 @@ def check_logging_settings(app_configs: Dict[str, Any], **kwargs: Any) -> List[E

# Validate LOG_EMAIL_NOTIFIER
log_email_notifier = log_settings.get(
"LOG_EMAIL_NOTIFIER", DEFAULT_LOG_EMAIL_NOTIFIER
"LOG_EMAIL_NOTIFIER", defaults.log_email_notifier
)
errors.extend(validate_email_notifier(log_email_notifier))

Expand Down
5 changes: 3 additions & 2 deletions django_logging/settings/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
from typing import List, Dict, Optional, Union

from django_logging.constants import FORMAT_OPTIONS, DEFAULT_LOG_FILE_LEVELS
from django_logging.constants import FORMAT_OPTIONS, DefaultLoggingSettings
from django_logging.filters.level_filter import LoggingLevelFilter


Expand Down Expand Up @@ -132,6 +132,7 @@ def get_log_file(self, log_level: str) -> Optional[str]:

def set_conf(self) -> None:
"""Sets the logging configuration using the generated log files."""
defaults = DefaultLoggingSettings()
handlers = {
level.lower(): {
"class": "logging.FileHandler",
Expand Down Expand Up @@ -165,7 +166,7 @@ def set_conf(self) -> None:
"()": LoggingLevelFilter,
"logging_level": getattr(logging, level),
}
for level in DEFAULT_LOG_FILE_LEVELS
for level in defaults.log_levels
}

formatters = {
Expand Down
Loading

0 comments on commit c61c08f

Please sign in to comment.