基于spring boot构建的微服务,服务之间调用日志跟踪,基于spring boot的配置日志输出模式,spring-cloud-starter-feign'的扩展日志输出,请求事件的解析和服务调用轨迹追踪
##搭建spring boot工程## 使用spring boot构建一个微服务
##spring cloud 依赖添加## 参照spring cloud添加服务调用feign模块,如果想采用okHttp调用,则可选引入okHttp。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<!--可选依赖-->
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
##配置## 在spring boot规定的配置文件中添加配置,配置中可以指定日志格式、日志输出方式(支持kafka和file)、日志输出路径、是否使用okHttp,如果不添加配置,则日志默认输出到文件/var/log/hzcard目录下。以下以application.properties为配置文件样例:
feign.httpclient.enabled=false #使用okHttp调用服务
logtrace.appenderType=KAFKA #使用KAFKA/FILE输出
logtrace.kafkaTopic=eventpropertiestopic #kafka输出使用的topic
logtrace.kafkaProperty.bootstrapServers.name = bootstrap.servers #kafka的属性配置属性名
logtrace.kafkaProperty.bootstrapServers.value=${kafka.brokers:191.162.102.208:9092}#kafka的属性配置属性值,跟上一条bootstrapServers.name配置组成 name=value的属性,跟上一条bootstrapServers可以随便定义,只要最终name=value给kafka配置就可以
logtrace.kafkaProperty.maxrequestsize.name=max.request.size #同上解释
logtrace.kafkaProperty.maxrequestsize.value=2097152 #同上解释
... #kafka其他属性值配置
logtrace.patter = %d %-5p [%t] %C{2} (%F:%L) - %m%n #使用的日志输出模式
logtrace.logFile = /var/log/hzcard/feiginClient.log #配置输出文件及路径
##事件解析添加##
编写一个类实现com.hzcard.logtrace.event.EventTypeResolver
类,实现eventGen方法,自己定义把请求解析成事件。
根据spring boot的规范,在启动类中注入一个bean
@Bean
public EventTypeResolver defaultEventTypeResolver(){
return new EventResolverDefault(); //自定义创建的类
}
应用启动后,就会使用注入的bean对request做解析
##默认设备类型解析和扩展##
logtrace默认会解析请求的设备,包括:iphone、ipad、mac、windows、linux、android,详细见com.hzcard.logtrace.spring.boot.handle.interceptor.EquipmentTypeEnum
如果默认的请求无法辨认客户端设备类型,可以进行扩展。
创建一个继承com.hzcard.logtrace.spring.boot.handle.interceptor.EventHandlerInterceptor
的类,实现EquipmentTypeEnum resolve(HttpServletRequest request)
方法。根据spring boot的mvc配置扩展规范,在自己工程目录下创建一个继承了org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
的类,覆写方法
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPhoneEquipMentInterceptor(this.context)); //继承了EventHandlerInterceptor的类
}
##获得客户访问设备类型##
默认提供了工具类com.hzcard.logtrace.spring.util.ClientTypeTools
,调用其方法getClientType()
,获得设备默认对应的类型。
##日志输出与服务调用轨迹##
logtrace会将所有服务调用的http header和body都输出。logtrace增加了几个定制头:X-Event-Platform(事件发生的平台)、X-Event-Type(事件类型)、X-Event-Id(事件id)、X-Event-Code(事件编码)、X-Event-Sequence(事件发生的顺序)
从客户端过来一次请求,可能会调用到多个服务,但X-Event-Id只有一个,X-Event-Sequence会根据请求的顺序,依次增加。如client调用A服务,A再调用B,A再调用c。事件顺序就是:1-0,1-0-1,1-1