logging_.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. '''
  2. Created on 6 juil. 2017
  3. @author: olivier.massot
  4. '''
  5. from email.mime.text import MIMEText
  6. import logging.config
  7. import smtplib
  8. from path import Path
  9. import yaml
  10. LOG_DIR = Path(__file__).parent / "logs"
  11. LOG_DIR.makedirs_p()
  12. def getLogger(name):
  13. # charge la configuration du logging depuis le fichier 'logging.yaml'
  14. configfile = Path(__file__).parent
  15. with open(configfile / 'logging.yaml', 'rt') as f:
  16. conf = yaml.load(f)
  17. logging.config.dictConfig(conf)
  18. return logging.getLogger(name)
  19. # ******************************
  20. class BufferingSMTPHandler(logging.handlers.BufferingHandler):
  21. def __init__(self, mailhost, fromaddr, toaddrs, subject, capacity):
  22. logging.handlers.BufferingHandler.__init__(self, capacity)
  23. self.mailhost = mailhost
  24. self.mailport = None
  25. self.fromaddr = fromaddr
  26. self.toaddrs = toaddrs
  27. self.subject = subject
  28. def flush(self):
  29. try:
  30. if len(self.buffer) > 0:
  31. port = self.mailport if self.mailport else smtplib.SMTP_PORT
  32. msg = "\n".join([self.format(record) for record in self.buffer])
  33. msg = MIMEText(msg.encode('utf-8'), _charset='utf-8')
  34. msg['Subject'] = self.subject
  35. msg['From'] = self.fromaddr
  36. msg['To'] = ",".join(self.toaddrs)
  37. smtp = smtplib.SMTP(self.mailhost, port)
  38. smtp.sendmail(self.fromaddr, self.toaddrs, msg.as_string())
  39. smtp.quit()
  40. self.buffer = []
  41. except Exception as e:
  42. print(e)
  43. raise