Skip to content

Commit

Permalink
⚡🔨 refactor(utils): Update log_email_notifier modules
Browse files Browse the repository at this point in the history
Refactored log_and_notify exception to improve clearity of Exception that might raised
Updated imports in notifier to sort them
  • Loading branch information
MEHRSHAD-MIRSHEKARY committed Aug 27, 2024
1 parent 382ad5b commit c481756
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 24 deletions.
34 changes: 16 additions & 18 deletions django_logging/utils/log_email_notifier/log_and_notify.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,54 @@
import logging
import inspect
from typing import Optional, Dict, Any
import logging
from typing import Any, Dict, Optional

from django.conf import settings

from django_logging.constants.log_format_options import FORMAT_OPTIONS
from django_logging.utils.log_email_notifier.notifier import send_email_async
from django_logging.utils.get_conf import get_config
from django_logging.handlers import EmailHandler
from django_logging.settings.conf import LogConfig
from django_logging.utils.get_conf import get_config
from django_logging.utils.log_email_notifier.notifier import send_email_async


def log_and_notify_admin(
logger: logging.Logger, level: int, message: str, extra: Optional[Dict[str, Any]] = None
logger: logging.Logger,
level: int,
message: str,
extra: Optional[Dict[str, Any]] = None,
) -> None:
# Get the caller's frame to capture the correct module, file, and line number
frame = inspect.currentframe().f_back
logging_settings = get_config()
email_notifier_enable = getattr(
logging_settings, "log_email_notifier_enable", False
)
frame = inspect.currentframe().f_back # type: ignore
email_notifier_enable = get_config().get("log_email_notifier_enable", False)

if not email_notifier_enable:
raise ValueError(
"Email notifier is disabled. Please set the 'ENABLE' option to True in the 'LOG_EMAIL_NOTIFIER'"
" in DJANGO_LOGGING in your settings to activate email notifications."
)

_format = getattr(
logging_settings, "log_email_notifier_log_format", FORMAT_OPTIONS[1]
)
_format = get_config().get("log_email_notifier_log_format", FORMAT_OPTIONS[1])

try:
# create a LogRecord
log_record = logger.makeRecord(
name=logger.name,
level=level,
fn=frame.f_code.co_filename,
lno=frame.f_lineno,
fn=frame.f_code.co_filename, # type: ignore
lno=frame.f_lineno, # type: ignore
msg=message,
args=(),
exc_info=None,
func=frame.f_code.co_name,
func=frame.f_code.co_name, # type: ignore
extra=extra,
)

# Pass the LogRecord to the logger's handlers
logger.handle(log_record)
except TypeError as e:
except (TypeError, AttributeError) as e:
raise ValueError(
f"Failed to log message due to invalid param. Original error: {e}"
)
) from e
# Create a formatter instance and pass the email_notifier format
formatter = logging.Formatter(LogConfig.resolve_format(_format))

Expand Down
12 changes: 6 additions & 6 deletions django_logging/utils/log_email_notifier/notifier.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import logging
import threading
from typing import List, Optional
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP
from typing import List, Optional

from django.conf import settings

Expand Down Expand Up @@ -32,10 +32,10 @@ def send_email() -> None:
settings.DEFAULT_FROM_EMAIL, recipient_list, msg.as_string()
)
server.quit()
logger.info(f"Log Record has been sent to ADMIN EMAIL successfully.")
logger.info("Log Record has been sent to ADMIN EMAIL successfully.")

except Exception as e:
logger.warning(f"Email Notifier failed to send Log Record: {e}")
except Exception as e: # pylint: disable=broad-exception-caught
logger.warning("Email Notifier failed to send Log Record: %s", e)

finally:
if event:
Expand Down

0 comments on commit c481756

Please sign in to comment.