springboot和ELK搭建配置詳情

環境準備centos7,jdk8

一、ELK 是什麼?

ELK 是三個開源框架的簡寫,分別是:Elasticsearch、Logstash、Kibana 。

Logstash:日誌收集工具,可以從本地磁盤,網絡服務(自己監聽端口,接受用戶日誌),消息隊列中收集各種各樣的日誌,然後進行過濾分析,並將日誌輸出到Elasticsearch中。

Elasticsearch:日誌分佈式存儲/搜索工具,原生支持集羣功能,可以將指定時間的日誌生成一個索引,加快日誌查詢和訪問。

Kibana:可視化日誌Web展示工具,對Elasticsearch中存儲的日誌進行展示,還可以生成炫麗的儀表盤。

二、安裝部署 Elasticsearch

1、下載
官網下載地址:https://www.elastic.co/cn/downloads/elasticsearch

國內鏡像源(華爲):https://mirrors.huaweicloud.com/elasticsearch/

推薦使用國內的下載地址,官網下載太慢了。

選擇合適的版本下載(推薦下載自帶 JDK 的版本,否者自己配置的 JDK 可能不符合版本要求。注意:Elasticsearch 會優先使用系統配置的 JDK 。可將 Elasticsearch 自帶的 JDK 配置到系統的環境變量中,如果不這樣做的話,在安裝 Logstash 時,啓動會報沒有配置 JDK 環境變量的錯誤。)

[root@localhost ~]# wget https://mirrors.huaweicloud.com/elasticsearch/7.8.0/elasticsearch-7.8.0-linux-x86_64.tar.gz

2、解壓到指定目錄

# 新建文件夾
[root@localhost ~]# mkdir /usr/local/elasticsearch

# 解壓到指定文件夾
[root@localhost ~]# tar -zxvf elasticsearch-7.8.0-linux-x86_64.tar.gz -C /usr/local/elasticsearch/

3、修改配置文件

# 進入安裝目錄
[root@localhost ~]# cd /usr/local/elasticsearch/elasticsearch-7.8.0/

# 修改config/elasticsearch.yml
[root@localhost elasticsearch-7.8.0]# vim ./config/elasticsearch.yml

# 修改以下幾項:

node.name: node-1 # 設置節點名
network.host: 0.0.0.0 # 允許外部 ip 訪問
cluster.initial_master_nodes: ["node-1"] # 設置集羣初始主節點

4、新建用戶並賦權

ES爲了安全考慮不允許使用root用戶啓動ElasticSearch,所以需要新建一個普通用戶啓動程序。

# 添加用戶 es
[root@localhost elasticsearch-7.8.0]# adduser es

# 設置用戶 es 的密碼(需要輸入兩遍密碼)
# (如果設置密碼過於簡單可能會提示 BAD PASSWORD: XXX ,如果是用 root 用戶操作可忽略提示繼續輸入第二遍密碼強制設置密碼)
[root@localhost elasticsearch-7.8.0]# passwd es
Changing password for user es.
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: 
passwd: all authentication tokens updated successfully.

# 將對應的文件夾權限賦予用戶 es
[root@localhost elasticsearch-7.8.0]# chown -R es /usr/local/elasticsearch

5、切換至新建的用戶並啓動 Elasticsearch

# 切換至用戶 es
[root@localhost elasticsearch-7.8.0]# su es

# 啓動 ElasticSearch (-d 表示在後臺啓動)
[es@localhost elasticsearch-7.8.0]$ ./bin/elasticsearch -d

錯誤處理
啓動之後可能會報以下三個錯誤:

ERROR: [3] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
[2]: max number of threads [3795] for user [es] is too low, increase to at least [4096]
[3]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

解決方式:

需切換到root用戶解決錯誤:

# 切換到 root 用戶
[es@localhost elasticsearch-7.8.0]$ su root

[1] 和 [2] 的解決方法:

# 修改 /etc/security/limits.conf 文件
[root@localhost elasticsearch-7.8.0]# vim /etc/security/limits.conf
# 添加以下四行
* soft nofile 65536
* hard nofile 131072
* soft nproc 2048
* hard nproc 4096

[3] 的解決方法:

# 修改 /etc/sysctl.conf 文件
[root@localhost elasticsearch-7.8.0]# vim /etc/sysctl.conf
# 添加下面一行
vm.max_map_count=655360

# 執行命令
[root@localhost elasticsearch-7.8.0]# sysctl -p

切換到用戶 es 重新啓動程序就可以了。

6、驗證

注意: 防火牆需要開放9200端口

[root@localhost elasticsearch-7.8.0]# firewall-cmd --permanent --add-port=9200/tcp
success
[root@localhost elasticsearch-7.8.0]# firewall-cmd --permanent --add-port=9200/udp
success
[root@localhost elasticsearch-7.8.0]# firewall-cmd --reload
success

