【工具】利用python 傳送MySQL 慢日誌郵件

楊奇龍發表於2015-02-25
一 需求
    因為開發針對某系統做穩定性建設,需要對資料庫系統的慢日誌進行審計,檢查最佳化。和開發溝通選擇定期傳送慢查詢到開發的郵箱的方式,每日彙總,然後一起評估 最佳化slow query 。

二 工具實現
mail.py  指令碼
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # mail.py
  4. import os.path
  5. import time
  6. import sys
  7. import os
  8. import json
  9. import string
  10. import random
  11. import smtplib
  12. import time
  13. from datetime import date
  14. from email.mime.multipart import MIMEMultipart
  15. from email.mime.text import MIMEText
  16. from email.mime.image import MIMEImage
  17. from email.Header import Header
  18. from email.MIMEText import MIMEText
  19. from email.MIMEMultipart import MIMEMultipart

  20. mail_user="xxx@xxxx.com";
  21. mail_pass="xxxxx";
  22. mail_smtp_server="smtp.xxxxx.com";
  23. mail_smtp_port= 25

  24. def sendMail(contents,subject,attach,mail_to):
  25.     lTime=str(time.strftime('%Y%m%d_%H',time.localtime(time.time())))
  26.     msg = MIMEMultipart('related');
  27.     if subject=="":
  28.         subject='test';
  29.     msg['Subject'] = subject+" Time:"+ lTime;
  30.     msg['From'] = mail_user;
  31.     msg['To'] = ";".join(mail_to) ;
  32.     html="";
  33.     for cont in contents:
  34.         html = html+cont[0];
  35.     msgHtml = MIMEMultipart('alternative');
  36.     msgHtml.set_charset('UTF-8');
  37.     msgAtt = MIMEText(open(attach,'rb').read(),'base','gbk');
  38.     msgAtt["Content-Type"] = 'application/octet-stream'
  39.     msgAtt["Content-Disposition"] = 'attachment; filename="'+subject+'"'
  40.     msg.attach(msgAtt);

  41.     try:
  42.         smtp = smtplib.SMTP();
  43.         smtp.connect(mail_smtp_server,mail_smtp_port)
  44.         smtp.login(mail_user,mail_pass);
  45.         smtp.sendmail(mail_user,mail_to,msg.as_string());
  46.         smtp.close();
  47.     except Exception,e:
  48.         print str(e)
 sendSlowlog.py
 
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import mail ##使用了上述指令碼
  4. import sys
  5. import time
  6. import os
  7. import datetime

  8. from datetime import date
  9. from os.path import join, getsize

  10. def sendSlowlog(subject_info,attach,mail_to):
  11.     size = os.path.getsize(attach)
  12.     if(size > 1):
  13.        mail.sendMail("",subject_info,attach,mail_to)


  14. if __name__ == '__main__':
  15.    mail_to=["qilong.yangql@xxxx.com"]
  16.    lDate=str(time.strftime('%Y%m%d',time.localtime(time.time())))
  17.    lTime=str(time.strftime('%Y%m%d_%H',time.localtime(time.time())))
  18.    subject_info="Slowlog of DBname" + lTime
  19.    attach="/u01/my3306/log/slow_"+ lDate +"/slow.log."+lTime
  20.    sendSlowlog(subject_info,attach,mail_to)


   本系統已經每小時將slow log 進行分割,關於如何切割,各位可以思考一下。 



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-1441204/,如需轉載,請註明出處,否則將追究法律責任。

相關文章