python-mylib/Report.py
2021-04-19 14:55:54 +02:00

67 lines
2.2 KiB
Python

#!/usr/bin/python
# coding: utf8
""" Report """
import atexit
import logging
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:
logging.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:
logging.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):
logging.debug('Report sent to %s', self.rcpt_to or rcpt_to)
return True
logging.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)