由于微服务架构中每个服务可能分散在不同的服务器上,因此需要一套分布式日志的解决方案。spring-cloud提供了一个用来trace服务的组件sleuth。它可以通过日志获得服务的依赖关系。基于sleuth,可以通过现有的日志工具实现分布式日志的采集。
这里使用的是ELK,也就是elasticsearch、logstash、kibana。
一、sleuth
第一步:sleuth管理端
sleuth一般单独放在一个工程中。需要添加如下依赖
<dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-autoconfigure-ui</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-server</artifactId> </dependency>
配置服务注册中心的地址
eureka: client: serviceUrl: defaultZone: http://localhost:1111/eureka/
启动类加入服务发现的注解和zipkin的注解,如下
package com.wlf.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import zipkin.server.EnableZipkinServer; @EnableDiscoveryClient @EnableZipkinServer @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
这个时候启动并访问该微服务的地址,可以看到zipkin的管理页面了。
推荐一个 Spring Boot 基础教程及实战示例: https://github.com/javastacks/spring-boot-best-practice
第二步:被管理的微服务端
在我们的其他微服务端需要简单的配置,纳入到zipkin的管理之中
引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-sleuth-zipkin</artifactId> </dependency>
加入如下配置
spring: sleuth: sampler: percentage: 1 zipkin: base-url: http://localhost:9411
spring.sleuth.sampler.percentage
:这个参数的意思是抓取100%的日志,只有通过抓取日志,才能获知依赖关系。但是如果始终抓取日志的话对性能会有影响,因此可以自己配置。一般在开发环境,该值设置为1,生产环境视情况而定。
spring.zipkin.base-url
:为第一步配置的zipkin管理端微服务的地址
现在分别启动服务注册中心,网关,需要的微服务,以及sleuth。
随便调用一个微服务
然后我们可以看到相关的跟踪日志
同样我们也可以看到微服务之间的依赖关系,这里是通过网关调用了myservice-consumer-feign
微服务,然后通过myservice-consumer-feign
微服务调用了myservice-provider
微服务
二、搭建ELK
1、elasticsearch的安装与配置,由于之前的文章已经介绍了elasticsearch的单点,集群的安装,head插件的安装。这里不再总结。
2、kibana的安装,没什么好说的,解压,运行就可以了
3、logstash的安装,解压即可
在config下新建配置文件
output { input { tcp { port => 4560 codec => json_lines } } output { elasticsearch { hosts => ["192.168.160.66:9200","192.168.160.88:9200","192.168.160.166:9200"] index => "applog" } }
其中port为端口号,codec表示通过json格式,elasticsearch.hosts表示elasticsearch的地址,这里是集群。index 为日志存储的elasticsearch索引。
启动需要调用bin下的logstash命令,通过-f指定配置文件