zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    php获取http请求原文
    windows下安装MongoDB服务
    微服务RESTful 接口设计规范
    mysql主从复制原理及步骤
    nodejs主要框架
    redis事务机制和分布式锁
    计算机专业学生一定要学好这几门课
    redis常见7种使用场景
    js类型判断
    SQL语句:case when then的用法
  • 原文地址:https://www.cnblogs.com/songxingzhu/p/10213230.html
Copyright © 2011-2022 走看看