啓動沒有報錯成功後,在瀏覽器輸入ip:9200端口如:http://192.168.110.200:9200,顯示下圖所示爲啓動成功

{
  "name" : "node-1",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "ZjEM0gywRRaoko1fJ2bJIA",
  "version" : {
    "number" : "7.8.0",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "757314695644ea9a1dc2fecd26d1a43856725e65",
    "build_date" : "2020-06-14T19:35:50.234439Z",
    "build_snapshot" : false,
    "lucene_version" : "8.5.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

三、安裝部署 Kibana

1、下載

華爲鏡像源:https://mirrors.huaweicloud.com/kibana

選擇合適的版本下載(和Elasticsearch版本保持一致)。

[root@localhost ~]# wget https://mirrors.huaweicloud.com/kibana/7.8.0/kibana-7.8.0-linux-x86_64.tar.gz

2、解壓並移動到指定目錄

# 解壓到當前目錄
[root@localhost ~]# tar -zxvf kibana-7.8.0-linux-x86_64.tar.gz

# 重命名並移動到指定目錄
[root@localhost ~]# mv ./kibana-7.8.0-linux-x86_64 /usr/local/kibana-7.8.0

3、修改配置文件

[root@localhost kibana-7.8.0]# vim ./config/kibana.yml

# 服務端口
server.port: 5601
# 服務器ip  本機
server.host: "0.0.0.0"
# Elasticsearch 服務地址
elasticsearch.hosts: ["http://localhost:9200"]
# 設置語言爲中文
i18n.locale: "zh-CN"

4、授權並切換用戶

給 es 用戶授予 kibana 目錄的權限。

# 授權
[root@localhost ~]# chown -R es /usr/local/kibana-7.8.0
# 切換用戶
root@localhost ~]# su es

5、啓動 Kibana

注意:啓動 Kibana 之前需要先啓動 Elasticsearch

需要先配置防火牆打開5601端口:

[root@localhost kibana-7.8.0]# firewall-cmd --permanent --add-port=5601/tcp
success
[root@localhost kibana-7.8.0]# firewall-cmd --permanent --add-port=5601/udp
success
[root@localhost kibana-7.8.0]# firewall-cmd --reload
success

# 前臺啓動方式
[es@localhost kibana-7.8.0]$ ./bin/kibana

# 後臺啓動方式
[es@localhost kibana-7.8.0]$ nohup ./bin/kibana &

如果需要用root用戶啓動,可以使用:nohup ./bin/kibana --allow-root &

6、在瀏覽器中訪問 Kibana

啓動完成沒有報錯後,在瀏覽器輸入IP:Ports如:http://192.168.110.200:5601/,出現如下界面

四、安裝部署 Logstash

1、下載安裝包

華爲鏡像源:https://mirrors.huaweicloud.com/logstash

選擇合適版本的安裝包(和 Elasticsearch 保持一致)。

[root@localhost ~]# wget https://mirrors.huaweicloud.com/logstash/7.8.0/logstash-7.8.0.tar.gz

2、解壓並移動到指定目錄

# 解壓安裝包
[root@localhost ~]# tar -zxvf logstash-7.8.0.tar.gz

# 移動到指定目錄
[root@localhost ~]# mv ./logstash-7.8.0 /usr/local/logstash-7.8.0

3、新建配置文件

根據原有的 logstash-sample.conf 配置文件複製出一個新的配置文件並修改。

[root@localhost logstash-7.8.0]# cp config/logstash-sample.conf config/logstash-es.conf

# 修改配置文件logstash-es.conf
[root@localhost logstash-7.8.0]# vim config/logstash-es.conf

配置文件詳細入門參考傳送門:https://www.cnblogs.com/moonlightL/p/7760512.html

input {
 # 我們創建了兩個微服務demo 所以建立兩個不同的輸入,將兩個服務的日誌分別輸入到不同的索引中
  tcp {
    mode => "server"
    host => "0.0.0.0"   # 允許任意主機發送日誌
    type => "elk1"      # 設定type以區分每個輸入源
    port => 9601        # 監聽的端口  
    codec => json_lines # 數據格式
  }
  tcp {
    mode => "server"
    host => "0.0.0.0"
    type => "elk2"
    port => 9602
    codec => json_lines
  }

}
filter {
  #Only matched data are send to output.
}
output {
  # For detail config for elasticsearch as output,
  # See: https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html

  if [type] == "elk1" {
    elasticsearch {
      action => "index"          # 輸出時創建映射
      hosts  => "192.168.110.200:9200"   # ElasticSearch 的地址和端口
      index  => "elk1"           # 指定索引名
      codec  => "json"
     }
  }
  if [type] == "elk2" {
    elasticsearch {
      action => "index"        #The operation on ES
      hosts  => "192.168.110.200:9200"   #ElasticSearch host, can be array.
      index  => "elk2"         #The index to write data to.
      codec  => "json"
     }
  }
}

注意要根據配置的端口,打開對應的防火牆:

[root@localhost logstash-7.8.0]# firewall-cmd --permanent --add-port=9601/tcp
success
[root@localhost logstash-7.8.0]# firewall-cmd --permanent --add-port=9601/udp
success
[root@localhost logstash-7.8.0]# firewall-cmd --permanent --add-port=9602/tcp
success
[root@localhost logstash-7.8.0]# firewall-cmd --permanent --add-port=9602/udp
success
[root@localhost logstash-7.8.0]# firewall-cmd --reload
success

4、安裝插件

由於國內無法訪問默認的gem source,需要將gem source改爲國內的源。

# 修改Gemfile
[root@localhost logstash-7.8.0]# vim Gemfile

# 將source這一行改成如下所示:

source "https://gems.ruby-china.com"

然後執行安裝:

[root@localhost logstash-7.8.0]# ./bin/logstash-plugin install logstash-codec-json_lines

如果報以下錯誤,請檢查是否已經配置了 JDK 環境變量。

could not find java; set JAVA_HOME or ensure java is in PATH

5、啓動 Logstash

# 後臺啓動Logstash
[root@localhost logstash-7.8.0]# nohup ./bin/logstash -f ./config/logstash-es.conf --config.reload.automatic &

如果不需要自動檢查配置修改,可以使用下面命令啓動:

[root@localhost logstash-7.8.0]# nohup ./bin/logstash -f ./config/logstash-es.conf &

五、配置項目查看結果

本示例使用的是 Spring Boot 項目。

1、引入依賴

        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>5.2</version>
        </dependency>

2、在resources裏新建 logback.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration>
    <appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <!--指定logstash ip:監聽端口-->
        <destination>192.168.40.149:9601</destination>
        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder" />
    </appender>

    <!--引用springboot默認配置-->
    <include resource="org/springframework/boot/logging/logback/base.xml"/>

    <root level="INFO">
        <!--使用上述訂閱logstash數據tcp傳輸 -->
        <appender-ref ref="LOGSTASH" />
        <!--使用springboot默認配置 調試窗口輸出-->
        <appender-ref ref="CONSOLE" />
    </root>

</configuration>

3、啓動系統打印日誌

啓動類:

@SpringBootApplication
@RestController
public class TestspringbootApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(TestspringbootApplication.class, args);
    }

    @Override
    public void run(String... args) {
        Logger logger = LoggerFactory.getLogger(TestspringbootApplication.class);
        logger.info("測試log345345345345354");

        for (int i = 0; i < 5; i++) {
            logger.error("something wrong. id={}; name=Ryan-{};", i, i);
        }
    }
}

