定时日志清理

 

作用:

针对的log目录是家目录的.ros文件夹,目录结构是/home/xxx/.ros/log/latest

.ros中除了log文件夹,其他缓存文件全部清除

然后就是log文件夹里面,这里面就是真正的log文件了,会有很多文件夹,每次重启,都会在log目录生成日志文件夹如:swswdedefraa-323232-wswdededeede,该文件夹会被打包,放到/opt/xxx/logs中,还有一些.log文件,.log文件全部清除

首先来说打包,默认情况下,我们保留/home/xxx/.ros/log/目录中三个最新的日志文件夹,其他的会被打包到/opt/xxx/logs,并且删除文件夹,打包后要检查是否大于50M,如果大于50M就会分割为20M的文件分段存储,

接着 判断/home/xxx/.ros/log/的目录大小,如果大于800M,就会只保留一个最新的文件夹,其他的全部压缩,删除

还要检查/opt/xxx/logs,如果大于1G,那就删除旧的压缩包,直到他的大小小于1G。

加个定时任务,定时执行该脚本,就可以做到日志自动备份清除。

#-*- encoding=utf8 -*-
import time 
import os
import sys
import math
import zipfile
import tarfile
import commands
from os.path import join, getsize
fpath="/home/xxx/"
targetpath="/opt/xxx/logs/"
chunksize = 20*(1024**2)
log_path=fpath+".ros/"+"log/"

def get_FileSize(filePath):
    fsize = os.path.getsize(filePath)
    #fsize = fsize/float(1024*1024)
    #return round(fsize,5)
    return fsize
def getdirsize(dirpath):
    size = 0
    for root, dirs, files in os.walk(dirpath):
        size += sum([getsize(join(root, name)) for name in files])
    return size
def get_time_stamp(ct):
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y-%m-%d--%H:%M:%S", local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s:%03d" % (data_head, data_secs)
    return time_stamp
def fileTime(file):
    #time.ctime(os.path.getatime(file))
    return [
        os.path.getatime(file),
        os.path.getctime(file),
        os.path.getmtime(file)
    ]
def make_targz(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))
def make_targz_one_by_one(output_filename, source_dir):
    tar = tarfile.open(output_filename,"w:gz")
    for root,dir,files in os.walk(source_dir):
        for file in files:
            pathfile = os.path.join(root, file)
            tar.add(pathfile)
    tar.close()

def del_tar(tar_list):
    if(getdirsize(targetpath)<=1024*(1024**2)):
        return 1
    else:
        i=tar_list.pop()
        print("delete "+i[0]+" successfully!")
        os.remove(targetpath+i[0])
        return del_tar(tar_list)

def split(fromfile,todir,chunksize):
    partnum = 0
    file_name=os.path.basename(fromfile)
    inputfile = open(fromfile,'rb')#open the fromfile
    while True:
        chunk = inputfile.read(chunksize)
        if not chunk:             #check the chunk is empty
            break
        partnum += 1
        filename = os.path.join(todir,('{0}-({1}).tar.gz'.format(file_name.split(".")[0],partnum)))
        fileobj = open(filename,'wb')#make partfile
        fileobj.write(chunk)         #write data into partfile
        fileobj.close()
    return partnum
file_dic={}
filetwo_dic={}
tar_dic={}
sorted_list=[]
if(os.path.exists(fpath+".ros")):
    file_list=os.listdir(fpath+".ros")
    if(file_list):
        if("log" in file_list):
            file_list.remove("log")
        if(file_list):
            for j in file_list:
                status, output = commands.getstatusoutput("sudo rm -rf "+fpath+j)
                if(not status):
                    print("delete .ros/ successfully!")

