Skip to content

Commit

Permalink
Merge pull request #18 from MEHRSHAD-MIRSHEKARY/debug/log_and_notify
Browse files Browse the repository at this point in the history
Debug/log and notify
  • Loading branch information
ARYAN-NIKNEZHAD authored Aug 19, 2024
2 parents 550e0c8 + 1665ec9 commit 9287c2b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
5 changes: 1 addition & 4 deletions django_logging/handlers/email_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


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

self.include_html = include_html
Expand All @@ -19,9 +19,6 @@ def __init__(self, include_html=False, *args, **kwargs):

self.include_html = logging_settings.get("LOG_EMAIL_NOTIFIER", {}).get("USE_TEMPLATE", include_html)

except AttributeError:
logging.warning(
f"DJANGO_LOGGING settings not found. Using default include_html value: {self.include_html}.")
except Exception as e:
logging.error(f"An unexpected error occurred while initializing EmailHandler: {e}")

Expand Down
27 changes: 25 additions & 2 deletions django_logging/utils/log_and_notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,32 @@

from django.conf import settings

from django_logging.constants.format_options import FORMAT_OPTIONS
from django_logging.utils.email import send_email_async
from django_logging.handlers import EmailHandler
from django_logging.settings.conf import LogConfig


def log_and_notify(logger, level: int, message: str, extra: Optional[Dict] = None):
def log_and_notify(logger, level: int, message: str, extra: Optional[Dict] = None) -> None:
# Get the caller's frame to capture the correct module, file, and line number
frame = inspect.currentframe().f_back

if not hasattr(settings, "DJANGO_LOGGING"):
raise ValueError(
"Email notifier is disabled. Please add DJANGO_LOGGING to your settings file and set "
"the 'ENABLE' option to True in the 'LOG_EMAIL_NOTIFIER' settings to activate email notifications."
)
email_notifier_conf = settings.DJANGO_LOGGING.get("LOG_EMAIL_NOTIFIER")

notifier_enable = email_notifier_conf.get("ENABLE", False)
if not notifier_enable:
raise ValueError(
"Email notifier is disabled. Please set the 'ENABLE' option to True in the 'LOG_EMAIL_NOTIFIER' "
"settings to activate email notifications."
)

_format = email_notifier_conf.get("LOG_FORMAT", FORMAT_OPTIONS[1])

try:
# create a LogRecord
log_record = logger.makeRecord(
Expand All @@ -32,11 +50,16 @@ def log_and_notify(logger, level: int, message: str, extra: Optional[Dict] = Non
raise ValueError(
f"Failed to log message due to invalid param. Original error: {e}"
)
# Create a formatter instance and pass the email_notifier format
formatter = logging.Formatter(LogConfig.resolve_format(_format))

# Format the log message using the formatter
formatted_message = formatter.format(log_record)

request = extra.get("request") if extra else None

# Render the email template with the formatted message
email_body = EmailHandler.render_template(log_record, request)
email_body = EmailHandler.render_template(formatted_message, request)

subject = f"New Log Record: {logging.getLevelName(level)}"
send_email_async(subject, email_body, [settings.ADMIN_EMAIL])

0 comments on commit 9287c2b

Please sign in to comment.