啓動,打印日誌:

2021-07-26 10:40:30.066  INFO 7044 --- [           main] c.e.t.TestspringbootApplication          : No active profile set, falling back to default profiles: default
2021-07-26 10:40:32.215  INFO 7044 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8012 (http)
2021-07-26 10:40:34.352  INFO 7044 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-07-26 10:40:37.315  INFO 7044 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-07-26 10:40:38.292  INFO 7044 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-07-26 10:40:38.293  INFO 7044 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 6683 ms
2021-07-26 10:40:39.719  INFO 7044 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-07-26 10:40:40.620  INFO 7044 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8012 (http) with context path ''
2021-07-26 10:40:51.601  INFO 7044 --- [           main] c.e.t.TestspringbootApplication          : Started TestspringbootApplication in 37.395 seconds (JVM running for 37.87)
2021-07-26 10:40:53.103  INFO 7044 --- [           main] c.e.t.TestspringbootApplication          : 測試log345345345345354
2021-07-26 10:41:02.712 ERROR 7044 --- [           main] c.e.t.TestspringbootApplication          : something wrong. id=0; name=Ryan-0;
2021-07-26 10:41:03.328 ERROR 7044 --- [           main] c.e.t.TestspringbootApplication          : something wrong. id=1; name=Ryan-1;
2021-07-26 10:41:03.752 ERROR 7044 --- [           main] c.e.t.TestspringbootApplication          : something wrong. id=2; name=Ryan-2;
2021-07-26 10:41:09.616 ERROR 7044 --- [           main] c.e.t.TestspringbootApplication          : something wrong. id=3; name=Ryan-3;
2021-07-26 10:41:10.175 ERROR 7044 --- [           main] c.e.t.TestspringbootApplication          : something wrong. id=4; name=Ryan-4;

Kibana還需要配置日誌讀取的索引:

然後再次打開Discover,配置顯示列,顯示如下

 參考:

https://blog.csdn.net/sinat_27245917/article/details/108123826

https://blog.csdn.net/weixin_43184769/article/details/84971532

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章