if(os.path.exists(log_path)):
    sh="sudo rm -rf "+fpath+".ros/log/*.log"
    status, output = commands.getstatusoutput(sh)
    if(not status):
        print("delete *.log successfully!")
    file_list=os.listdir(log_path)
    if(file_list):
        if("latest" in file_list):
            file_list.remove("latest")
        if(file_list):
            if(len(file_list)>3):
                for i in file_list:
                    file_dic[i]=fileTime(log_path+i)[2]
                ccc=sorted(file_dic.items(),key = lambda x:x[1],reverse = True)[3:]
                sorted_list=[x for x in ccc if os.path.isdir(log_path+x[0])]
                for j in sorted_list:
                    print("to tar...")
                    t_tar=targetpath+get_time_stamp(os.path.getmtime(log_path+j[0]))+".tar.gz"
                    if(os.path.exists(t_tar)):
                        os.remove(t_tar)
                        print("remove already exist file!")
                    print(t_tar)
                    try:
                        make_targz(t_tar,log_path+j[0])
                    except Exception as e:
                        print(e)
                    print("to delete file...")
                    status, output = commands.getstatusoutput("sudo rm -rf "+log_path+j[0])
                    print("delete ok!")
                    if(not status):
                        print("delete .ros/log successfully!")
                    if(get_FileSize(t_tar)>(50*(1024**2))):
                        try:
                            parts = split(t_tar,targetpath,chunksize)
                            print("split ok!")
                        except:
                            print('Error during split:')
                            print(sys.exc_info()[0],sys.exc_info()[1])
                        else:
                            print("DELETE old tar")
                            os.remove(t_tar)
                            print("delete success!!!")
            if(getdirsize(log_path)>=800*(1024**2)):
                if(len(file_list)==1):
                    pass
                else:
                    for i in file_list:
                        filetwo_dic[i]=fileTime(log_path+i)[2]
                    ccc=sorted(filetwo_dic.items(),key = lambda x:x[1],reverse = True)[1:]
                    sorted_list=[x for x in ccc if os.path.isdir(log_path+x[0])]
                    for j in sorted_list:
                        print("to tar...")
                        t_tar=targetpath+get_time_stamp(os.path.getmtime(log_path+j[0]))+".tar.gz"
                        if(os.path.exists(t_tar)):
                            os.remove(t_tar)
                            print("remove already exist file!")
                        print(t_tar)
                        try:
                            make_targz(t_tar,log_path+j[0])
                        except Exception as e:
                            print(e)
                        print("to delete file...")
                        status, output = commands.getstatusoutput("sudo rm -rf "+log_path+j[0])
                        print("delete ok!")
                        if(not status):
                            print("delete .ros/log successfully!")
                        if(get_FileSize(t_tar)>(50*(1024**2))):
                            try:
                                parts = split(t_tar,targetpath,chunksize)
                                print("split ok!")
                            except:
                                print('Error during split:')
                                print(sys.exc_info()[0],sys.exc_info()[1])
                            else:
                                print("DELETE old tar")
                                os.remove(t_tar)
                                print("delete success!!!")
if(os.path.exists(targetpath)):
    file_list=os.listdir(targetpath)
    if(file_list):
        if("server.log" in file_list):
            file_list.remove("server.log")
        if(file_list):
            for i in file_list:
                tar_dic[i]=fileTime(targetpath+i)[2]
            tar_list=sorted(tar_dic.items(),key = lambda x:x[1],reverse = True)
            if(del_tar(tar_list)):
                print("tar directory checked!")
            

 

转载于:https://www.cnblogs.com/sea-stream/p/10242190.html

