import os
import logging
import datetime
import subprocess
logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s %(message)s',
                    level=logging.INFO)

def clear_log():
    yesterday_one = str(datetime.date.today() - datetime.timedelta(days=1)).replace('-', '')
    # yesterday_timec_one = int(time.mktime(time.strptime(str(yesterday_one), '%Y-%m-%d')))

    yesterday_two = str(datetime.date.today() - datetime.timedelta(days=2)).replace('-', '')
    # yesterday_timec_two = int(time.mktime(time.strptime(str(yesterday_two), '%Y-%m-%d')))


    directory = '/var/log/'  # 指定目录路径
    clear_name = [
        f'messages-{yesterday_one}',
        f'messages-{yesterday_two}',
        'messages',
    ]
    log_files = [file for file in os.listdir(directory) if file in clear_name]
    logging.info(f"指定目录下以 .log 结尾的文件名:{log_files}")
    for i in log_files:
        command = f'rm -f /var/log/{i}'
        logging.info(f"{command}")
        try:
            # 执行终端命令并获取输出结果
            result = subprocess.check_output(command, shell=True)
            logging.info("命令执行成功！")
            logging.info(f"输出结果为: {result.decode()}\n")
        except subprocess.CalledProcessError as e:
            logging.info(f"命令执行失败！错误信息为:{e.stderr.decode()}\n", )


if __name__ == '__main__':
    clear_log()
