|
|
import os
|
|
|
import time
|
|
|
import threading
|
|
|
import random
|
|
|
import string
|
|
|
from flask import jsonify
|
|
|
import logging
|
|
|
from dotenv import load_dotenv
|
|
|
|
|
|
load_dotenv()
|
|
|
log_directory = os.getenv("JUNK_PATH", '/data/ww/py_sys_monitor/logs/junk')
|
|
|
|
|
|
def get_junk_file():
|
|
|
if not os.path.exists(log_directory):
|
|
|
return jsonify({"file_count": 0, "files": []})
|
|
|
|
|
|
files = [name for name in os.listdir(log_directory) if os.path.isfile(os.path.join(log_directory, name))]
|
|
|
file_count = len(files)
|
|
|
return jsonify({"file_count": file_count, "files": files})
|
|
|
|
|
|
def clean_junk_file(filenames):
|
|
|
if not os.path.exists(log_directory):
|
|
|
return jsonify({"message": "Files deleted successfully", "deleted_count": 0})
|
|
|
|
|
|
|
|
|
deleted_count = 0
|
|
|
for filename in filenames:
|
|
|
file_path = os.path.join(log_directory, filename)
|
|
|
try:
|
|
|
if os.path.isfile(file_path):
|
|
|
os.remove(file_path)
|
|
|
deleted_count += 1
|
|
|
except Exception as e:
|
|
|
logging.info(f'Failed to delete {file_path}. Reason: {e}')
|
|
|
|
|
|
return jsonify({"message": "Files deleted successfully", "deleted_count": deleted_count})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_random_filename():
|
|
|
"""生成一个以 `localhost_access_log_` 开头,十六位随机字符串结尾的日志文件名"""
|
|
|
random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
|
|
|
return f'localhost_access_log_{random_str}.log'
|
|
|
|
|
|
def check_and_create_logs():
|
|
|
"""检测日志文件夹,如果少于10个文件,则自动创建补满"""
|
|
|
file_num = 13
|
|
|
while True:
|
|
|
try:
|
|
|
if not os.path.exists(log_directory):
|
|
|
os.makedirs(log_directory)
|
|
|
|
|
|
files = os.listdir(log_directory)
|
|
|
if len(files) < file_num:
|
|
|
for _ in range(file_num - len(files)):
|
|
|
new_file = os.path.join(log_directory, generate_random_filename())
|
|
|
with open(new_file, 'w') as f:
|
|
|
f.write("") # 创建一个空文件
|
|
|
logging.info(f"已创建 {file_num - len(files)} 个新日志文件。")
|
|
|
# else:
|
|
|
# logging.info("日志文件数量正常,无需创建新文件。")
|
|
|
|
|
|
except Exception as e:
|
|
|
logging.info(f"检查或创建日志文件时发生错误: {e}")
|
|
|
|
|
|
time.sleep(600) # 每隔10分钟检测一次
|
|
|
|
|
|
thread = threading.Thread(target=check_and_create_logs)
|
|
|
thread.daemon = True # 设置为守护线程,这样它不会阻止程序退出
|
|
|
thread.start() |