一、分析服务器日志
服务器日志分析,年月日 _Fatal/Info
二、开始编写(实现清除3天前创建的日志文件,即删除日志文件中时间是三天前的文件)
#coding=utf-8
import os,time,datetime
def strToTimestamp(time_st,format=’%Y%m%d%H%M%S’):
t=time.strptime(time_st,format) #把格式化好的时间转成时间元组
res = time.mktime(t) #时间元组转成时间戳
return res
def timestampToStr(time_strmp,format=’%Y%m%d%H%M%S’):
#时间戳转格式化好的时间
cur_time = time.localtime(time_strmp) #时间戳转成时间元组
res = time.strftime(format, cur_time) #再把时间元组转成格式化好的时间
return res
def clean_log(path):
if os.path.exists(path) and os.path.isdir(path):
today = datetime.date.today().strftime(’%Y-%m-%d’) # 2021-06-08
print(today)
yesterday = (datetime.date.today() + datetime.timedelta(-1)).strftime(’%Y-%m-%d’)
print(yesterday)
before_yesterday = (datetime.date.today() + datetime.timedelta(-2)).strftime(’%Y-%m-%d’)
print(before_yesterday)
file_name_list = [today, yesterday, before_yesterday]
for file in os.listdir(path):
#进行切割,替换
#把2021-06-03.Info.log
file_bs=file.replace(’_’,’.’)
file_name_sp = file_bs.split(’.’)
if len(file_name_sp) > 2:
file_date = file_name_sp[0] # 取文件名里面的日期
# print(type(file_date))
# print(type(file_name_list[0]))
if file_date not in file_name_list:
abs_path = os.path.join(path, file)
print(‘删除的文件是%s,’ % abs_path)
os.remove(abs_path)
else:
print(‘没有删除的文件是%s’ % file)
else:
print(‘路径不存在/不是目录’)
clean_log(r’C:\HK_Service\Weixin\Service\Logs’)
print(“运行完毕!”)
三、打包成exe放入服务器
pyinstaller -F logs.py
设置定时任务: