linux添加日志清理任务,Linux中添加计划任务与Elasticsearch日志自动清理

一、简述

当日志发送到ELK之后,Elasticsearch随着日志的增加,占用磁盘量会越来越大。这时候,需要我们写角本定期DELETE日志。角本写法,也很简单,只是发送HTTP的DELETE方式到:http://:/*-yyyy.MM.dd*即可。

b8c92b38124fcb50942bc4e314107230.png

二、定期删除Elasticsearch中日志的角本:新建一个es-index-clear.sh到/opt目录下,内容如下:

#/bin/bash

#es-index-clear#只保留15天内的日志索引

LAST_DATA=`date -d "-15 days" "+%Y.%m.%d"`

#删除上个月份所有的索引

curl-XDELETE 'http://127.0.0.1:9200/*-'${LAST_DATA}'*'

三、使用crontab -e添加定时任务:执行crontab -e,在打开的内容中,输入(前面‘0  * * * *’表示Cron表达式,可以参考我前面的文章):

比如下列表示每小时整时执行一次:

0 * * * * /opt/es-index-clear.sh

如果要每天凌晨执行一次:

0 0 * * * /opt/es-index-clear.sh

四、启动定时任务,并开机自动运行

systemctl enable crond

systemctl restart crond

systemctl status crond

五、也可以把es-index-clear.sh内容换成其它优秀代码,如下:

#!/bin/bash

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

#删除早于十天的ES集群的索引

###################################functiondelete_indices() {

comp_date=`date -d "10 day ago" +"%Y-%m-%d"`

date1="$1 00:00:00"date2="$comp_date 00:00:00"t1=`date -d "$date1" +%s`

t2=`date -d "$date2" +%s`if [ $t1 -le $t2 ]; then

echo "$1时间早于$comp_date,进行索引删除"#转换一下格式,将类似2017-10-01格式转化为2017.10.01format_date=`echo $1| sed 's/-/./g'`

curl-XDELETE http://127.0.0.1:9200/*$format_date

fi}

curl-XGET http://127.0.0.1:9200/_cat/indices | awk -F" " '{print $3}' | awk -F"-" '{print $NF}' | egrep "[0-9]*.[0-9]*.[0-9]*" | sort | uniq | sed 's/./-/g' | while read LINE

do#调用索引删除函数

delete_indices $LINEdone

六、删除完后,再看占用量:

be1740327667a64a9677d61887f11e76.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值