utils_daily_logs_generate.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 设置每天 00:00:00 新建一个日志记录
  4. '''
  5. import os
  6. import sys
  7. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto_message')[0] + 'auto_message'))
  8. import time
  9. from datetime import datetime
  10. import pymongo
  11. from utils.utils_load_config import load_config, get_base_path
  12. config_json = load_config()
  13. base_project = 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. rss_base_url = 'http://home.erhe.link:20002/xmlfile/'
  27. class LogsHandle(object):
  28. def __init__(self):
  29. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  30. db = 'logs'
  31. collection = 'logs_' + self.now_day
  32. self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
  33. def logs_generate(self):
  34. data_to_insert = {
  35. "title": "logs",
  36. "context": 'generate message logs',
  37. "state": "create",
  38. "create_time": int(time.time()),
  39. "create_datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  40. }
  41. self.mongo.collection.insert_one(data_to_insert)
  42. class MongoHandle(object):
  43. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  44. self.client = pymongo.MongoClient(MONGO_LINK)
  45. self.db = db
  46. self.collection = collection
  47. if del_db and db:
  48. # 检查数据库是否存在
  49. if db in self.client.list_database_names():
  50. # 删除数据库
  51. self.client.drop_database(db)
  52. self.db = self.client[db]
  53. if del_collection and self.collection:
  54. # 检查集合是否存在
  55. if self.collection in self.db.list_collection_names():
  56. # 删除集合
  57. self.db.drop_collection(collection)
  58. self.collection = self.db[collection]
  59. if auto_remove:
  60. self.auto_remove_data(auto_remove)
  61. def write_data(self, data):
  62. self.collection.insert_one(data)
  63. def auto_remove_data(self, day):
  64. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  65. self.collection.delete_one({'_id': data['_id']})
  66. if __name__ == '__main__':
  67. print("新建当天日志记录...")
  68. LogsHandle().logs_generate()
  69. print("当天日志记录已创建...")