change logging

This commit is contained in:
2021-10-11 15:52:39 +02:00
parent 4d6674473d
commit feeb866c3f
3 changed files with 36 additions and 37 deletions

View File

@@ -247,37 +247,35 @@ def add_whitelist_entry(quarantines, args):
# add entry to whitelist # add entry to whitelist
whitelist.add(args.mailfrom, args.recipient, args.comment, args.permanent) whitelist.add(args.mailfrom, args.recipient, args.comment, args.permanent)
logger.info("whitelist entry added successfully") print("whitelist entry added successfully")
def delete_whitelist_entry(quarantines, args): def delete_whitelist_entry(quarantines, args):
logger = logging.getLogger(__name__)
whitelist = _get_whitelist(quarantines, args.quarantine, args.debug) whitelist = _get_whitelist(quarantines, args.quarantine, args.debug)
whitelist.delete(args.whitelist_id) whitelist.delete(args.whitelist_id)
logger.info("whitelist entry deleted successfully") print("whitelist entry deleted successfully")
def notify(quarantines, args): def notify(quarantines, args):
logger = logging.getLogger(__name__)
quarantine = _get_quarantine(quarantines, args.quarantine, args.debug) quarantine = _get_quarantine(quarantines, args.quarantine, args.debug)
quarantine.notify(args.quarantine_id, args.recipient) quarantine.notify(args.quarantine_id, args.recipient)
logger.info("notification sent successfully") print("notification sent successfully")
def release(quarantines, args): def release(quarantines, args):
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
quarantine = _get_quarantine(quarantines, args.quarantine, args.debug) quarantine = _get_quarantine(quarantines, args.quarantine, args.debug)
rcpts = quarantine.release(args.quarantine_id, args.recipient) rcpts = quarantine.release(args.quarantine_id, args.recipient)
rcpts = ", ".join(rcpts)
logger.info( logger.info(
f"quarantined email {args.quarantine_id} released successfully " f"{args.quarantine}: released message with id {args.quarantine_id} "
f"for recipients {rcpts}") f"for {rcpts}")
def delete(quarantines, args): def delete(quarantines, args):
logger = logging.getLogger(__name__)
storage = _get_quarantine(quarantines, args.quarantine, args.debug).storage storage = _get_quarantine(quarantines, args.quarantine, args.debug).storage
storage.delete(args.quarantine_id, args.recipient) storage.delete(args.quarantine_id, args.recipient)
logger.info("quarantined email deleted successfully") print("quarantined message deleted successfully")
def get(quarantines, args): def get(quarantines, args):

View File

