base_daily_logs_send.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 设置每天 23:59 执行, 读取当天数据库中, 所有日志, 发送到指定邮箱
  4. '''
  5. import os
  6. import sys
  7. import time
  8. import httpx
  9. import pymongo
  10. sys.path.append(os.path.join(os.path.abspath(__file__).split('AutoInfo')[0] + 'AutoInfo'))
  11. from utils.utils import LoadConfig
  12. config_json = LoadConfig().load_config()
  13. base_project = LoadConfig().get_base_path()
  14. PROJECT_NAME = config_json.get('PROJECT_NAME')
  15. DB_USER = config_json.get('DB_USER')
  16. DB_PASSWORD = config_json.get('DB_PASSWORD')
  17. DB_IP = config_json.get('DB_IP')
  18. DB_PORT = config_json.get('DB_PORT')
  19. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  20. MAIL_HOST = config_json.get('MAIL_HOST')
  21. MAIL_USER = config_json.get('MAIL_USER')
  22. MAIL_PASS = config_json.get('MAIL_PASS')
  23. MAIL_SENDER = config_json.get('MAIL_SENDER')
  24. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  25. now_day = time.strftime('%Y-%m-%d', time.localtime())
  26. class LogsHandle(object):
  27. def __init__(self):
  28. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  29. db = 'logs'
  30. collection = 'logs_' + self.now_day
  31. self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
  32. def logs_send(self):
  33. title = 'AutoInfo message - daily logs: {}'.format(self.now_day)
  34. text = ''
  35. # TODO
  36. # 从 mongodb 读取日志, 拼接 text, 发送邮件
  37. # 查询所有文档
  38. query = {'state': 'error'}
  39. cursor = self.mongo.collection.find(query)
  40. # 遍历结果集
  41. for record in cursor:
  42. text += "logs_source: {}, logs_detail: {}, state: {} logs_create_time: {}\n\n".format(
  43. record.setdefault('title'),
  44. record.setdefault('content'),
  45. record.setdefault('state'),
  46. record.setdefault('create_datetime'),
  47. )
  48. if text:
  49. G = GotifyNotifier(title=title, message=text, token_name='base')
  50. G.send_message()
  51. else:
  52. print("No error logs found for today.")
  53. class MongoHandle(object):
  54. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  55. self.client = pymongo.MongoClient(MONGO_LINK)
  56. self.db = db
  57. self.collection = collection
  58. if del_db and db:
  59. # 检查数据库是否存在
  60. if db in self.client.list_database_names():
  61. # 删除数据库
  62. self.client.drop_database(db)
  63. self.db = self.client[db]
  64. if del_collection and self.collection:
  65. # 检查集合是否存在
  66. if self.collection in self.db.list_collection_names():
  67. # 删除集合
  68. self.db.drop_collection(collection)
  69. self.collection = self.db[collection]
  70. if auto_remove:
  71. self.auto_remove_data(auto_remove)
  72. def write_data(self, data):
  73. self.collection.insert_one(data)
  74. def auto_remove_data(self, day):
  75. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  76. self.collection.delete_one({'_id': data['_id']})
  77. class GotifyNotifier:
  78. def __init__(self, title, message, token_name='A52cfQ1UZ2e.Z0B'):
  79. self.gotify_url = 'https://gotify.erhe.top'
  80. self.app_token = token_name
  81. self.title = title
  82. self.message = message
  83. def send_message(self):
  84. # 发送POST请求
  85. with httpx.Client() as client:
  86. response = client.post(
  87. url=f"{self.gotify_url}/message?token={self.app_token}",
  88. headers={'Content-Type': 'application/json'},
  89. json={'title': self.title, 'message': self.message}
  90. )
  91. # 检查响应状态码
  92. if response.status_code == 200:
  93. print('Gotify Message sent successfully!')
  94. else:
  95. print('Failed to send message:', response.text)
  96. if __name__ == '__main__':
  97. print("开始执行日志处理")
  98. LogsHandle().logs_send()
  99. print("处理日志程序执行完毕")