### 回答1: 在Linux中,可以使用crontab命令来定时清理日志文件。具体步骤如下: 1. 打开终端,输入以下命令来编辑crontab文件: ``` crontab -e ``` 2. 在打开的编辑器中添加如下内容,表示每天凌晨2点清理日志文件: ``` 0 2 * * * rm /path/to/log/files/*.log ``` 其中,`/path/to/log/files`是日志文件的路径,`*.log`表示删除该路径下所有以`.log`为后缀的文件。 3. 保存并退出编辑器。现在,crontab将在每天凌晨2点定时执行这个清理操作,从而自动删除指定目录下的日志文件。 ### 回答2: 在Linux系统中,日志文件是必不可少的组成部分,它可以记录系统运行过程中发生的各种事件和错误,并对问题排查、优化性能等方面提供支持。但是,由于日志文件会占据大量磁盘空间,如果不及时清理可能会导致磁盘空间不足的问题,从而影响系统运行。因此,定时清理日志文件是很有必要的。 以下是在Linux系统上定时清理日志文件的一些方法: 1. 使用logrotate logrotate是一款Linux系统中用于专门管理日志文件的工具,它支持各种日志文件的定期滚动、压缩和删除等操作。logrotate的配置文件在/etc目录下,可以设置生效时间、日志保存数量、压缩、提醒等属性。例如,执行以下命令可以每周清理/var/log目录下的所有日志文件: ``` 0 0 * * 0 /usr/sbin/logrotate /etc/logrotate.conf ``` 2. 使用Cron Job Cron是一款在Linux系统中定时执行任务的工具,可以用来定时清理日志文件。可以使用Cron Job来清理Linux系统中的日志文件,比如将所有日志文件压缩归档,只保留30天以上的文件,然后将压缩的日志文件上传到远程机器备份。例如,执行以下命令可以每月清理/var/log目录下的所有日志文件: ``` 0 0 1 * * /usr/bin/find /var/log -name "*.log" -mtime +30 -exec tar -cvzf /tmp/mylog.tar.gz {} \; && scp /tmp/mylog.tar.gz user@example.com:/backup/ ``` 3. 使用系统自带工具 Linux系统还自带一些其他工具可以清理日志文件,例如,使用find命令和xargs命令。 find命令可以查找特定的文件,xargs命令可以对查找的文件进行操作。例如,执行以下命令可以每天清理/var/log目录下7天前的所有日志文件: ``` 0 0 * * * find /var/log -mtime +7 -name "*.log" -type f -print0 | xargs -0 rm -f ``` 总之,定时清理日志文件是Linux系统管理的必要操作,它可以节省磁盘空间并提高系统的稳定性和性能。根据实际情况和需要,可以选择不同的工具和方法来实现这个目的。 ### 回答3: Linux系统中,有很多日志文件会随着时间的推移不断地增加,从而占据磁盘空间,并使磁盘使用效率降低。为了避免这种情况的出现,我们可以使用定时清理日志文件的方法。 Linux中定时清理日志文件有很多种方式,这里我将介绍两种常用的方法。 1. 使用logrotate命令 logrotate命令是Linux系统中一个用于管理日志文件的实用工具,它可以根据规则自动地旋转、清理和压缩日志文件,从而避免日志文件过多占用磁盘空间。使用logrotate的步骤如下: (1)编辑配置文件。 在/etc/logrotate.d目录下创建一个新的文件,命名为需要清理日志文件名。例如,如果要清理nginx服务器的访问日志,可以创建一个文件/etc/logrotate.d/nginx,将下列配置内容复制至该文件中: /var/log/nginx/access.log { daily rotate 7 compress delaycompress missingok notifempty create 0644 root root } 其中,daily表示每天执行一次清理操作,rotate 7表示保留7个备份文件,compress表示压缩备份文件,missingok表示如果日志文件不存在,则跳过不做处理,notifempty表示如果日志文件为空,则跳过不做处理,create 0644 root root表示创建新日志文件的权限和属主。 (2)测试logrotate配置。 使用以下命令可以测试logrotate配置是否正确: logrotate -d /etc/logrotate.d/nginx 该命令会列出logrotate将要执行的操作,如果显示正确,则可以执行下一步。 (3)添加日志清理任务。 使用以下命令将任务添加到cron表中: 0 0 * * * /usr/sbin/logrotate /etc/logrotate.d/nginx >/dev/null 2>&1 该命令表示每天午夜12点执行一次logrotate命令,/dev/null是输出到空设备,2>&1是将错误信息输出到标准输出(即/dev/null) 2. 使用systemd-tmpfiles 使用systemd-tmpfiles也可以清理日志文件,它是systemd工具的一部分,可以用于管理临时文件和目录。使用systemd-tmpfiles的步骤如下: (1)编辑配置文件。 在/etc/tmpfiles.d目录下创建一个新的文件,命名为需要清理日志文件名。例如,如果要清理/var/log/nginx/access.log文件,可以创建一个文件/etc/tmpfiles.d/nginx.conf,将下列配置内容复制至该文件中: #Type Path Mode Age Argument r /var/log/nginx/access.log 0644 7d - 其中,r表示删除目标文件,/var/log/nginx/access.log是目标文件的路径,0644是创建新日志文件的权限和属主,7d表示删除7天以前的文件,-表示没有额外的参数。 (2)添加日志清理任务。 使用以下命令将任务添加到cron表中: 0 0 * * * /usr/bin/systemd-tmpfiles --clean >/dev/null 2>&1 该命令表示每天午夜12点执行一次systemd-tmpfiles命令,--clean选项用于清理临时文件和目录,/dev/null是输出到空设备,2>&1是将错误信息输出到标准输出(即/dev/null)。 综上所述,以上两种方法都可以使Linux系统自动清理日志文件,避免磁盘空间不足的情况。如果需要清理其他类型的日志文件,也可以根据需要修改以上方法的配置文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值