python-mylib/mylib/report.py
Benjamin Renard 6bbacce38a Code cleaning
2021-05-19 19:19:57 +02:00

69 lines
2.2 KiB
Python

# coding: utf8
""" Report """
import atexit
import logging
log = logging.getLogger(__name__)
class Report: # pylint: disable=useless-object-inheritance
""" Logging report """
content = []
handler = None
formatter = None
subject = None
rcpt_to = None
email_client = None
def __init__(self, loglevel=logging.WARNING, logformat='%(asctime)s - %(levelname)s - %(message)s',
subject=None, rcpt_to=None, email_client=None):
self.handler = logging.StreamHandler(self)
self.handler.setLevel(loglevel)
self.formatter = logging.Formatter(logformat)
self.handler.setFormatter(self.formatter)
self.subject = subject
self.rcpt_to = rcpt_to
self.email_client = email_client
def get_handler(self):
""" Retreive logging handler """
return self.handler
def write(self, msg):
""" Write a message """
self.content.append(msg)
def get_content(self):
""" Read the report content """
return "".join(self.content)
def send(self, subject=None, rcpt_to=None, email_client=None, just_try=False):
""" Send report using an EmailClient """
if not self.rcpt_to and not rcpt_to:
log.debug('No report recipient, do not send report')
return True
assert self.subject or subject, "You must provide report subject using Report.__init__ or Report.send"
assert self.email_client or email_client, "You must provide email client using Report.__init__ or Report.send"
content = self.get_content()
if not content:
log.debug('Report is empty, do not send it')
return True
msg = email_client.forge_message(
self.rcpt_to or rcpt_to,
subject=self.subject or subject,
text_body=content
)
if email_client.send(self.rcpt_to or rcpt_to, msg=msg, just_try=just_try):
log.debug('Report sent to %s', self.rcpt_to or rcpt_to)
return True
log.error('Fail to send report to %s', self.rcpt_to or rcpt_to)
return False
def send_at_exit(self, **kwargs):
""" Send report at exit """
atexit.register(self.send, **kwargs)