@@ -145,10 +145,10 @@ class EMailNotification(BaseNotification):
self.parser_lib = parser_lib self.parser_lib = parser_lib
def get_email_body_soup(self, msg, logger): def get_msg_body_soup(self, msg, logger):
"Extract and decode email body and return it as BeautifulSoup object." "Extract and decode message body, return it as BeautifulSoup object."
# try to find the body part # try to find the body part
logger.debug("trying to find email body") logger.debug("trying to find message body")
try: try:
body = msg.get_body(preferencelist=("html", "plain")) body = msg.get_body(preferencelist=("html", "plain"))
except Exception as e: except Exception as e:
@@ -178,8 +178,8 @@ class EMailNotification(BaseNotification):
else: else:
logger.debug(f"content type is {content_type}") logger.debug(f"content type is {content_type}")
else: else:
logger.error("unable to find email body") logger.error("unable to find message body")
content = "ERROR: unable to find email body" content = "ERROR: unable to find message body"
# create BeautifulSoup object # create BeautifulSoup object
length = len(content) length = len(content)
@@ -194,7 +194,7 @@ class EMailNotification(BaseNotification):
def sanitize(self, soup, logger): def sanitize(self, soup, logger):
"Sanitize mail html text." "Sanitize mail html text."
logger.debug("sanitizing email text") logger.debug("sanitize message text")
# completly remove bad elements # completly remove bad elements
for element in soup(EMailNotification._bad_tags): for element in soup(EMailNotification._bad_tags):
@@ -230,7 +230,7 @@ class EMailNotification(BaseNotification):
template_vars={}, synchronous=False): template_vars={}, synchronous=False):
"Notify recipients via email." "Notify recipients via email."
# extract body from email # extract body from email
soup = self.get_email_body_soup(msg, logger) soup = self.get_msg_body_soup(msg, logger)
# replace picture sources # replace picture sources
image_replaced = False image_replaced = False
@@ -248,15 +248,15 @@ class EMailNotification(BaseNotification):
element["src"] = "cid:removed_for_security_reasons" element["src"] = "cid:removed_for_security_reasons"
image_replaced = True image_replaced = True
# sanitizing email text of original email # sanitize message text
sanitized_text = self.sanitize(soup, logger) sanitized_text = self.sanitize(soup, logger)
del soup del soup
# sending email notifications # send email notifications
for recipient in recipients: for recipient in recipients:
logger.debug( logger.debug(
f"generating email notification for '{recipient}'") f"generating email notification for '{recipient}'")
logger.debug("parsing email template") logger.debug("parsing message template")
variables = defaultdict(str, template_vars) variables = defaultdict(str, template_vars)
variables["HTML_TEXT"] = sanitized_text variables["HTML_TEXT"] = sanitized_text
@@ -307,7 +307,8 @@ class EMailNotification(BaseNotification):
newmsg.as_string()) newmsg.as_string())
except Exception as e: except Exception as e:
raise RuntimeError( raise RuntimeError(
f"error while sending email to '{recipient}': {e}") f"error while sending email notification "
f"to '{recipient}': {e}")
else: else:
mailer.sendmail(self.smtp_host, self.smtp_port, qid, mailer.sendmail(self.smtp_host, self.smtp_port, qid,
self.mailfrom, recipient, newmsg.as_string(), self.mailfrom, recipient, newmsg.as_string(),

View File

@@ -48,26 +48,26 @@ class BaseMailStorage:
self.pretend = False self.pretend = False
def add(self, data, qid, mailfrom, recipients, subject, variables): def add(self, data, qid, mailfrom, recipients, subject, variables):
"Add email to storage." "Add message to storage."
return ("", "") return ("", "")
def execute(self, milter, logger): def execute(self, milter, logger):
return return
def find(self, mailfrom=None, recipients=None, older_than=None): def find(self, mailfrom=None, recipients=None, older_than=None):
"Find emails in storage." "Find messages in storage."
return return
def get_metadata(self, storage_id): def get_metadata(self, storage_id):
"Return metadata of email in storage." "Return metadata of message in storage."
return return
def delete(self, storage_id, recipients=None): def delete(self, storage_id, recipients=None):
"Delete email from storage." "Delete message from storage."
return return
def get_mail(self, storage_id): def get_mail(self, storage_id):
"Return email and metadata." "Return message and metadata."
return return
@@ -160,7 +160,7 @@ class FileMailStorage(BaseMailStorage):
raise RuntimeError(f"unable to remove file: {e}") raise RuntimeError(f"unable to remove file: {e}")
def add(self, data, qid, mailfrom, recipients, subject, variables, logger): def add(self, data, qid, mailfrom, recipients, subject, variables, logger):
"Add email to file storage and return storage id." "Add message to file storage and return storage id."
super().add(data, qid, mailfrom, recipients, subject, variables) super().add(data, qid, mailfrom, recipients, subject, variables)
storage_id = self.get_storageid(qid) storage_id = self.get_storageid(qid)
@@ -221,7 +221,7 @@ class FileMailStorage(BaseMailStorage):
milter.msginfo["vars"], logger) milter.msginfo["vars"], logger)
def get_metadata(self, storage_id): def get_metadata(self, storage_id):
"Return metadata of email in storage." "Return metadata of message in storage."
super().get_metadata(storage_id) super().get_metadata(storage_id)
if not self.metadata: if not self.metadata:
@@ -279,7 +279,7 @@ class FileMailStorage(BaseMailStorage):
return metadata return metadata
def find(self, mailfrom=None, recipients=None, older_than=None): def find(self, mailfrom=None, recipients=None, older_than=None):
"Find emails in storage." "Find messages in storage."
super().find(mailfrom, recipients, older_than) super().find(mailfrom, recipients, older_than)
if isinstance(mailfrom, str): if isinstance(mailfrom, str):
mailfrom = [mailfrom] mailfrom = [mailfrom]
@@ -289,7 +289,7 @@ class FileMailStorage(BaseMailStorage):
if not self.metadata: if not self.metadata:
return {} return {}
emails = {} msgs = {}
metafiles = glob(os.path.join( metafiles = glob(os.path.join(
self.directory, f"*{self._metadata_suffix}")) self.directory, f"*{self._metadata_suffix}"))
for metafile in metafiles: for metafile in metafiles:
@@ -316,12 +316,12 @@ class FileMailStorage(BaseMailStorage):
len(recipients + metadata["recipients"]): len(recipients + metadata["recipients"]):
continue continue
emails[storage_id] = metadata msgs[storage_id] = metadata
return emails return msgs
def delete(self, storage_id, recipients=None): def delete(self, storage_id, recipients=None):
"Delete email from storage." "Delete message from storage."
super().delete(storage_id, recipients) super().delete(storage_id, recipients)
if not recipients or not self.metadata: if not recipients or not self.metadata:
self._remove(storage_id) self._remove(storage_id)
@@ -330,7 +330,7 @@ class FileMailStorage(BaseMailStorage):
try: try:
metadata = self.get_metadata(storage_id) metadata = self.get_metadata(storage_id)
except RuntimeError as e: except RuntimeError as e:
raise RuntimeError(f"unable to delete email: {e}") raise RuntimeError(f"unable to delete message: {e}")
metafile, _ = self._get_file_paths(storage_id) metafile, _ = self._get_file_paths(storage_id)
@@ -352,7 +352,7 @@ class FileMailStorage(BaseMailStorage):
with open(datafile, "rb") as fh: with open(datafile, "rb") as fh:
data = fh.read() data = fh.read()
except IOError as e: except IOError as e:
raise RuntimeError(f"unable to open email data file: {e}") raise RuntimeError(f"unable to open data file: {e}")
return data return data
def get_mail(self, storage_id): def get_mail(self, storage_id):
@@ -491,7 +491,7 @@ class Quarantine:
return self._milter_action return self._milter_action
def notify(self, storage_id, recipient=None): def notify(self, storage_id, recipient=None):
"Notify recipient about email in storage." "Notify recipient about message in storage."
if not self._notification: if not self._notification:
raise RuntimeError( raise RuntimeError(
"notification not defined, " "notification not defined, "
@@ -530,7 +530,7 @@ class Quarantine:
except Exception as e: except Exception as e:
raise RuntimeError( raise RuntimeError(
f"error while sending email to '{recipient}': {e}") f"error while sending message to '{recipient}': {e}")
self.storage.delete(storage_id, recipient) self.storage.delete(storage_id, recipient)
return recipients return recipients
@@ -552,7 +552,7 @@ class Quarantine:
milter.msginfo["rcpts"] = rcpts milter.msginfo["rcpts"] = rcpts
if self._milter_action in ["REJECT", "DISCARD"]: if self._milter_action in ["REJECT", "DISCARD"]:
logger.info(f"quarantine message for recipients: {rcpts}") logger.info(f"quarantine message for {rcpts}")
self._storage.execute(milter) self._storage.execute(milter)