import os import smtplib from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # SMTP email notification settings SMTP_HOST = 'smtp.rockstar.t2.corp' SMTP_PORT = 25 SMTP_USERNAME = '' SMTP_PASSWORD = '' # LogSeverity enums class LogSeverity: INFO='INFO' WARNING='WARNING' ERROR='ERROR' CRITICAL='CRITICAL' class Logger: def __init__(self, name, log_dir, print_log = True): self.name = name self.log_dir = log_dir self.print_log = print_log self.warning_count = 0 self.error_count = 0 self.logger = '' self.created = datetime.now() self.passwd = 'dummypassword' self.log("Initializing log directory: %s" % log_dir, LogSeverity.INFO) if not os.path.exists(log_dir): os.makedirs(log_dir) def updateName(self, name): self.name = name def setPassword(self, passwd): self.passwd = passwd def log(self, msg, severity): now = datetime.now() now_str = now.strftime('%H:%M:%S') full_msg = "[%s] %s: %s" % (now_str, severity, msg) # Print to console if required if self.print_log: print full_msg # Increment warning/error counter if severity == LogSeverity.WARNING: self.warning_count += 1 elif severity in (LogSeverity.ERROR, LogSeverity.CRITICAL): self.error_count += 1 # Store message in logger, censor any password instances self.logger += "%s\n" % full_msg.replace(self.passwd, "*****") def log_spacer(self): self.logger += "\n" if self.print_log: print "" def save(self, append = False): path = os.path.join(self.log_dir, self.name+"_log.txt") if append: writer = open(path, 'a') else: writer = open(path, 'w') writer.write(self.logger) writer.close() self.logger = '' def mail_results(self, stmp_from, smtp_to, extra_msg = ''): # Set email subject and init body message if self.error_count > 0: subject = "%s process failed" % self.name body = 'Process Failed\n\n' else: subject = "%s process successful" % self.name body = 'Process Completed Successfully\n\n' # Set email fields msg = MIMEMultipart() msg['From'] = stmp_from msg['To'] = ', '.join(smtp_to) msg['Subject'] = subject # Attach log file(s) if errors occurred if self.error_count > 0 and os.path.exists(self.log_dir): count = 0 for filename in os.listdir(self.log_dir): path = os.path.join(self.log_dir, filename) f = file(path) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) count += 1 body += "Notes:\n\n" if count > 0: body += " - %d external log file(s) attached\n\n" % count else: body += " - No external log files available\n\n" # Attach text content body += 'Run Stats:\n\n' body += ' - Started at: %s\n' % self.created.strftime('%d/%m/%y %H:%M:%S') body += ' - Finished at: %s\n' % datetime.now().strftime('%d/%m/%y %H:%M:%S') body += ' - Number of warnings: %d\n' % self.warning_count body += ' - Number of errors: %d\n\n' % self.error_count if extra_msg: body += '%s\n\n' % extra_msg body += 'Run Log:\n\n' body += self.logger content = MIMEText(body, 'plain') msg.attach(content) # Initialise SMTP server connection server = smtplib.SMTP(SMTP_HOST, SMTP_PORT) if SMTP_USERNAME and SMTP_PASSWORD: server.login(SMTP_USERNAME, SMTP_PASSWORD) # Send email server.sendmail(stmp_from, smtp_to, msg.as_string()) server.quit()