这几天在做算法平台,需要记录每个算法模块启动和运行的日志,但是又怕长时间运行,记录文件太大,导致写爆存储,故想之保留记录文件的最后N行来保证存储不会被写爆。
故开始问度娘要解决方案,网上提供了head和tail两个命令。
1. head命令
head命令用于显示文件文字区块,可以显示文件的前N行,例如:head -10 test.txt ,该命令会打印test.txt文件的前10行到终端。
2. tail命令
tail命令用于显示文件文字区块,可以显示文件的最后N行,例如:tail -10 test.txt ,该命令会打印test.txt文件的最后10行到终端。
我想让记录日志的文件之保留最后500行,尝试使用tail命令然后重定向的方式来实现,使用tail -500 test.txt > test.txt,但是使用该命令后test.txt文件直接被清空了,看来不能把输出重定向到自己。
然后接着尝试,使用比较折中的办法
方法一:
先把记录文件的最后500行重定向到另一个文件B,然后删除原有的文件,再把B文件修改为原有的记录文件名,经过试验该方法可以实现我想要的结果。命令如下:
tail -1000 test.txt > test1.txt && rm test.txt && mv test1.txt test.txt
方法二:
统计文件的行数
sed -n '$=' module-start-603-1.0.0-30110.log
例如统计有600行,我只需要后500行,所以删除100行
sed -i '1,100d' module-start-606-1.0.0-30115.log //这个指令的意思是删除前100行
利用方法二的思想实现一个定时器对服务器某目录下的日志文件进行行数管理,每个日志文件最多只保留500行
package com.supconit.data.algorithm.platform.executor.schedulerTask;
import com.supconit.data.algorithm.platform.common.entity.module.ModuleVersion;
import com.supconit.data.algorithm.platform.dao.module.AlgorithmModuleDAO;
import com.supconit.data.algorithm.platform.util.FileViewerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.scheduling.an