100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python自动定期清理日志脚本支持Linux+windows

python自动定期清理日志脚本支持Linux+windows

时间:2020-05-22 02:35:26

相关推荐

python自动定期清理日志脚本支持Linux+windows

1 直接上代码

# -*-coding:utf-8-*- #Linux定时执行方式:# 需要单独执行下面定时命令(每天凌晨一点执行)# 添加任务之前请检查 systemctl status crond 是否为开启状态。# echo '0 1 * * * python3 /etc/init.d/Clear_Log.py' >> /var/spool/cron/root# 查看当前用户的定时任务:crontab -limport loggingimport os.pathimport time, datetimetry:import yamlexcept Exception as e:print("检测到没有安装yaml正在尝试安装")os.system("pip3 install pyyaml ")import yamlclass ClearLog(object):Log_level = {'debug': logging.DEBUG,'info': logging.INFO,'warning': logging.WARNING,'error': logging.ERROR,'critical': logging.CRITICAL}def __init__(self, out_log_path, name, day, log_file_list, level='info', write_to_log=1):self.day = dayself.level = levelself.log_file_list = log_file_listself.name = nameself.sysdate = datetime.date.today()self.WriteToLog = write_to_log# 创建一个日志器self.logger = logging.getLogger(out_log_path)# 创建一个日志处理器sh = logging.StreamHandler()# 设置日志等级self.logger.setLevel(self.Log_level.get(self.level))# 创建一个日志格式器fmt = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'formatter = logging.Formatter(fmt)# 将格式进行日志处理器sh.setFormatter(formatter)# 将处理器进行处理self.logger.addHandler(sh)# 日志写入处理if self.WriteToLog == 1:log_write = logging.FileHandler(out_log_path, mode='a', encoding='utf-8')self.logger.addHandler(log_write)else:passdef log_clear(self):time.sleep(2)systime = datetime.datetime.now()self.logger.info("""************开始执行删除日志程序,执行时间:{}********************Start""".format(systime))self.logger.info("开始删除{}天前文件后缀包含{}的日志文件...".format(self.day, self.name))log_num = 0log_size1 = 0for logfile in self.log_file_list:self.logger.info('正确检查是否有可删除的日志:' + logfile)for log_path, dir_name, dir_filename in os.walk(logfile):self.logger.info('正在清除路径下的日志:' + log_path)for log_name in dir_filename:try:log_file = log_path + "/" + log_namecreate_timer = os.path.getmtime(log_file)create_date = datetime.datetime.fromtimestamp(create_timer).date()except IOError:self.logger.error("获取文件错误请检查路径是否正确!")continueelse:log_name = log_name.split('.')[-1]date_difference = self.sysdate - create_datedate_difference = int(date_difference.days)if date_difference >= self.day and log_name in self.name:log_num += 1log_size = os.path.getsize(log_file)log_size1 = log_size1 + log_size# print(log_size)try:os.remove(log_file)except:self.logger.info("删除失败,跳过:{}".format(log_file))passself.logger.info("已删除文件:{}".format(log_file))if log_num <= 0:time.sleep(1)self.logger.info("没有需要删除的日志文件或者文件路径错误!", )self.logger.info("**************结束...**************END")time.sleep(5)else:log_size1 = round(log_size1 / 1024 / 1024, 2)self.logger.info("***************一共删除文件:{}个,共{}MB。**************END".format(log_num, log_size1))def run():sysdate = datetime.date.today()# 获取当前工作路径current_path = os.path.dirname(os.path.realpath(__file__))try:os.mkdir(r"./LogClear/")except IOError:passClearLog_path = r"./LogClear/"# print(current_path)default_out_log_path = ClearLog_path + str(sysdate) + 'ClearLog.log'f = open(current_path + r'/settings.yml', 'r', encoding='utf-8')yaml.warnings({'YAMLLoadWarning': False})data = yaml.load_all(f, Loader=yaml.SafeLoader)for a in data:name = a["name"]day = a["day"]log_file_list = a["log_file_list"]write_out_log = a["write_out_log"]log_file_extension = a["log_file_extension"]sleep_time = a["sleep_time"]if log_file_extension is None:log_file_extension = 0if a["out_log_path"] is None:out_log_path = default_out_log_pathprint("日志输出路径:", out_log_path)else:out_log_path = a["out_log_path"]out_log_level = a["out_log_level"]lists = []for i in range(1, log_file_extension):lists.append(str(i))log_name = name + listslog = ClearLog(out_log_path=out_log_path, name=log_name, day=day, log_file_list=log_file_list,level=out_log_level, write_to_log=write_out_log)log.log_clear()try:sleep_time = int(sleep_time)except (TypeError, ValueError):passelse:log.logger.info("定时任务已开启。正在执行定时清理...")while True:for i in range(sleep_time, 0, -1):m, s = divmod(i, 60)h, m = divmod(m, 60)print("\r", "定时清理任务运行中...!{}小时{}分{}秒后开始执行。".format(h, m, s), end="", flush=True)time.sleep(1)if i == 1:log.log_clear()if __name__ == '__main__':try:run()except Exception as e:print(e, "运行失败!请检查配置文件!")input("\n")

配置文件

settings.yml

#需要删除的日志文件名称格式后缀name: ['log', 'gz', 'zip', 'rar','21212']#日志文件名称后缀,一个整数,比如输入99 删除的文件就会包含1~99数字结尾的日志文件,默认为0log_file_extension: 5#需要删除几天前的日志 默认为7天前的day: 1#日志文件夹目录路径列表,路径请用单引号 如 ['/d/a/a','/a/a/a']log_file_list: ['E:\python-object\linux_ssh\script\LogClear\LogClear','']#执行日志是否写入文件 1 写入 0 不写入 默认为1write_out_log: 1#执行日志写入目录 默认为当前目录 /LogClear/"out_log_path:#日志等级默认为:infoout_log_level: debug# 是否启动定时任务,空为关闭,单位为秒Ssleep_time:

python可以打包成.exe

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。