linux自动清理日志的方法分享

linux自动清理日志的方法分享,第1张

1.做自动部署系统时精简的一个脚本,主要功能是清理所有目录的日志

2.根据给定日志目录,删除时间 结合crontab进行清理日志,清理完成后,后在/var/log/deltelog/ 生成按照月的清理日志

3.扩展,因为脚本采用mtime(最后修改时间)进行删除,所以可以适用于删除过期备份等,不受文件名称的限制

shell小窍门

find –type f –print 时会根据换行或者空格来输出查找的文件,在不同的sh下有不同的`反应,如果不做处理结合xargs 进行删除 更改 *** 作,会有影响

所以需要增加 –print0 用 null来 作为边界符号,才敢结婚 xargs –o 来格式化输入

使用find 的时候 遵循最小结果集原则,find解析式从左到右,所有确保你在最左边的过滤符号能够过滤最大数据

你可以根据你的需要增加到crontab中

shell脚本

复制代码 代码如下:

#!/bin/sh

###########################

# log blog.duplicatedcode.com

# in_day_num: like 1 2 is 2day ago logs

# in_log_path like tomcat log home

###########################

in_log_path=${1}

in_day_num=${2}

tmp__log=/var/log/log/"`date +%Y%m`.log"

Log()

{

inner_num=${1}

#find log

echo "[`date`] >>start logs---" >>$tmp__log

find ${in_log_path} -type f -mtime ${inner_num} -print0 | xargs -0 rm -rf

echo "[`date`] >>end logs---" >>$tmp__log

}

init()

{

mkdir -p /var/log/log/

}

main()

{

init

if [ -z ${in_log_path} ]then

echo "[`date`] >>error log_path not init---" >>$tmp__log

return

fi

inner_day_num=+7

if [[ -n ${in_day_num} ]] &&[[ ${in_day_num} -ge 1 ]] then

${inner_day_num}=${in_day_num}

fi

Log ${inner_day_num}

}

main

使用过Windows的人都知道,在使用windows系统的.过程中系统会变得越来越慢。而对于Windows下饱受诟病的各种垃圾文件都需要自己想办法删除,不然系统将会变得越来越大,越来越迟钝!windows怎么清理垃圾相信大家都知道的,那么linux下怎么清理系统垃圾呢?

Linux的文件系统比Windows的要优秀,不会产生碎片,对于长时间运行的服务器来说尤为重要,而且Linux系统本身也不会像Windows一样产生大量的垃圾文件。不知道这个说法有没有可信度!至少我们可以确定的是linux系统的文件系统是比较优秀的!

错误

rm -f logfile

原因

应用已经打开文件句柄,直接删除会造成:

1.应用无法正确释放日志文件和写入

2.显示磁盘空间未释放

正确

cat /dev/null >logfile

把一下代码保存为.sh后缀脚本来运行即可清除Linux系统日志

#!/bin/sh

cat /dev/null >/var/log/syslog

cat /dev/null >/var/adm/sylog

cat /dev/null >/var/log/wtmp

cat /dev/null >/var/log/maillog

cat /dev/null >/var/log/messages

cat /dev/null >/var/log/openwebmail.log

cat /dev/null >/var/log/maillog

cat /dev/null >/var/log/secure

cat /dev/null >/var/log/httpd/error_log

cat /dev/null >/var/log/httpd/ssl_error_log

cat /dev/null >/var/log/httpd/ssl_request_log

cat /dev/null >/var/log/httpd/ssl_access_log

另外清理linux系统垃圾还有以下命令

sudo apt-get autoclean 清理旧版本的软件缓存

sudo apt-get clean 清理所有软件缓存

sudo apt-get autoremove 删除系统不再使用的孤立软件

查看某个目录的文件大小并排序 (单位为MB)

清空 /var/log/journal 文件的方法

1、用echo命令,将空字符串内容重定向到指定文件中

echo "" >system.journal

2、journalctl 命令自动维护文件大小

1)只保留近一周的日志

journalctl --vacuum-time=1w

2)只保留500MB的日志

journalctl --vacuum-size=500M

3)直接删除 /var/log/journal/ 目录下的日志文件

rm -rf /var/log/journal/f9d400c5e1e8c3a8209e990d887d4ac1

问题与分析解决

执行 journalctl时报错:Error was encountered while opening journal files: Input/output error

问题分析:日志文件损坏

解决方法:删除之前的日志,并重启 journalctl 服务

然后,再执行 journalctl 限制日志的命令:


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/6067346.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-13
下一篇 2023-03-13

发表评论

登录后才能评论

评论列表(0条)

保存