base_daily_logs_send.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 设置每天 23:59 执行, 读取当天数据库中, 所有日志, 发送到指定邮箱
  4. '''
  5. import time
  6. import os
  7. import sys
  8. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto')[0] + 'auto'))
  9. import pymongo
  10. import smtplib
  11. from email.mime.text import MIMEText
  12. from email.header import Header
  13. from base.base_load_config import load_config, get_base_path
  14. config_json = load_config()
  15. base_project = get_base_path()
  16. PROJECT_NAME = config_json.get('PROJECT_NAME')
  17. DB_USER = config_json.get('DB_USER')
  18. DB_PASSWORD = config_json.get('DB_PASSWORD')
  19. DB_IP = config_json.get('DB_IP')
  20. DB_PORT = config_json.get('DB_PORT')
  21. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  22. MAIL_HOST = config_json.get('MAIL_HOST')
  23. MAIL_USER = config_json.get('MAIL_USER')
  24. MAIL_PASS = config_json.get('MAIL_PASS')
  25. MAIL_SENDER = config_json.get('MAIL_SENDER')
  26. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  27. now_day = time.strftime('%Y-%m-%d', time.localtime())
  28. class LogsHandle(object):
  29. def __init__(self):
  30. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  31. db = 'logs'
  32. collection = 'logs_' + self.now_day
  33. self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
  34. def logs_send(self):
  35. subject = 'auto message logs'
  36. title = 'auto message - daily logs: {}'.format(self.now_day)
  37. text = ''
  38. # TODO
  39. # 从 mongodb 读取日志, 拼接 text, 发送邮件
  40. # 查询所有文档
  41. query = {'state': 'error'}
  42. cursor = self.mongo.collection.find(query)
  43. # 遍历结果集
  44. for record in cursor:
  45. text += "logs_source: {}, logs_detail: {}, state: {} logs_create_time: {}\n\n".format(
  46. record.setdefault('title'),
  47. record.setdefault('content'),
  48. record.setdefault('state'),
  49. record.setdefault('create_datetime'),
  50. )
  51. if text:
  52. S = SendEmail(subject=subject, title=title, text=text)
  53. S.send()
  54. else:
  55. print("No error logs found for today.")
  56. class MongoHandle(object):
  57. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  58. self.client = pymongo.MongoClient(MONGO_LINK)
  59. self.db = db
  60. self.collection = collection
  61. if del_db and db:
  62. # 检查数据库是否存在
  63. if db in self.client.list_database_names():
  64. # 删除数据库
  65. self.client.drop_database(db)
  66. self.db = self.client[db]
  67. if del_collection and self.collection:
  68. # 检查集合是否存在
  69. if self.collection in self.db.list_collection_names():
  70. # 删除集合
  71. self.db.drop_collection(collection)
  72. self.collection = self.db[collection]
  73. if auto_remove:
  74. self.auto_remove_data(auto_remove)
  75. def write_data(self, data):
  76. self.collection.insert_one(data)
  77. def auto_remove_data(self, day):
  78. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  79. self.collection.delete_one({'_id': data['_id']})
  80. class SendEmail(object):
  81. def __init__(self, subject='auto subject', title='auto title', text='auto text') -> None:
  82. # 第三方 SMTP 服务
  83. self.mail_host = MAIL_HOST # 设置服务器
  84. self.mail_user = MAIL_USER # 用户名
  85. self.mail_pass = MAIL_PASS # 口令
  86. self.sender = MAIL_SENDER
  87. self.receivers = [MAIL_RECEIVERS]
  88. self.subject = subject
  89. self.title = title
  90. self.text = text
  91. def send(self):
  92. message = MIMEText(self.text, 'plain', 'utf-8')
  93. message['From'] = Header(self.title, 'utf-8')
  94. message['To'] = Header("auto", 'utf-8')
  95. message['Subject'] = Header(self.subject, 'utf-8')
  96. try:
  97. smtpObj = smtplib.SMTP_SSL(self.mail_host)
  98. smtpObj.login(self.mail_user, self.mail_pass)
  99. smtpObj.sendmail(self.sender, self.receivers, message.as_string())
  100. print("邮件发送成功")
  101. except smtplib.SMTPException as e:
  102. print("Error: 无法发送邮件", e)
  103. if __name__ == '__main__':
  104. print("发送当天日志:start")
  105. LogsHandle().logs_send()
  106. print("发送当天日志:done")