Jasper Ji

开口不在舌头上

0%

Spring Boot使用ELK

是在Mac环境下跑的例子。

安装ELK相关软件

ELK主要指Elasticsearch、Logstash、Kibana,使用elastic.co提供的安装指南,使用Brew安装。

切换Tab

1
brew tap elastic/tap

安装软件

1
2
3
brew install elastic/tap/elasticsearch-full  # 安装Elasticsearch
brew install elastic/tap/logstash-full # Logstash
brew install elastic/tap/kibana-full # Kibana

可以在前台或者后台启动软件

1
2
3
4
5
6
7
8
brew services start elastic/tap/elasticsearch-full # 后台启动
elasticsearch # 前台启动

brew services start elastic/tap/logstash-full
logstash

brew services start elastic/tap/kibana-full
kibana

Spring Boot配置

Maven添加Logstash依赖

1
2
3
4
5
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>5.3</version>
</dependency>

在Resources目录下添加logback-spring.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<!-- 配置输出地址 -->
<destination>127.0.0.1:4560</destination>
<!-- 日志输出编码 -->
<encoder charset="UTF-8"
class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<timestamp>
<timeZone>UTC</timeZone>
</timestamp>
<pattern>
<pattern>
{
"logLevel": "%level",
"serviceName": "${springAppName:-}",
"pid": "${PID:-}",
"thread": "%thread",
"class": "%logger{40}",
"rest": "%message"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="LOGSTASH" />
<appender-ref ref="CONSOLE" />
</root>
</configuration>

配置Logstash,创建一个logstash-sample.conf文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
input {
tcp {
mode => "server"
host => "0.0.0.0"
port => 4560
codec => json
}
}
output{
elasticsearch {
hosts => ["http://localhost:9200"] # Elasticsearch 地址
index => "spring_cms-%{+YYYY.MM.dd}" # 这里我用spring_cms,可以替换为自己的。需要注意ES关于索引的命名规范
}
}

使用配置文件重启Logstash服务

1
logstash  -f logstash-sample.conf

最后在项目中输出一段测试日志

1
logger.info("Hello,ELK");

最后在Kibana创建索引就应该能看到日志了。

额外工具

一开始发现Kibana中没有数据,猜测Elasticsearch没有收到数据,最后用到了ElasticSearch head这个可以查看Elasticsearch存储的工具,具体安装可以参考Github的说明。

运行这个工具遇到问题,发现ElasticSearch连接不上,原来是跨域访问的问题,使用brew安装ElasticSearch后会有如下目录

1
2
3
4
Data:    /usr/local/var/lib/elasticsearch/elasticsearch_xxxx/ # xxxx此处是你自己的电脑名
Logs: /usr/local/var/log/elasticsearch/elasticsearch_xxxx.log # xxxx此处是你自己的电脑名
Plugins: /usr/local/var/elasticsearch/plugins/
Config: /usr/local/etc/elasticsearch/

编辑配置文件nano /usr/local/etc/elasticsearch/elasticsearch.yml,添加如下配置。

1
2
http.cors.enabled: true
http.cors.allow-origin: "*"

最后就可以正常访问了。

总结

使用ELK访问日志确实很方便,实际开发中可能会使用云服务商提供ELK服务。