前面我们已经在Windows搭建好了ELK,没看过的朋友可以看一下我的上一篇文章
https://www.jianshu.com/p/b783688f637d
现在我们开始试着把ELK整合到项目中实现日志的分析
1.首先我们把Logstash的conf配置文件改成
input {
tcp {
host => "localhost" ##安装logstash的ip
port => 9601 ##设置logstash的端口
mode => "server"
tags => ["tags"]
codec => json_lines ##格式json
}
}
output {
elasticsearch {
action => "index"
hosts => "127.0.0.1:9200" #e#s的ip和端口(本次logstash和es是同一个服务器)
index => "applog" ##es的index名称
}
stdout { codec => rubydebug}
}
接着重新启动一下
2.去我们的Spring Boot项目里添加依赖
<!--ELK-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>5.1</version>
</dependency>
3.在resources中添加配置文件logback.xml
<?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">
<!--这里必须和logstash配置文件中input -tcp 中的host 和 port一致-->
<destination>localhost:9601</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>
4.最后我们添加测试类进行测试
private final static Logger logger = LoggerFactory.getLogger(TextController.class );
@RequestMapping("/textElk")
public String textElk(){
logger.info("===================textElk");
logger.info("===================开始测试");
return "ok";
}
把项目跑起来
5.进入到Kibana中查看日志信息
首先去management中找到Index patterns然后点击Create index pattern
填写完以后点击Next step
此处选择"@timestamp"后确认
最后在Discover中查看