base_daily_logs_send.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 设置每天 23:59 执行, 读取当天数据库中, 所有日志, 发送到指定邮箱
  4. '''
  5. import time
  6. import os
  7. import sys
  8. import httpx
  9. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto')[0] + 'auto'))
  10. import pymongo
  11. import smtplib
  12. from email.mime.text import MIMEText
  13. from email.header import Header
  14. from base.base_load_config import load_config, get_base_path
  15. config_json = load_config()
  16. base_project = get_base_path()
  17. PROJECT_NAME = config_json.get('PROJECT_NAME')
  18. DB_USER = config_json.get('DB_USER')
  19. DB_PASSWORD = config_json.get('DB_PASSWORD')
  20. DB_IP = config_json.get('DB_IP')
  21. DB_PORT = config_json.get('DB_PORT')
  22. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  23. MAIL_HOST = config_json.get('MAIL_HOST')
  24. MAIL_USER = config_json.get('MAIL_USER')
  25. MAIL_PASS = config_json.get('MAIL_PASS')
  26. MAIL_SENDER = config_json.get('MAIL_SENDER')
  27. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  28. now_day = time.strftime('%Y-%m-%d', time.localtime())
  29. class LogsHandle(object):
  30. def __init__(self):
  31. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  32. db = 'logs'
  33. collection = 'logs_' + self.now_day
  34. self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
  35. def logs_send(self):
  36. subject = 'auto message logs'
  37. title = 'auto message - daily logs: {}'.format(self.now_day)
  38. text = ''
  39. # TODO
  40. # 从 mongodb 读取日志, 拼接 text, 发送邮件
  41. # 查询所有文档
  42. query = {'state': 'error'}
  43. cursor = self.mongo.collection.find(query)
  44. # 遍历结果集
  45. for record in cursor:
  46. text += "logs_source: {}, logs_detail: {}, state: {} logs_create_time: {}\n\n".format(
  47. record.setdefault('title'),
  48. record.setdefault('content'),
  49. record.setdefault('state'),
  50. record.setdefault('create_datetime'),
  51. )
  52. if text:
  53. S = SendEmail(subject=subject, title=title, text=text)
  54. S.send()
  55. G = GotifyNotifier(title=title, message=text, token='base')
  56. G.send_message()
  57. else:
  58. print("No error logs found for today.")
  59. class MongoHandle(object):
  60. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  61. self.client = pymongo.MongoClient(MONGO_LINK)
  62. self.db = db
  63. self.collection = collection
  64. if del_db and db:
  65. # 检查数据库是否存在
  66. if db in self.client.list_database_names():
  67. # 删除数据库
  68. self.client.drop_database(db)
  69. self.db = self.client[db]
  70. if del_collection and self.collection:
  71. # 检查集合是否存在
  72. if self.collection in self.db.list_collection_names():
  73. # 删除集合
  74. self.db.drop_collection(collection)
  75. self.collection = self.db[collection]
  76. if auto_remove:
  77. self.auto_remove_data(auto_remove)
  78. def write_data(self, data):
  79. self.collection.insert_one(data)
  80. def auto_remove_data(self, day):
  81. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  82. self.collection.delete_one({'_id': data['_id']})
  83. class SendEmail(object):
  84. def __init__(self, subject='auto subject', title='auto title', text='auto text') -> None:
  85. # 第三方 SMTP 服务
  86. self.mail_host = MAIL_HOST # 设置服务器
  87. self.mail_user = MAIL_USER # 用户名
  88. self.mail_pass = MAIL_PASS # 口令
  89. self.sender = MAIL_SENDER
  90. self.receivers = [MAIL_RECEIVERS]
  91. self.subject = subject
  92. self.title = title
  93. self.text = text
  94. def send(self):
  95. message = MIMEText(self.text, 'plain', 'utf-8')
  96. message['From'] = Header(self.title, 'utf-8')
  97. message['To'] = Header("auto", 'utf-8')
  98. message['Subject'] = Header(self.subject, 'utf-8')
  99. try:
  100. smtpObj = smtplib.SMTP_SSL(self.mail_host)
  101. smtpObj.login(self.mail_user, self.mail_pass)
  102. smtpObj.sendmail(self.sender, self.receivers, message.as_string())
  103. print("邮件发送成功")
  104. except smtplib.SMTPException as e:
  105. print("Error: 无法发送邮件", e)
  106. class GotifyNotifier:
  107. def __init__(self, title, message, token='A8EVb0Cmxnb2vfk'):
  108. self.gotify_url = 'https://gotify.erhe.top'
  109. self.app_token = token
  110. self.title = title
  111. self.message = message
  112. def send_message(self):
  113. # 构建POST请求的headers
  114. headers = {
  115. 'Content-Type': 'application/json'
  116. }
  117. # 构建POST请求的body
  118. body = {
  119. 'title': self.title,
  120. 'message': self.message
  121. }
  122. # 发送POST请求
  123. with httpx.Client() as client:
  124. response = client.post(
  125. url=f"{self.gotify_url}/message?token={self.app_token}",
  126. headers=headers,
  127. json=body
  128. )
  129. # 检查响应状态码
  130. if response.status_code == 200:
  131. print('Gotify Message sent successfully!')
  132. else:
  133. print('Failed to send message:', response.text)
  134. if __name__ == '__main__':
  135. print("开始执行日志处理")
  136. LogsHandle().logs_send()
  137. print("处理日志程序执行完毕")