欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

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

一、简述

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

  

 

二、定期删除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集群的索引
###################################
function delete_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.01
        format_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 $LINE
done

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

 

posted @ 2019-01-03 11:24  宋兴柱  阅读(2627)  评论(0编辑  收藏  举报