utils_daily_logs_generate.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 设置每天 00:00:00 新建一个日志记录
  4. '''
  5. import os
  6. import time
  7. from datetime import datetime
  8. import pymongo
  9. import tools_load_config
  10. config_json = tools_load_config.load_config()
  11. base_project = tools_load_config.get_base_path()
  12. PROJECT_NAME = config_json.get('PROJECT_NAME')
  13. DB_USER = config_json.get('DB_USER')
  14. DB_PASSWORD = config_json.get('DB_PASSWORD')
  15. DB_IP = config_json.get('DB_IP')
  16. DB_PORT = config_json.get('DB_PORT')
  17. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  18. MAIL_HOST = config_json.get('MAIL_HOST')
  19. MAIL_USER = config_json.get('MAIL_USER')
  20. MAIL_PASS = config_json.get('MAIL_PASS')
  21. MAIL_SENDER = config_json.get('MAIL_SENDER')
  22. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  23. now_day = time.strftime('%Y-%m-%d', time.localtime())
  24. rss_base_url = 'http://home.erhe.link:20002/xmlfile/'
  25. class LogsHandle(object):
  26. def __init__(self):
  27. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  28. db = 'logs'
  29. collection = 'logs_' + self.now_day
  30. self.mongo = MongoHandle(db=db, collection=collection, del_db=False, del_collection=False, auto_remove=0)
  31. def logs_generate(self):
  32. data_to_insert = {
  33. "title": "logs",
  34. "context": 'generate logs',
  35. "state": "create",
  36. "create_time": int(time.time()),
  37. "create_datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  38. }
  39. self.mongo.collection.insert_one(data_to_insert)
  40. class MongoHandle(object):
  41. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  42. self.client = pymongo.MongoClient(MONGO_LINK)
  43. self.db = db
  44. self.collection = collection
  45. if del_db and db:
  46. # 检查数据库是否存在
  47. if db in self.client.list_database_names():
  48. # 删除数据库
  49. self.client.drop_database(db)
  50. self.db = self.client[db]
  51. if del_collection and self.collection:
  52. # 检查集合是否存在
  53. if self.collection in self.db.list_collection_names():
  54. # 删除集合
  55. self.db.drop_collection(collection)
  56. self.collection = self.db[collection]
  57. if auto_remove:
  58. self.auto_remove_data(auto_remove)
  59. def write_data(self, data):
  60. self.collection.insert_one(data)
  61. def auto_remove_data(self, day):
  62. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  63. self.collection.delete_one({'_id': data['_id']})
  64. if __name__ == '__main__':
  65. print("新建当天日志记录...")
  66. LogsHandle().logs_generate()
  67. print("当天日志记录已创建...")