• ELK Stack实践


    一、ELK搭建篇

    官网地址:https://www.elastic.co/cn/

    官网权威指南:https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html

    安装指南:https://www.elastic.co/guide/en/elasticsearch/reference/2.x/rpm.html

    ELK是Elasticsearch、Logstash、Kibana的简称,这三者是核心套件,但并非全部。

    Elasticsearch是实时全文搜索和分析引擎,提供搜集、分析、存储数据三大功能;是一套开放REST和JAVA API等结构提供高效搜索功能,可扩展的分布式系统。它构建于Apache Lucene搜索引擎库之上。

    Logstash是一个用来搜集、分析、过滤日志的工具。它支持几乎任何类型的日志,包括系统日志、错误日志和自定义应用程序日志。它可以从许多来源接收日志,这些来源包括 syslog、消息传递(例如 RabbitMQ)和JMX,它能够以多种方式输出数据,包括电子邮件、websockets和Elasticsearch。

    Kibana是一个基于Web的图形界面,用于搜索、分析和可视化存储在 Elasticsearch指标中的日志数据。它利用Elasticsearch的REST接口来检索数据,不仅允许用户创建他们自己的数据的定制仪表板视图,还允许他们以特殊的方式查询和过滤数据

    环境

    Centos6.5 两台IP:192.168.1.224 安装: elasticsearch、logstash、Kibana、Nginx、Redis
              192.168.1.157 安装:  elasticsearch  (两台都关闭iptables和SElinux)

    安装

    安装elasticsearch的yum源的密钥(这个需要在所有服务器上都配置)
    rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch 
    
    配置elasticsearch的yum源,在elasticsearch.repo文件中添加如下内容
    vim /etc/yum.repos.d/elasticsearch.repo
    [elasticsearch-2.x]
    name=Elasticsearch repository for 2.x packages
    baseurl=https://packages.elastic.co/elasticsearch/2.x/centos
    gpgcheck=1
    gpgkey=https://packages.elastic.co/GPG-KEY-elasticsearch
    enabled=1

    安装elasticsearch的环境

    安装elasticsearch
    # yum install -y elasticsearch
    
    安装java环境(java环境必须是1.8版本以上的)
    1.tar zxvf ./jdk-8u151-linux-x64.tar.gz -C /usr/lib/jvm
    2.用命令vim /etc/bashrc文件,在文件最后面加上:
    export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_151
    export JRE_HOME=${JAVA_HOME}/jre
    exportCLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
    export PATH=${JAVA_HOME}/bin:$PATH
    3.更新环境变量
    source  /etc/bashrc
    4.验证是否安装成功
    java -version
    echo  $PATH

    创建elasticsearch data的存放目录,并修改该目录的属主属组

    # mkdir -p /data/es-data   (自定义用于存放data数据的目录)
    # chown -R elasticsearch:elasticsearch /data/es-data

    修改elasticsearch的日志属主属组

    # chown -R elasticsearch:elasticsearch /var/log/elasticsearch/

    修改elasticsearch的配置文件

    # vim /etc/elasticsearch/elasticsearch.yml
    
    #找到配置文件中的cluster.name,打开该配置并设置集群名称
    cluster.name: oldboy
    
    #找到配置文件中的node.name,打开该配置并设置节点名称
    node.name: ywxi-1 
    #修改data存放的路径
    path.data: /data/es-data 
    #修改logs日志的路径
    path.logs: /var/log/elasticsearch/
    
    #配置内存使用用交换分区
    bootstrap.memory_lock: true
    #监听的网络地址
    network.host: 0.0.0.0 
    #开启监听的端口
    http.port: 9200  
    #关掉广播地址传播
    discovery.zen.ping.multicast.enabled: false 
    #指定局域网IP,让他们找到集群
    discovery.zen.ping.unicast.hosts: ["192.168.1.224","192.168.1.157"]

    启动服务

    [root@al7 elasticsearch]# /etc/init.d/elasticsearch start
    Starting elasticsearch: Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x0000000085330000, 2060255232, 0) failed; error='Cannot allocate memory' (errno=12)
    #
    # There is insufficient memory for the Java Runtime Environment to continue.
    # Native memory allocation (mmap) failed to map 2060255232 bytes for committing reserved memory.
    # An error report file with more information is saved as:
    # /tmp/hs_err_pid2616.log
                                                               [FAILED]
    这个报错是因为默认使用的内存大小为2G,虚拟机没有那么多的空间
    
    修改参数:
    vim /etc/elasticsearch/jvm.options
    -Xms512m
    -Xmx512m
    
    再次启动
    /etc/init.d/elasticsearch start查看服务状态,如果有报错可以去看错误日志 less /var/log/elasticsearch/demon.log(日志的名称是以集群名称命名的)
    
    创建开机自启动服务
    # chkconfig elasticsearch on

    注意事项

    vim /etc/security/limits.conf  #开启elasticsearch用户锁住内存
    # allow user 'elasticsearch' mlockall
    elasticsearch soft memlock unlimited
    elasticsearch hard memlock unlimited
    
    [root@227 elasticsearch]# /etc/init.d/elasticsearch restart                         
    Stopping elasticsearch:                                    [FAILED]
    Starting elasticsearch: Exception in thread "main" java.lang.IllegalStateException: marvel plugin requires the license plugin to be installed
            at org.elasticsearch.marvel.license.LicenseModule.verifyLicensePlugin(LicenseModule.java:37)
            at org.elasticsearch.marvel.license.LicenseModule.<init>(LicenseModule.java:25)
            at org.elasticsearch.marvel.MarvelPlugin.nodeModules(MarvelPlugin.java:89)
            at org.elasticsearch.plugins.PluginsService.nodeModules(PluginsService.java:263)
            at org.elasticsearch.node.Node.<init>(Node.java:179)
            at org.elasticsearch.node.Node.<init>(Node.java:140)
            at org.elasticsearch.node.NodeBuilder.build(NodeBuilder.java:143)
            at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:194)
            at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:286)
            at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:45)
    Refer to the log for complete error details.
                                                               [FAILED]
    报错解决: /usr/share/elasticsearch/bin/plugin install license  #安装下插件解决

    通过浏览器请求下9200的端口,看下是否成功

    先检查9200端口是否起来
    [root@al7 elasticsearch]# netstat -tnlp|grep 9200
    tcp        0      0 :::9200                     :::*                        LISTEN      4760/java

    如何和elasticsearch交互

    JavaAPI
    
    RESTful API
    Javascript,.Net,PHP,Perl,Python
    
    利用API查看状态# curl -i -XGET 'localhost:9200/_count?pretty' 
        HTTP/1.1 200 OK
        content-type: application/json; charset=UTF-8
        content-length: 95
    
        {      "count" : 0,      "_shards" : {        "total" : 0,        "successful" : 0,        "failed" : 0
          }
        }

    安装插件

    安装elasticsearch-head插件1  /usr/share/elasticsearch/bin/plugin install mobz/elasticsearch-head
    #访问 http://192.168.1.224:9200/_plugin/head
    
    安装插件2 ES监控 /usr/share/elasticsearch/bin/plugin install lmenezes/elasticsearch-kopf
    #访问 http://192.168.1.224:9200/_plugin/kopf
    浏览器访问:http://192.168.1.224:9200/_plugin/head/    #ywxi-1和ywxi-2是我这里搭的节点,另外两个是同事的节点

    image.png

    LogStash的使用

    安装Logstash环境:
    
    官方安装手册:
    https://www.elastic.co/guide/en/logstash/current/installing-logstash.html
    
    下载yum源的密钥认证:
    # rpm --import https://packages.elastic.co/GPG-KEY-elasticsearch
    #配置logstash的yum源,在logstash.repo文件中添加如下内容
    vim logstash.repo
    [logstash-2.4]
    name=Logstash repository for 2.4.x packages
    baseurl=https://packages.elastic.co/logstash/2.4/centos
    gpgcheck=1
    gpgkey=https://packages.elastic.co/GPG-KEY-elasticsearch
    enabled=1
    
    # yum install -y logstash
    查看下logstash的安装目录
    # rpm -ql logstash
    
    #创建一个软连接,每次执行命令的时候不用在写安装路劲(默认安装在/usr/share下)ln -s /opt/logstash/bin/logstash /bin/
    
    执行logstash的命令
    # logstash -e 'input { stdin { } } output { stdout {} }'运行成功以后输入:
    nihao
    
    stdout返回的结果:

    image.png

    注:
       -e 执行操作 input 标准输入
       { input } 插件  output  标准输出
       { stdout }  插件  
    
    通过rubydebug来输出下更详细的信息
    # logstash -e 'input { stdin { } } output { stdout {codec => rubydebug} }'
    
    执行成功输入:
    nihao
    
    stdout输出的结果:

    image.png

    如果标准输出还有elasticsearch中都需要保留应该怎么玩,看下面
    # logstash -e 'input { stdin { } } output { elasticsearch { hosts => ["192.168.1.224:9200"] } stdout { codec => rubydebug }}'
    
    运行成功以后输入:
    I am elk
    
    返回的结果(标准输出中的结果):

    image.png

    logstash使用配置文件

    官方指南:https://www.elastic.co/guide/en/logstash/current/configuration.html  
    创建配置文件01-logstash.conf
    # vim /etc/logstash/conf.d/elk.conf 文件中添加以下内容input { stdin { } }output {  elasticsearch { hosts => ["192.168.1.224:9200"] }  stdout { codec => rubydebug }
    }
    
    使用配置文件运行logstash# logstash -f ./elk.conf运行成功以后输入以及标准输出结果

    image.png

    logstash的数据库类型

    1. Input插件
        权威指南:https://www.elastic.co/guide/en/logstash/current/input-plugins.html
        
        file插件的使用    
        # vim /etc/logstash/conf.d/elk.conf
            # 添加如下配置
        input {
            file {
                path => "/var/log/messages"
                type => "system"
                start_position => "beginning"
                }
        }
        output {    
                 elasticsearch {
                        hosts => ["192.168.1.224:9200"]
                        index => "system-%{+YYYY.MM.dd}"
                    }
        }
    
    
    运行logstash指定elk.conf配置文件,进行过滤匹配#logstash -f /etc/logstash/conf.d/elk.conf

    image.png

    来一发配置安全日志的并且把日志的索引按类型做存放,继续编辑elk.conf文件

    # vim /etc/logstash/conf.d/elk.conf添加secure日志的路径
    input {
        file {
            path => "/var/log/messages"
            type => "system"
            start_position => "beginning"
        }
    
        file {
            path => "/var/log/secure"
            type => "secure"
            start_position => "beginning"
        }
    }
    
    output {    if [type] == "system" {
    
            elasticsearch {
                hosts => ["192.168.1.224:9200"]
                index => "system-%{+YYYY.MM.dd}"
            }
        }    if [type] == "secure" {
    
            elasticsearch {
                hosts => ["192.168.1.224:9200"]
                index => "nagios-secure-%{+YYYY.MM.dd}"
            }
        }
    }
    
    运行logstash指定elk.conf配置文件,进行过滤匹配# logstash -f ./elk.conf

    image.png

    这些设置都没有问题之后,接下来安装下kibana,可以让在前台展示

    Kibana的安装及使用

    安装kibana环境
    
    官方安装手册:https://www.elastic.co/guide/en/kibana/current/install.html
    
    下载kibana的tar.gz的软件包
    [root@al7 conf.d]#  cd /usr/local/src/
    [root@al7 src]# wget https://download.elastic.co/kibana/kibana/kibana-4.3.1-linux-x64.tar.gz
    
    解压kibana的tar包
    [root@al7 src]# tar zxvf kibana-4.3.1-linux-x64.tar.gz
    
    进入解压好的kibana
    [root@al7 src]# mv kibana-4.3.1-linux-x64 /usr/local/ #在/usr/local创建kibana的软连接
    [root@al7 src]# ln -s /usr/local/kibana-4.3.1-linux-x64/ /usr/local/kibana
    
    编辑kibana的配置文件
    [root@al7 src]# vim /usr/local/kibana/config/kibana.yml 
    server.port: 5601
    server.host: "0.0.0.0"
    elasticsearch.url: "http://192.168.1.224:9200"   
    kibana.index: ".kibana"
    
    #安装screen,以便于kibana在后台运行(当然也可以不用安装,用其他方式进行后台启动)
    [root@al7 src]# yum -y install screen
    [root@al7 src]# screen
    
    /usr/local/kibana/bin/kibana
    Crtl a+d  退出 
    [root@al224 ~]# screen -ls
    There is a screen on:
            2257.pts-0.al224        (Detached)
    1 Socket in /var/run/screen/S-root.
    
    
    打开浏览器并设置对应的index   http://IP:5601

    添加ES的索引到kibana里

    image.png

    image.png

    二、ELK实战篇

    好,现在索引也可以创建了,现在可以来输出nginx、message、secrue的日志到前台展示(Nginx有的话直接修改,没有自行安装)

    编辑nginx配置文件,修改以下内容(在http模块下添加)
    
    log_format json '{"@timestamp":"$time_iso8601",'
                 '"@version":"1",'
                 '"client":"$remote_addr",'
                 '"url":"$uri",'
                 '"status":"$status",'
                 '"domian":"$host",'
                 '"host":"$server_addr",'
                 '"size":"$body_bytes_sent",'
                 '"responsetime":"$request_time",'
                 '"referer":"$http_referer",'
                 '"ua":"$http_user_agent"'
              '}';
    
    修改access_log的输出格式为刚才定义的json 
    access_log  logs/elk.access.log  json;
    
    
    
    编辑logstash配置文件,进行日志收集
    vim /etc/logstash/conf.d/full.conf
    
        input {
        file {
            path => "/var/log/messages"
            type => "system"
            start_position => "beginning"
        }   
    
        file {
            path => "/var/log/secure"
            type => "secure"
            start_position => "beginning"
        }   
        file {
            path => "/usr/local/nginx/logs/elk.access.log"
            type => "nginx"
            start_position => "beginning"
        }   
    
    }
        
    output {    if [type] == "system" { 
    
            elasticsearch {
                hosts => ["192.168.1.224:9200"]
                index => "nagios-system-%{+YYYY.MM.dd}"
            }       
        }   
    
        if [type] == "secure" {
    
            elasticsearch {
                hosts => ["192.168.1.224:9200"]
                index => "nagios-secure-%{+YYYY.MM.dd}"
            }
        }    
         if [type] == "nginx" {
    
            elasticsearch {
                hosts => ["192.168.1.224:9200"]
                index => "nginx-log-%{+YYYY.MM.dd}"
            }
        }
    
    }
    
    运行看看效果如何
    logstash -f /etc/logstash/conf.d/full.conf

    image.png

    可以发现所有创建日志的索引都已存在,接下来就去Kibana创建日志索引,进行展示(按照上面的方法进行创建索引即可),看下展示的效果

    ab压测下: ab -n 20000 -c 1000 http://192.168.1.224/image.png

    具体的日志输出需求,进行具体的分析

    三:ELK终极篇

    安装reids 
    # yum install -y redis
    
    修改redis的配置文件
    # vim /etc/redis.conf
    
    修改内容如下
    daemonize yes
    
    bind 192.168.1.224启动redis服务
    # /etc/init.d/redis restart
    
    测试redis的是否启用成功
    # redis-cli -h 192.168.1.224输入info如果有不报错即可
    redis 192.168.1.224:6379> info
    编辑配置redis-out.conf配置文件,把标准输入的数据存储到redis中
    # vim /etc/logstash/conf.d/redis-out.conf
    
    添加如下内容
    input {
                stdin {}
    }
    
    output {
    
            redis {
                    host => "192.168.1.224"
                    port => "6379"
                    db => '6'
                    data_type => "list"
                    key => 'demo'
            }
    }
    
    运行logstash指定redis-in.conf的配置文件# /usr/share/logstash/bin/logstash -f /etc/logstash/conf.d/redis-out.conf
    
    
    编辑配置redis-in.conf配置文件,把reids的存储的数据输出到elasticsearch中
    # vim /etc/logstash/conf.d/redis-out.conf添加如下内容
    input{
        redis {
                        host => "192.168.1.224"
                        port => "6379"
                        db => '6'
                        data_type => "list"
                        key => 'demo'
                }
    
    }
    
    output {
            elasticsearch {
                    hosts => ['192.168.1.224:9200']
                    index => 'redis-test-%{+YYYY.MM.dd}'
            }
    }
    
    运行logstash指定redis-in.conf的配置文件# /usr/share/logstash/bin/logstash -f /etc/logstash/conf.d/redis-out.conf

    image.png

    把之前的配置文件修改一下,变成所有的日志监控的来源文件都存放到redis中,然后通过redis在输出到elasticsearch中
    更改为如下,编辑full.conf
    input {
       file {
                path => "/var/log/nginx/access_json.log"
                type => "nginx"
                start_position => "beginning"
        }
        file {
                path => "/var/log/secure"
                type => "secure"
                start_position => "beginning"
        }
        file {
                path => "/var/log/messages"
                type => "system"
                start_position => "beginning"
        }
    }
    output {   
          if [type] == "nginx" {
            redis {
                host => "192.168.1.224"
                port => "6379"
                db => "6"
                data_type => "list"
                key => 'nginx' 
            }
        }   
        if [type] == "secure" {
            redis {
                host => "192.168.1.224"
                port => "6379"
                db => "6"
                data_type => "list"
                key => 'secure' 
            }
        }    
        if [type] == "system" {
            redis {
                host => "192.168.1.224"
                port => "6379"
                db => "6"
                data_type => "list"
                key => 'system' 
            }
        }
    } 
    运行logstash指定shipper.conf的配置文件# /usr/share/logstash/bin/logstash -f /etc/logstash/conf.d/full.conf在redis中
    (查看是否已经将数据写到里面(有时候输入的日志文件不产生日志,会导致redis里面也没有写入日志)

    image.png

    把redis中的数据读取出来,写入到elasticsearch中(需要另外一台主机做实验)
    
    编辑配置文件
    # vim /etc/logstash/conf.d/redis-out.conf
    添加如下内容
    input {
    
        redis {
            type => "system"
    
            host => "192.168.1.224"
    
            port => "6379"
    
            db => "6"
    
            data_type => "list"
    
            key => 'system'
     
              batch_count => 1
    
         }
        redis {
            type => "nginx"
    
            host => "192.168.1.224"
    
            port => "6379"
    
            db => "6"
    
            data_type => "list"
    
            key => 'nginx'
    
               batch_count => 1
    
         }
        
        redis {
            type => "secure"
    
            host => "192.168.1.224"
    
            port => "6379"
    
            db => "6"
    
            data_type => "list"
    
            key => 'secure'
     
              batch_count => 1
    
        }
    }
        
    output {    
        if[type] == "system"
    
        {
         elasticsearch {
         hosts => ["192.168.1.224:9200"]
         index => "system-%{+YYYY.MM.dd}"
    
            }
        }   
        if[type] == "nginx"
          {
         elasticsearch {
         hosts => ["192.168.1.224:9200"]            
           index => "nginx-%{+YYYY.MM.dd}"
             }   
        }  
             if[type] == "secure"
          {
          elasticsearch {
         hosts => ["192.168.1.224:9200"]
         index => "secure-%{+YYYY.MM.dd}"
    
            }   
        }  
    }
     

    image.png

      注意: input是从客户端收集的 output是同样也保存到192.168.1.224中的elasticsearch中,如果要保存到当前的主机上,可以把output中的hosts修改成localhost,如果还需要在kibana中显示,需要在本机上部署kabana,为何要这样做,起到一个松耦合的目的。说白了,就是在客户端收集日志,写到服务端的redis里或是本地的redis里面,输出的时候对接ES服务器即可 运行

    命令看看效果# /usr/share/logstash/bin/logstash -f /etc/logstash/conf.d/redis-out.conf

    上线ELK

        1.日志分类
            系统日志       rsyslog     logstash    syslog插件
            访问日志       nginx      logstash    codec   json
            错误日志       file       logstash    mulitline
            运行日志       file       logstash    codec   json
            设备日志       syslog      logstash    syslog插件
            Debug日志      file       logstash     json或者mulitline  
        2.日志标准化
            路径      固定
            格式      尽量json3.   系统个日志开始-->错误日志-->运行日志-->访问日志

    因为ES保存日志是永久保存,所以需要定期删除一下日志,下面命令为删除指定时间前的日志

    curl -X DELETE http://xx.xx.com:9200/logstash-*-`date +%Y-%m-%d -d "-$n days"`
  • 相关阅读:
    sqlite3数据库的简要应用
    5分钟把任意网站变成桌面软件--windows版
    bootstrap-multiselect 的简单使用,样式修改,动态创建option
    jquery自定义进度条与h5原生进度条
    Angular 4+ Http
    Flexible Box布局基础知识详解
    Angular4+路由
    Angular 4 设置组件样式的几种方式
    Angular 4 自定义组件封装遇见的一些事儿
    angular4 中自定义pagination组件
  • 原文地址:https://www.cnblogs.com/Leslieblog/p/10929430.html
Copyright © 2020-2023  润新知