億級日誌平臺之——ELK Stack實踐

1、ELK搭建篇

官網地址:https://www.elastic.co/cn/html

官網權威指南:https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.htmljava

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

ELK是Elasticsearch、Logstash、Kibana的簡稱,這三者是核心套件,但並不是所有。linux

Elasticsearch是實時全文搜索和分析引擎,提供蒐集、分析、存儲數據三大功能;是一套開放REST和JAVA API等結構提供高效搜索功能,可擴展的分佈式系統。它構建於Apache Lucene搜索引擎庫之上。ios

Logstash是一個用來蒐集、分析、過濾日誌的工具。它支持幾乎任何類型的日誌,包括系統日誌、錯誤日誌和自定義應用程序日誌。它能夠從許多來源接收日誌,這些來源包括 syslog、消息傳遞(例如 RabbitMQ)和JMX,它可以以多種方式輸出數據,包括電子郵件、websockets和Elasticsearch。nginx

Kibana是一個基於Web的圖形界面,用於搜索、分析和可視化存儲在 Elasticsearch指標中的日誌數據。它利用Elasticsearch的REST接口來檢索數據,不只容許用戶建立他們本身的數據的定製儀表板視圖,還容許他們以特殊的方式查詢和過濾數據web

環境

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的存放目錄,並修改該目錄的屬主屬組redis

# mkdir -p /data/es-data   (自定義用於存放data數據的目錄)
# chown -R elasticsearch:elasticsearch /data/es-data

修改elasticsearch的日誌屬主屬組數據庫

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

修改elasticsearch的配置文件json

# 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

2、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"`
相關文章
相關標籤/搜索