1. 程式人生 > >ZipKin原理學習--zipkin支援日誌列印追蹤資訊

ZipKin原理學習--zipkin支援日誌列印追蹤資訊

       目前在zipkin brave已經提供功能在我們使用logback或log4j等時可以在日誌資訊中將traceId和spanId等資訊列印到執行日誌,這樣可能對我們通過日誌檢視解決問題有比較大的幫助。

示例:

pom.xml中新增zipkin相關jar

        <dependency>
	      <groupId>io.zipkin.brave</groupId>
	      <artifactId>brave-instrumentation-spring-web</artifactId>
	      <version>5.4.3</version>
	    </dependency>
        <dependency>
			<groupId>io.zipkin.brave</groupId>
			<artifactId>brave</artifactId>
			<version>5.4.3</version>
		</dependency>
		<dependency>
			<groupId>io.zipkin.brave</groupId>
			<artifactId>brave-context-slf4j</artifactId>
			<version>5.4.3</version>
		</dependency>
	    <dependency>
	      <groupId>io.zipkin.brave</groupId>
	      <artifactId>brave-instrumentation-spring-webmvc</artifactId>
	      <version>5.4.3</version>
	    </dependency>

注入zip相關bean:

Configuration
@Import({
    TracingClientHttpRequestInterceptor.class,
    SpanCustomizingAsyncHandlerInterceptor.class
})
public class TracingConfiguration extends WebMvcConfigurerAdapter {

	
	@Bean
	public DelegatingTracingFilter getDelegatingTracingFilter() {
		return new DelegatingTracingFilter();
	}
	
  @Bean 
  Sender sender() {
	  return OkHttpSender.create("http://127.0.0.1:9411/api/v2/spans");
  }


  @Bean 
  AsyncReporter<Span> spanReporter() {
	  return AsyncReporter.create(sender());
  }

  @Bean 
  Tracing tracing(@Value("${zipkin.service:brave-webmvc-example}") String serviceName) {
	  return Tracing.newBuilder()
        .localServiceName(serviceName)
        .propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, "user-name"))
        .spanReporter(spanReporter()).currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
//新增日誌相關的處理器
.addScopeDecorator(MDCScopeDecorator.create()).build()).build();
  }

  @Bean 
  HttpTracing httpTracing(Tracing tracing) {
	  return HttpTracing.create(tracing);
  }

 
  
  @Autowired 
  TracingClientHttpRequestInterceptor clientInterceptor;

  @Bean
  public RestTemplate restTemplate() {
	  RestTemplate restTemplate = new RestTemplate();
	  List<ClientHttpRequestInterceptor> interceptors =new ArrayList<>(restTemplate.getInterceptors());
	  interceptors.add(clientInterceptor);
	  restTemplate.setInterceptors(interceptors);
	  return restTemplate;
  }

  @Autowired 
  SpanCustomizingAsyncHandlerInterceptor serverInterceptor;

  @Override 
  public void addInterceptors(InterceptorRegistry registry) {
	  registry.addInterceptor(serverInterceptor);
  }
}

執行日誌:

    @RequestMapping("start")
    public String start(HttpServletRequest request1,HttpServletResponse response1) throws InterruptedException, IOException {

    	logger.info("start");

    	String data = restTemplate.getForObject("http://localhost:9090/foo", String.class);

    	return data;
    }

logback.xml相關配置:

主要新增這個列印格式:

<property name="CONSOLE_LOG_PATTERN" value="%d [%X{traceId}/%X{spanId}] [%thread] %-5level %logger{36} - %msg%n"/>

logback.xml示例:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    ​
    <springProperty scope="context" name="springAppName" source="spring.application.name"/>
    <!-- Example for logging into the build folder of your project -->
    <property name="LOG_FILE" value="logs\\${springAppName}.log"/>​
    <!-- You can override this to have a custom pattern -->

    <property name="CONSOLE_LOG_PATTERN" value="%d [%X{traceId}/%X{spanId}] [%thread] %-5level %logger{36} - %msg%n"/>

    <!-- Appender to log to console -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- Minimum logging level to be presented in the console logs-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>
    <!-- Appender to log to file -->​
    <appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
            <maxHistory>7</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>
    ​
    ​
    <root level="INFO">
        <appender-ref ref="console"/>
        <!-- uncomment this to have also JSON logs -->
        <appender-ref ref="flatfile"/>
    </root>
</configuration>

日誌列印資訊:

2018-10-20 21:24:28,656 [af49581a0f632677/af49581a0f632677] [http-nio-8080-exec-1] INFO  c.t.controller.HomeController - start