Guest User

Untitled

a guest
Oct 30th, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.49 KB | None | 0 0
  1. log = logging.getLogger()
  2. log.setLevel(logging.DEBUG)
  3. debug_format = logging.Formatter("%(levelname)s at %(asctime)s in %(filename)s (line %(lineno)d):: %(message)s")
  4.  
  5. # write errors to email
  6. error_mail_subject = "ERROR: Script error in %s on %s" % (sys.argv[0], os.uname()[1])
  7. error_mail_handler = logging.handlers.SMTPHandler(SMTP_HOST, 'errors@'+os.uname()[1], [LOG_EMAIL], error_mail_subject)
  8. error_mail_handler.setLevel(logging.ERROR)
  9. #error_mail_handler.setLevel(logging.DEBUG)
  10. error_mail_handler.setFormatter(debug_format)
  11.  
  12. # buffer debug messages so they can be sent with error emails
  13. memory_handler = logging.handlers.MemoryHandler(1024*10, logging.ERROR, error_mail_handler)
  14. memory_handler.setLevel(logging.DEBUG)
  15.  
  16. # attach handlers
  17. log.addHandler(memory_handler)
  18. log.addHandler(error_mail_handler)
  19.  
  20. import logging
  21.  
  22. from django.conf import settings
  23. from django.core.mail import EmailMessage
  24.  
  25.  
  26. class DjangoBufferingSMTPHandler(logging.handlers.BufferingHandler):
  27. def __init__(self, capacity, toaddrs=None, subject=None):
  28. logging.handlers.BufferingHandler.__init__(self, capacity)
  29.  
  30. if toaddrs:
  31. self.toaddrs = toaddrs
  32. else:
  33. # Send messages to site administrators by default
  34. self.toaddrs = zip(*settings.ADMINS)[-1]
  35.  
  36. if subject:
  37. self.subject = subject
  38. else:
  39. self.subject = 'logging'
  40.  
  41. def flush(self):
  42. if len(self.buffer) == 0:
  43. return
  44.  
  45. try:
  46. msg = "rn".join(map(self.format, self.buffer))
  47. emsg = EmailMessage(self.subject, msg, to=self.toaddrs)
  48. emsg.send()
  49. except Exception:
  50. # handleError() will print exception info to stderr if logging.raiseExceptions is True
  51. self.handleError(record=None)
  52. self.buffer = []
  53.  
  54. EMAIL_USE_TLS = True
  55. EMAIL_PORT = 25
  56. EMAIL_HOST = '' # example: 'smtp.yandex.ru'
  57. EMAIL_HOST_USER = '' # example: 'user@yandex.ru'
  58. EMAIL_HOST_PASSWORD = ''
  59. DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
  60. SERVER_EMAIL = EMAIL_HOST_USER
  61.  
  62. LOGGING = {
  63. 'handlers': {
  64. ...
  65. 'mail_buffer': {
  66. 'level': 'WARN',
  67. 'capacity': 9999,
  68. 'class': 'utils.logging.DjangoBufferingSMTPHandler',
  69. # optional:
  70. # 'toaddrs': 'admin@host.com'
  71. # 'subject': 'log messages'
  72. }
  73. },
  74. ...
  75. }
  76.  
  77. # init
  78. log_handler1 = BufferingSMTPHandler(
  79. 'smtp.host.lala', "from@test.com", ['to@test.com'], 'Log event(s)',5000)
  80. ...
  81. logger.addHandler(log_handler1)
  82. ...
  83.  
  84. # main code
  85. ...
  86. if internet_connection_ok and seconds_since_last_flush>60:
  87. log_handler1.flush() # send buffered log records (if any)
  88.  
  89. import logging
  90. import smtplib
  91. from email.mime.multipart import MIMEMultipart
  92. from email.mime.text import MIMEText
  93. from email.mime.base import MIMEBase
  94. import os
  95. from email import encoders
  96. import uuid
  97. # atexit allows for a method to be set to handle an object when the script exits
  98. import atexit
  99. filename = uuid.uuid4().hex
  100. class MailLogger:
  101.  
  102. def __init__(self, filePath, smtpDict):
  103. self.filePath = filePath
  104. self.smtpDict = smtpDict
  105. # Generate random file name
  106. filename = '%s.txt' % ( uuid.uuid4().hex )
  107. # Create full filename
  108. filename = '%s/%s' % (filePath,filename)
  109. self.filename = filename
  110. self.fileLogger = logging.getLogger('mailedLog')
  111. self.fileLogger.setLevel(logging.INFO)
  112. self.fileHandler = logging.FileHandler(filename)
  113. self.fileHandler.setLevel(logging.INFO)
  114. formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
  115. self.fileHandler.setFormatter(formatter)
  116. self.fileLogger.addHandler(self.fileHandler)
  117. atexit.register(self.mailOut)
  118.  
  119. def mailOut(self):
  120. '''
  121. Script is exiting so time to mail out the log file
  122.  
  123. "emailSettings": {
  124. "smtpServer" : "smtp.dom.com",
  125. "smtpPort" : 25,
  126. "sender" : "sender@dom.com>",
  127. "recipients" : [
  128. "recipient@dom.com"
  129. ],
  130. "subject" : "Email Subject"
  131. },
  132. '''
  133. # Close the file handler
  134. smtpDict = self.smtpDict
  135. self.fileHandler.close()
  136. msg = MIMEMultipart('alternative')
  137. s = smtplib.SMTP(smtpDict["smtpServer"], smtpDict["smtpPort"] )
  138. msg['Subject'] = smtpDict["subject"]
  139. msg['From'] = smtpDict["sender"]
  140. msg['To'] = ','.join(smtpDict["recipients"])
  141. body = 'See attached report file'
  142. content = MIMEText(body, 'plain')
  143. msg.attach(content)
  144. attachment = MIMEBase('application', 'octet-stream')
  145. attachment.set_payload(open(self.filename, 'rb').read())
  146. encoders.encode_base64(attachment)
  147. attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(self.filename))
  148. msg.attach(attachment)
  149. s.send_message(msg)
  150. s.quit()
  151.  
  152. from EmailLogRpt import MailLogger
  153. import time
  154. smtpDict = {
  155. "smtpServer" : "smtp.dom.com",
  156. "smtpPort" : 25,
  157. "sender" : "sender@dom.com",
  158. "recipients" : [
  159. "recpient@dom.com>"
  160. ],
  161. "subject" : "Email Subject"
  162. }
  163. myMailLogger = MailLogger("/home/ed/tmp",smtpDict).fileLogger
  164. myMailLogger.info("test msg 1")
  165. time.sleep(5)
  166. myMailLogger.info("test msg 2")
Add Comment
Please, Sign In to add comment