2021-04-19 14:47:30 +02:00
|
|
|
# coding: utf8
|
|
|
|
|
|
|
|
""" Report """
|
|
|
|
|
2021-04-19 14:55:07 +02:00
|
|
|
import atexit
|
2021-04-19 14:47:30 +02:00
|
|
|
import logging
|
|
|
|
|
|
|
|
|
2021-05-19 18:07:42 +02:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2021-04-19 14:47:30 +02:00
|
|
|
class Report(object): # 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:
|
2021-05-19 18:07:42 +02:00
|
|
|
log.debug('No report recipient, do not send report')
|
2021-04-19 14:47:30 +02:00
|
|
|
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:
|
2021-05-19 18:07:42 +02:00
|
|
|
log.debug('Report is empty, do not send it')
|
2021-04-19 14:47:30 +02:00
|
|
|
return True
|
|
|
|
msg = email_client.forge_message(
|
|
|
|
self.rcpt_to or rcpt_to,
|
|
|
|
subject=self.subject or subject,
|
|
|
|
text_body=content
|
|
|
|
)
|
2021-04-19 14:55:54 +02:00
|
|
|
if email_client.send(self.rcpt_to or rcpt_to, msg=msg, just_try=just_try):
|
2021-05-19 18:07:42 +02:00
|
|
|
log.debug('Report sent to %s', self.rcpt_to or rcpt_to)
|
2021-04-19 14:55:54 +02:00
|
|
|
return True
|
2021-05-19 18:07:42 +02:00
|
|
|
log.error('Fail to send report to %s', self.rcpt_to or rcpt_to)
|
2021-04-19 14:55:54 +02:00
|
|
|
return False
|
2021-04-19 14:55:07 +02:00
|
|
|
|
|
|
|
def send_at_exit(self, **kwargs):
|
|
|
|
""" Send report at exit """
|
|
|
|
atexit.register(self.send, **kwargs)
|