diff --git a/reference/html/README.html b/reference/html/README.html index e0846819f..c9f29ce18 100644 --- a/reference/html/README.html +++ b/reference/html/README.html @@ -109,21 +109,21 @@ $(addBlockSwitches);
  • Additional Resources
  • -
  • Features
  • -
  • Building +
  • 1. Features
  • +
  • 2. Building
  • -
  • Contributing +
  • 3. Contributing
  • @@ -1082,7 +1082,7 @@ Sleuth and Zipkin -

    Features

    +

    1. Features

    -

    Building

    +

    2. Building

    -

    Basic Compile and Test

    +

    2.1. Basic Compile and Test

    To build the source you will need to install JDK 1.7.

    @@ -1297,7 +1297,7 @@ If all else fails, build with the command from .travis.yml (usually
    -

    Documentation

    +

    2.2. Documentation

    The spring-cloud-build module has a "docs" profile, and if you switch that on it will try to build asciidoc sources from @@ -1310,7 +1310,7 @@ a modified file in the correct place. Just commit it and push the change.

    -

    Working with the code

    +

    2.3. Working with the code

    If you don’t have an IDE preference we would recommend that you use Spring Tools Suite or @@ -1319,7 +1319,7 @@ a modified file in the correct place. Just commit it and push the change.

    should also work without issue as long as they use Maven 3.3.3 or better.

    -

    Importing into eclipse with m2eclipse

    +

    2.3.1. Importing into eclipse with m2eclipse

    We recommend the m2eclipse eclipse plugin when working with eclipse. If you don’t already have m2eclipse installed it is available from the "eclipse @@ -1346,7 +1346,7 @@ pom into your settings.xml.

    -

    Importing into eclipse without m2eclipse

    +

    2.3.2. Importing into eclipse without m2eclipse

    If you prefer not to use m2eclipse you can generate eclipse project metadata using the following command:

    @@ -1380,7 +1380,7 @@ so, your app breaks during the Maven build.
    -

    Contributing

    +

    3. Contributing

    Spring Cloud is released under the non-restrictive Apache 2.0 license, @@ -1390,7 +1390,7 @@ to contribute even something trivial please do not hesitate, but follow the guidelines below.

    -

    Sign the Contributor License Agreement

    +

    3.1. Sign the Contributor License Agreement

    Before we accept a non-trivial patch or pull request we will need you to sign the Contributor License Agreement. @@ -1401,7 +1401,7 @@ given the ability to merge pull requests.

    -

    Code of Conduct

    +

    3.2. Code of Conduct

    This project adheres to the Contributor Covenant code of conduct. By participating, you are expected to uphold this code. Please report @@ -1409,7 +1409,7 @@ unacceptable behavior to spri

    -

    Code Conventions and Housekeeping

    +

    3.3. Code Conventions and Housekeeping

    None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge.

    @@ -1457,7 +1457,7 @@ message (where XXXX is the issue number).

    -

    Checkstyle

    +

    3.4. Checkstyle

    Spring Cloud Build comes with a set of checkstyle rules. You can find them in the spring-cloud-build-tools module. The most notable files under the module are:

    @@ -1490,7 +1490,7 @@ message (where XXXX is the issue number).

    -

    Checkstyle configuration

    +

    3.4.1. Checkstyle configuration

    Checkstyle rules are disabled by default. To add checkstyle to your project just define the following properties and plugins.

    @@ -1560,11 +1560,11 @@ message (where XXXX is the issue number).

    <?xml version="1.0"?>
     <!DOCTYPE suppressions PUBLIC
    -		"-//Puppy Crawl//DTD Suppressions 1.1//EN"
    -		"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
    +        "-//Puppy Crawl//DTD Suppressions 1.1//EN"
    +        "https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
     <suppressions>
    -	<suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
    -	<suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
    +    <suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
    +    <suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
     </suppressions>
    @@ -1580,9 +1580,9 @@ $ touch .springformat
    -

    IDE setup

    +

    3.5. IDE setup

    -

    Intellij IDEA

    +

    3.5.1. Intellij IDEA

    In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. The following files can be found in the Spring Cloud Build project.

    @@ -1654,15 +1654,15 @@ The following files can be found in the -

    Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

    +

    Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

    • -

      checkstyle.header.file - please point it to the Spring Cloud Build’s, spring-cloud-build-tools/src/main/resources/checkstyle/checkstyle-header.txt file either in your cloned repo or via the https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt URL.

      +

      checkstyle.header.file - please point it to the Spring Cloud Build’s, spring-cloud-build-tools/src/main/resources/checkstyle/checkstyle-header.txt file either in your cloned repo or via the raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt URL.

    • -

      checkstyle.suppressions.file - default suppressions. Please point it to the Spring Cloud Build’s, spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml file either in your cloned repo or via the https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml URL.

      +

      checkstyle.suppressions.file - default suppressions. Please point it to the Spring Cloud Build’s, spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml file either in your cloned repo or via the raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml URL.

    • checkstyle.additional.suppressions.file - this variable corresponds to suppressions in your local project. E.g. you’re working on spring-cloud-contract. Then point to the project-root/src/checkstyle/checkstyle-suppressions.xml folder. Example for spring-cloud-contract would be: /home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml.

      diff --git a/reference/html/appendix.html b/reference/html/appendix.html new file mode 100644 index 000000000..6f8d04538 --- /dev/null +++ b/reference/html/appendix.html @@ -0,0 +1,473 @@ + + + + + + + +Common application properties + + + + + + + + + + +
      +
      +

      Appendix A: Common application properties

      +
      +
      +

      Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches. +This appendix provides a list of common Spring Cloud Sleuth properties and references to the underlying classes that consume them.

      +
      +
      + + + + + +
      + + +Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list. +Also, you can define your own properties. +
      +
      + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      NameDefaultDescription

      spring.sleuth.annotation.enabled

      true

      spring.sleuth.async.configurer.enabled

      true

      Enable default AsyncConfigurer.

      spring.sleuth.async.enabled

      true

      Enable instrumenting async related components so that the tracing information is passed between threads.

      spring.sleuth.async.ignored-beans

      List of {@link java.util.concurrent.Executor} bean names that should be ignored and not wrapped in a trace representation.

      spring.sleuth.baggage-keys

      List of baggage key names that should be propagated out of process. These keys will be prefixed with baggage before the actual key. This property is set in order to be backward compatible with previous Sleuth versions. @see brave.propagation.ExtraFieldPropagation.FactoryBuilder#addPrefixedFields(String, java.util.Collection)

      spring.sleuth.enabled

      true

      spring.sleuth.feign.enabled

      true

      Enable span information propagation when using Feign.

      spring.sleuth.feign.processor.enabled

      true

      Enable post processor that wraps Feign Context in its tracing representations.

      spring.sleuth.grpc.enabled

      true

      Enable span information propagation when using GRPC.

      spring.sleuth.http.enabled

      true

      spring.sleuth.http.legacy.enabled

      false

      spring.sleuth.hystrix.strategy.enabled

      true

      Enable custom HystrixConcurrencyStrategy that wraps all Callable instances into their Sleuth representative - the TraceCallable.

      spring.sleuth.hystrix.strategy.passthrough

      false

      When enabled the tracing information is passed to the Hystrix execution threads but spans are not created for each execution.

      spring.sleuth.integration.enabled

      true

      Enable Spring Integration sleuth instrumentation.

      spring.sleuth.integration.patterns

      [!hystrixStreamOutput*, *]

      An array of patterns against which channel names will be matched. @see org.springframework.integration.config.GlobalChannelInterceptor#patterns() Defaults to any channel name not matching the Hystrix Stream channel name.

      spring.sleuth.integration.websockets.enabled

      true

      Enable tracing for WebSockets.

      spring.sleuth.keys.http.headers

      Additional headers that should be added as tags if they exist. If the header value is multi-valued, the tag value will be a comma-separated, single-quoted list.

      spring.sleuth.keys.http.prefix

      http.

      Prefix for header names if they are added as tags.

      spring.sleuth.local-keys

      Same as {@link #propagationKeys} except that this field is not propagated to remote services. @see brave.propagation.ExtraFieldPropagation.FactoryBuilder#addRedactedField(String)

      spring.sleuth.log.slf4j.enabled

      true

      Enable a {@link Slf4jScopeDecorator} that prints tracing information in the logs.

      spring.sleuth.log.slf4j.whitelisted-mdc-keys

      A list of keys to be put from baggage to MDC.

      spring.sleuth.messaging.enabled

      false

      Should messaging be turned on.

      spring.sleuth.messaging.jms.enabled

      false

      spring.sleuth.messaging.jms.remote-service-name

      jms

      spring.sleuth.messaging.kafka.enabled

      false

      spring.sleuth.messaging.kafka.remote-service-name

      kafka

      spring.sleuth.messaging.rabbit.enabled

      false

      spring.sleuth.messaging.rabbit.remote-service-name

      rabbitmq

      spring.sleuth.opentracing.enabled

      true

      spring.sleuth.propagation-keys

      List of fields that are referenced the same in-process as it is on the wire. For example, the name "x-vcap-request-id" would be set as-is including the prefix. <p> Note: {@code fieldName} will be implicitly lower-cased. @see brave.propagation.ExtraFieldPropagation.FactoryBuilder#addField(String)

      spring.sleuth.propagation.tag.enabled

      true

      Enables a {@link TagPropagationFinishedSpanHandler} that adds extra propagated fields to span tags.

      spring.sleuth.propagation.tag.whitelisted-keys

      A list of keys to be put from extra propagation fields to span tags.

      spring.sleuth.reactor.enabled.enabled

      true

      When true enables instrumentation for reactor.

      spring.sleuth.redis.enabled

      true

      Enable span information propagation when using Redis.

      spring.sleuth.rxjava.schedulers.hook.enabled

      true

      Enable support for RxJava via RxJavaSchedulersHook.

      spring.sleuth.rxjava.schedulers.ignoredthreads

      [HystrixMetricPoller, ^RxComputation.*$]

      Thread names for which spans will not be sampled.

      spring.sleuth.sampler.probability

      Probability of requests that should be sampled. E.g. 1.0 - 100% requests should be sampled. The precision is whole-numbers only (i.e. there’s no support for 0.1% of the traces).

      spring.sleuth.sampler.rate

      10

      A rate per second can be a nice choice for low-traffic endpoints as it allows you surge protection. For example, you may never expect the endpoint to get more than 50 requests per second. If there was a sudden surge of traffic, to 5000 requests per second, you would still end up with 50 traces per second. Conversely, if you had a percentage, like 10%, the same surge would end up with 500 traces per second, possibly overloading your storage. Amazon X-Ray includes a rate-limited sampler (named Reservoir) for this purpose. Brave has taken the same approach via the {@link brave.sampler.RateLimitingSampler}.

      spring.sleuth.scheduled.enabled

      true

      Enable tracing for {@link org.springframework.scheduling.annotation.Scheduled}.

      spring.sleuth.scheduled.skip-pattern

      org.springframework.cloud.netflix.hystrix.stream.HystrixStreamTask

      Pattern for the fully qualified name of a class that should be skipped.

      spring.sleuth.supports-join

      true

      True means the tracing system supports sharing a span ID between a client and server.

      spring.sleuth.trace-id128

      false

      When true, generate 128-bit trace IDs instead of 64-bit ones.

      spring.sleuth.web.additional-skip-pattern

      Additional pattern for URLs that should be skipped in tracing. This will be appended to the {@link SleuthWebProperties#skipPattern}.

      spring.sleuth.web.client.enabled

      true

      Enable interceptor injecting into {@link org.springframework.web.client.RestTemplate}.

      spring.sleuth.web.client.skip-pattern

      Pattern for URLs that should be skipped in client side tracing.

      spring.sleuth.web.enabled

      true

      When true enables instrumentation for web applications.

      spring.sleuth.web.exception-logging-filter-enabled

      true

      Flag to toggle the presence of a filter that logs thrown exceptions.

      spring.sleuth.web.exception-throwing-filter-enabled

      true

      Flag to toggle the presence of a filter that logs thrown exceptions. @deprecated use {@link #exceptionLoggingFilterEnabled}

      spring.sleuth.web.filter-order

      Order in which the tracing filters should be registered. Defaults to {@link TraceHttpAutoConfiguration#TRACING_FILTER_ORDER}.

      spring.sleuth.web.ignore-auto-configured-skip-patterns

      false

      If set to true, auto-configured skip patterns will be ignored. @see TraceWebAutoConfiguration

      spring.sleuth.web.skip-pattern

      /api-docs.|/swagger.|.\.png|.\.css|.\.js|.\.html|/favicon.ico|/hystrix.stream

      Pattern for URLs that should be skipped in tracing.

      spring.sleuth.zuul.enabled

      true

      Enable span information propagation when using Zuul.

      spring.zipkin.activemq.message-max-bytes

      100000

      Maximum number of bytes for a given message with spans sent to Zipkin over ActiveMQ.

      spring.zipkin.activemq.queue

      zipkin

      Name of the ActiveMQ queue where spans should be sent to Zipkin.

      spring.zipkin.base-url

      localhost:9411/

      URL of the zipkin query server instance. You can also provide the service id of the Zipkin server if Zipkin’s registered in service discovery (e.g. zipkinserver/).

      spring.zipkin.compression.enabled

      false

      spring.zipkin.discovery-client-enabled

      If set to {@code false}, will treat the {@link ZipkinProperties#baseUrl} as a URL always.

      spring.zipkin.enabled

      true

      Enables sending spans to Zipkin.

      spring.zipkin.encoder

      Encoding type of spans sent to Zipkin. Set to {@link SpanBytesEncoder#JSON_V1} if your server is not recent.

      spring.zipkin.kafka.topic

      zipkin

      Name of the Kafka topic where spans should be sent to Zipkin.

      spring.zipkin.locator.discovery.enabled

      false

      Enabling of locating the host name via service discovery.

      spring.zipkin.message-timeout

      1

      Timeout in seconds before pending spans will be sent in batches to Zipkin.

      spring.zipkin.rabbitmq.queue

      zipkin

      Name of the RabbitMQ queue where spans should be sent to Zipkin.

      spring.zipkin.sender.type

      Means of sending spans to Zipkin.

      spring.zipkin.service.name

      The name of the service, from which the Span was sent via HTTP, that should appear in Zipkin.

      +
      +
      +
      + + + + + + + \ No newline at end of file diff --git a/reference/html/features.html b/reference/html/features.html index fd998d22c..a132ec994 100644 --- a/reference/html/features.html +++ b/reference/html/features.html @@ -95,13 +95,13 @@ $(addBlockSwitches);
      Table of Contents
    -

    Features

    +

    1. Features

    @@ -300,13 +197,13 @@ $(addBlockSwitches);
    -

    Introduction

    +

    1. Introduction

    Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud.

    -

    Terminology

    +

    1.1. Terminology

    Spring Cloud Sleuth borrows Dapper’s terminology.

    @@ -397,12 +294,12 @@ Also, the Client Sent event took place.

    -

    Purpose

    +

    1.2. Purpose

    The following sections refer to the example shown in the preceding image.

    -

    Distributed Tracing with Zipkin

    +

    1.2.1. Distributed Tracing with Zipkin

    This example has seven spans. If you go to traces in Zipkin, you can see this number in the second trace, as shown in the following image:

    @@ -471,7 +368,7 @@ to service1 and three spans related to RPC calls.

    -

    Visualizing errors

    +

    1.2.2. Visualizing errors

    Zipkin lets you visualize errors in your trace. When an exception was thrown and was not caught, we set proper tags on the span, which Zipkin can then properly colorize. @@ -498,7 +395,7 @@ You could see in the list of traces one trace that is red. That appears because

    -

    Distributed Tracing with Brave

    +

    1.2.3. Distributed Tracing with Brave

    Starting with version 2.0.0, Spring Cloud Sleuth uses Brave as the tracing library. Consequently, Sleuth no longer takes care of storing the context but delegates that work to Brave.

    @@ -509,7 +406,7 @@ However, if you want to use the legacy Sleuth approaches, you can set the
    -

    Live examples

    +

    1.2.4. Live examples

    Zipkin deployed on Pivotal Web Services @@ -538,7 +435,7 @@ However, if you want to use the legacy Sleuth approaches, you can set the
    -

    Log correlation

    +

    1.2.5. Log correlation

    When using grep to read the logs of those four applications by scanning for a trace ID equal to (for example) 2485ec27856c56f4, you get output resembling the following:

    @@ -598,7 +495,7 @@ If you want to use Grok together with the logs from Cloud Foundry, you have to u
    -
    JSON Logback with Logstash
    +
    JSON Logback with Logstash

    Often, you do not want to store your logs in a text file but in a JSON file that Logstash can immediately pick. To do so, you have to do the following (for readability, we pass the dependencies in the groupId:artifactId:version notation).

    @@ -626,79 +523,79 @@ To do so, you have to do the following (for readability, we pass the dependencie
    <?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="${BUILD_FOLDER:-build}/${springAppName}"/>​
    +    <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="${BUILD_FOLDER:-build}/${springAppName}"/>​
     
    -	<!-- You can override this to have a custom pattern -->
    -	<property name="CONSOLE_LOG_PATTERN"
    -			  value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
    +    <!-- You can override this to have a custom pattern -->
    +    <property name="CONSOLE_LOG_PATTERN"
    +              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
     
    -	<!-- 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>DEBUG</level>
    -		</filter>
    -		<encoder>
    -			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
    -			<charset>utf8</charset>
    -		</encoder>
    -	</appender>
    +    <!-- 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>DEBUG</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>
    -	​
    -	<!-- Appender to log to file in a JSON format -->
    -	<appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
    -		<file>${LOG_FILE}.json</file>
    -		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    -			<fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
    -			<maxHistory>7</maxHistory>
    -		</rollingPolicy>
    -		<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    -			<providers>
    -				<timestamp>
    -					<timeZone>UTC</timeZone>
    -				</timestamp>
    -				<pattern>
    -					<pattern>
    -						{
    -						"severity": "%level",
    -						"service": "${springAppName:-}",
    -						"trace": "%X{X-B3-TraceId:-}",
    -						"span": "%X{X-B3-SpanId:-}",
    -						"parent": "%X{X-B3-ParentSpanId:-}",
    -						"exportable": "%X{X-Span-Export:-}",
    -						"pid": "${PID:-}",
    -						"thread": "%thread",
    -						"class": "%logger{40}",
    -						"rest": "%message"
    -						}
    -					</pattern>
    -				</pattern>
    -			</providers>
    -		</encoder>
    -	</appender>
    -	​
    -	<root level="INFO">
    -		<appender-ref ref="console"/>
    -		<!-- uncomment this to have also JSON logs -->
    -		<!--<appender-ref ref="logstash"/>-->
    -		<!--<appender-ref ref="flatfile"/>-->
    -	</root>
    +    <!-- 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>
    +    ​
    +    <!-- Appender to log to file in a JSON format -->
    +    <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
    +        <file>${LOG_FILE}.json</file>
    +        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    +            <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
    +            <maxHistory>7</maxHistory>
    +        </rollingPolicy>
    +        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    +            <providers>
    +                <timestamp>
    +                    <timeZone>UTC</timeZone>
    +                </timestamp>
    +                <pattern>
    +                    <pattern>
    +                        {
    +                        "severity": "%level",
    +                        "service": "${springAppName:-}",
    +                        "trace": "%X{X-B3-TraceId:-}",
    +                        "span": "%X{X-B3-SpanId:-}",
    +                        "parent": "%X{X-B3-ParentSpanId:-}",
    +                        "exportable": "%X{X-Span-Export:-}",
    +                        "pid": "${PID:-}",
    +                        "thread": "%thread",
    +                        "class": "%logger{40}",
    +                        "rest": "%message"
    +                        }
    +                    </pattern>
    +                </pattern>
    +            </providers>
    +        </encoder>
    +    </appender>
    +    ​
    +    <root level="INFO">
    +        <appender-ref ref="console"/>
    +        <!-- uncomment this to have also JSON logs -->
    +        <!--<appender-ref ref="logstash"/>-->
    +        <!--<appender-ref ref="flatfile"/>-->
    +    </root>
     </configuration>
    @@ -734,7 +631,7 @@ Otherwise, your custom logback file does not properly read the property.
    -

    Propagating Span Context

    +

    1.2.6. Propagating Span Context

    The span context is the state that must get propagated to any child spans across process boundaries. Part of the Span Context is the Baggage. The trace and span IDs are a required part of the span context. @@ -770,7 +667,7 @@ ExtraFieldPropagation.set(initialSpan.context(), "UPPER_CASE", "someValue");

    -
    Baggage versus Span Tags
    +
    Baggage versus Span Tags

    Baggage travels with the trace (every child span contains the baggage of its parent). Zipkin has no knowledge of baggage and does not receive that information.

    @@ -826,16 +723,16 @@ The span must be in scope.
    The code
    initialSpan.tag("foo",
    -		ExtraFieldPropagation.get(initialSpan.context(), "foo"));
    +        ExtraFieldPropagation.get(initialSpan.context(), "foo"));
     initialSpan.tag("UPPER_CASE",
    -		ExtraFieldPropagation.get(initialSpan.context(), "UPPER_CASE"));
    + ExtraFieldPropagation.get(initialSpan.context(), "UPPER_CASE"));
    -

    Adding Sleuth to the Project

    +

    1.3. Adding Sleuth to the Project

    This section addresses how to add Sleuth to your project with either Maven or Gradle.

    @@ -852,7 +749,7 @@ To ensure that your application name is properly displayed in Zipkin, set the
    -

    Only Sleuth (log correlation)

    +

    1.3.1. Only Sleuth (log correlation)

    If you want to use only Spring Cloud Sleuth without the Zipkin integration, add the spring-cloud-starter-sleuth module to your project.

    @@ -923,7 +820,7 @@ dependencies { (2)
    -

    Sleuth with Zipkin via HTTP

    +

    1.3.2. Sleuth with Zipkin via HTTP

    If you want both Sleuth and Zipkin, add the spring-cloud-starter-zipkin dependency.

    @@ -994,7 +891,7 @@ dependencies { (2)
    -

    Sleuth with Zipkin over RabbitMQ or Kafka

    +

    1.3.3. Sleuth with Zipkin over RabbitMQ or Kafka

    If you want to use RabbitMQ or Kafka instead of HTTP, add the spring-rabbit or spring-kafka dependency. The default destination name is zipkin.

    @@ -1101,7 +998,7 @@ dependencies {
    -

    Overriding the auto-configuration of Zipkin

    +

    1.4. Overriding the auto-configuration of Zipkin

    Spring Cloud Sleuth supports sending traces to multiple tracing systems as of version 2.1.0. In order to get this to work, every tracing system needs to have a Reporter<Span> and Sender. @@ -1113,46 +1010,46 @@ To do this you can use respectively ZipkinAutoConfiguration.REPORTER_BEAN_

    @Configuration
     protected static class MyConfig {
     
    -	@Bean(ZipkinAutoConfiguration.REPORTER_BEAN_NAME)
    -	Reporter<zipkin2.Span> myReporter() {
    -		return AsyncReporter.create(mySender());
    -	}
    +    @Bean(ZipkinAutoConfiguration.REPORTER_BEAN_NAME)
    +    Reporter<zipkin2.Span> myReporter() {
    +        return AsyncReporter.create(mySender());
    +    }
     
    -	@Bean(ZipkinAutoConfiguration.SENDER_BEAN_NAME)
    -	MySender mySender() {
    -		return new MySender();
    -	}
    +    @Bean(ZipkinAutoConfiguration.SENDER_BEAN_NAME)
    +    MySender mySender() {
    +        return new MySender();
    +    }
     
    -	static class MySender extends Sender {
    +    static class MySender extends Sender {
     
    -		private boolean spanSent = false;
    +        private boolean spanSent = false;
     
    -		boolean isSpanSent() {
    -			return this.spanSent;
    -		}
    +        boolean isSpanSent() {
    +            return this.spanSent;
    +        }
     
    -		@Override
    -		public Encoding encoding() {
    -			return Encoding.JSON;
    -		}
    +        @Override
    +        public Encoding encoding() {
    +            return Encoding.JSON;
    +        }
     
    -		@Override
    -		public int messageMaxBytes() {
    -			return Integer.MAX_VALUE;
    -		}
    +        @Override
    +        public int messageMaxBytes() {
    +            return Integer.MAX_VALUE;
    +        }
     
    -		@Override
    -		public int messageSizeInBytes(List<byte[]> encodedSpans) {
    -			return encoding().listSizeInBytes(encodedSpans);
    -		}
    +        @Override
    +        public int messageSizeInBytes(List<byte[]> encodedSpans) {
    +            return encoding().listSizeInBytes(encodedSpans);
    +        }
     
    -		@Override
    -		public Call<Void> sendSpans(List<byte[]> encodedSpans) {
    -			this.spanSent = true;
    -			return Call.create(null);
    -		}
    +        @Override
    +        public Call<Void> sendSpans(List<byte[]> encodedSpans) {
    +            this.spanSent = true;
    +            return Call.create(null);
    +        }
     
    -	}
    +    }
     
     }
    @@ -1161,7 +1058,7 @@ protected static class MyConfig {
    -

    Additional Resources

    +

    2. Additional Resources

    You can watch a video of Reshmi Krishna and Marcin Grzejszczak talking about Spring Cloud @@ -1173,7 +1070,7 @@ Sleuth and Zipkin -

    Features

    +

    3. Features

      @@ -1305,7 +1202,7 @@ If you do not use SLF4J, this pattern is NOT automatically applied.
    -

    Introduction to Brave

    +

    3.1. Introduction to Brave

    @@ -1343,7 +1240,7 @@ Most users do not use Brave directly. They use libraries or frameworks rather th It also includes libraries to propagate the trace context over network boundaries (for example, with HTTP headers).

    -

    Tracing

    +

    3.1.1. Tracing

    Most importantly, you need a brave.Tracer, configured to report to Zipkin.

    @@ -1395,7 +1292,7 @@ After starting a span, you can annotate events of interest or add tags containin
    -

    Local Tracing

    +

    3.1.2. Local Tracing

    When tracing code that never leaves your process, run it inside a scoped span.

    @@ -1445,7 +1342,7 @@ next child in an existing trace.

    -

    Customizing Spans

    +

    3.1.3. Customizing Spans

    Once you have a span, you can add tags to it. The tags can be used as lookup keys or details. @@ -1479,7 +1376,7 @@ The former is simpler to understand and test and does not tempt users with span

    -

    Implicitly Looking up the Current Span

    +

    3.1.4. Implicitly Looking up the Current Span

    Sometimes, you do not know if a trace is in progress or not, and you do not want users to do null checks. brave.CurrentSpanCustomizer handles this problem by adding data to any span that’s in progress or drops, as shown in the following example:

    @@ -1500,7 +1397,7 @@ void userCode() {
    @@ -1547,7 +1444,7 @@ span.finish();
    -
    One-Way tracing
    +
    One-Way tracing

    Sometimes, you need to model an asynchronous operation where there is a request but no response. In normal RPC tracing, you use span.finish() @@ -1607,7 +1504,7 @@ next = tracer.newSpan(oneWayReceive.context()).name("step2").start();

    -

    Sampling

    +

    4. Sampling

    Sampling may be employed to reduce the data collected and reported out of process. @@ -1621,7 +1518,7 @@ When a span is not sampled, it adds no overhead (a noop).

    Tracer.Builder.sampler controls this setting, and it defaults to tracing every request.

    -

    Declarative sampling

    +

    4.1. Declarative sampling

    Some applications need to sample based on the type or annotations of a java method.

    @@ -1657,7 +1554,7 @@ public Object traceThing(ProceedingJoinPoint pjp, Traced traced) throws Throwabl
    -

    Custom sampling

    +

    4.2. Custom sampling

    Depending on what the operation is, you may want to apply different policies. For example, you might not want to trace requests to static resources such as images, or you might want to trace all requests to a new api.

    @@ -1688,7 +1585,7 @@ Span nextSpan(final Request input) {
    -

    Sampling in Spring Cloud Sleuth

    +

    4.3. Sampling in Spring Cloud Sleuth

    By default Spring Cloud Sleuth sets all spans to non-exportable. That means that traces appear in logs but not in any remote store. @@ -1715,7 +1612,7 @@ You can configure the rate limit by setting spring.sleuth.sampler.rate

    @Bean
     public Sampler defaultSampler() {
    -	return Sampler.ALWAYS_SAMPLE;
    +    return Sampler.ALWAYS_SAMPLE;
     }
    @@ -1739,7 +1636,7 @@ Doing so forces the current span to be exportable regardless of the sampling dec
    -

    Propagation

    +

    5. Propagation

    Propagation is needed to ensure activities originating from the same root are collected together in the same trace. @@ -1804,7 +1701,7 @@ span = tracer.nextSpan(extractor.extract(request));

    -

    Propagating extra fields

    +

    5.1. Propagating extra fields

    Sometimes you need to propagate extra fields, such as a request ID or an alternate trace context. For example, if you are in a Cloud Foundry environment, you might want to pass the request ID, as shown in the following example:

    @@ -1847,7 +1744,7 @@ for you to create a bean of that type and we will set it in the Tracing
    -

    Prefixed fields

    +

    5.1.1. Prefixed fields

    If they follow a common pattern, you can also prefix fields. The following example shows how to propagate x-vcap-request-id the field as-is but send the country-code and user-id fields on the wire as x-baggage-country-code and x-baggage-user-id, respectively:

    @@ -1920,7 +1817,7 @@ Remember that adding entries to MDC can drastically decrease the performance of
    -

    Extracting a Propagated Context

    +

    5.1.2. Extracting a Propagated Context

    The TraceContext.Extractor<C> reads trace identifiers and sampling status from an incoming request or message. The carrier is usually a request object or headers.

    @@ -1934,7 +1831,7 @@ sharing span IDs between a client and a server.

    -

    Sharing span IDs between Client and Server

    +

    5.1.3. Sharing span IDs between Client and Server

    A normal instrumentation pattern is to create a span representing the server side of an RPC. Extractor.extract might return a complete trace context when applied to an incoming client request. @@ -1988,7 +1885,7 @@ Doing so forces a new child span on Tracer.joinSpan().

    -

    Implementing Propagation

    +

    5.1.4. Implementing Propagation

    TraceContext.Extractor<C> is implemented by a Propagation.Factory plugin. Internally, this code creates the union type, TraceContextOrSamplingFlags, with one of the following: @@ -2008,7 +1905,7 @@ When implementations have extra data, they handle it as follows:

    -

    Current Tracing Component

    +

    6. Current Tracing Component

    Brave supports a "current tracing component" concept, which should only be used when you have no other way to get a reference. @@ -2023,7 +1920,7 @@ Instead, look them up each time you need them.

    -

    Current Span

    +

    7. Current Span

    Brave supports a "current span" concept which represents the in-flight operation. @@ -2045,7 +1942,7 @@ you can use the traceIdString() method like this: tracer.curr

    -

    Setting a span in scope manually

    +

    7.1. Setting a span in scope manually

    When writing new instrumentation, it is important to place a span you created in scope as the current span. Not only does doing so let users access it with Tracer.currentSpan(), but it also allows customizations such as SLF4J MDC to see the current trace IDs.

    @@ -2081,7 +1978,7 @@ try (SpanInScope cleared = tracer.withSpanInScope(null)) {
    -

    Instrumentation

    +

    8. Instrumentation

    Spring Cloud Sleuth automatically instruments all your Spring applications, so you should not have to do anything to activate it. @@ -2107,7 +2004,7 @@ Tags are collected and exported only if there is a Sampler that all

    -

    Span lifecycle

    +

    9. Span lifecycle

    You can do the following operations on the Span by means of brave.Tracer:

    @@ -2146,7 +2043,7 @@ Spring Cloud Sleuth creates an instance of Tracer for you. In order
    -

    Creating and finishing spans

    +

    9.1. Creating and finishing spans

    You can manually create spans by using the Tracer, as shown in the following example:

    @@ -2156,17 +2053,17 @@ Spring Cloud Sleuth creates an instance of Tracer for you. In order // the `newSpan`'s parent. Span newSpan = this.tracer.nextSpan().name("calculateTax"); try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(newSpan.start())) { - // ... - // You can tag a span - newSpan.tag("taxValue", taxValue); - // ... - // You can log an event on a span - newSpan.annotate("taxCalculated"); + // ... + // You can tag a span + newSpan.tag("taxValue", taxValue); + // ... + // You can log an event on a span + newSpan.annotate("taxCalculated"); } finally { - // Once done remember to finish the span. This will allow collecting - // the span to send it to Zipkin - newSpan.finish(); + // Once done remember to finish the span. This will allow collecting + // the span to send it to Zipkin + newSpan.finish(); }
    @@ -2201,7 +2098,7 @@ Your names have to be explicit and concrete. Big names lead to latency issues an
    -

    Continuing Spans

    +

    9.2. Continuing Spans

    Sometimes, you do not want to create a new span but you want to continue one. An example of such a situation might be as follows:

    @@ -2226,23 +2123,23 @@ It is in fact merely a technical implementation detail that you would not necess // the `initialSpan` from thread X Span continuedSpan = this.tracer.toSpan(newSpan.context()); try { - // ... - // You can tag a span - continuedSpan.tag("taxValue", taxValue); - // ... - // You can log an event on a span - continuedSpan.annotate("taxCalculated"); + // ... + // You can tag a span + continuedSpan.tag("taxValue", taxValue); + // ... + // You can log an event on a span + continuedSpan.annotate("taxCalculated"); } finally { - // Once done remember to flush the span. That means that - // it will get reported but the span itself is not yet finished - continuedSpan.flush(); + // Once done remember to flush the span. That means that + // it will get reported but the span itself is not yet finished + continuedSpan.flush(); }
    -

    Creating a Span with an explicit Parent

    +

    9.3. Creating a Span with an explicit Parent

    You might want to start a new span and provide an explicit parent of that span. Assume that the parent of a span is in one thread and you want to start a new span in another thread. @@ -2256,21 +2153,21 @@ You can put the span in scope and then call nextSpan(), as shown in // of the `newSpan` Span newSpan = null; try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(initialSpan)) { - newSpan = this.tracer.nextSpan().name("calculateCommission"); - // ... - // You can tag a span - newSpan.tag("commissionValue", commissionValue); - // ... - // You can log an event on a span - newSpan.annotate("commissionCalculated"); + newSpan = this.tracer.nextSpan().name("calculateCommission"); + // ... + // You can tag a span + newSpan.tag("commissionValue", commissionValue); + // ... + // You can log an event on a span + newSpan.annotate("commissionCalculated"); } finally { - // Once done remember to finish the span. This will allow collecting - // the span to send it to Zipkin. The tags and events set on the - // newSpan will not be present on the parent - if (newSpan != null) { - newSpan.finish(); - } + // Once done remember to finish the span. This will allow collecting + // the span to send it to Zipkin. The tags and events set on the + // newSpan will not be present on the parent + if (newSpan != null) { + newSpan.finish(); + } }

    @@ -2290,7 +2187,7 @@ After creating such a span, you must finish it. Otherwise it is not reported (fo
    -

    Naming spans

    +

    10. Naming spans

    Picking a span name is not a trivial task. A span name should depict an operation name. @@ -2316,21 +2213,19 @@ The name should be low cardinality, so it should not include identifiers.

    Fortunately, for asynchronous processing, you can provide explicit naming.

    -

    @SpanName Annotation

    +

    10.1. @SpanName Annotation

    You can name the span explicitly by using the @SpanName annotation, as shown in the following example:

    -
    	@SpanName("calculateTax")
    -	class TaxCountingRunnable implements Runnable {
    +
    @SpanName("calculateTax")
    +class TaxCountingRunnable implements Runnable {
     
    -		@Override
    -		public void run() {
    -			// perform logic
    -		}
    -
    -	}
    +    @Override
    +    public void run() {
    +        // perform logic
    +    }
     
     }
    @@ -2341,7 +2236,7 @@ The name should be low cardinality, so it should not include identifiers.

    Runnable runnable = new TraceRunnable(this.tracing, spanNamer,
    -		new TaxCountingRunnable());
    +        new TaxCountingRunnable());
     Future<?> future = executorService.submit(runnable);
     // ... some additional logic ...
     future.get();
    @@ -2349,7 +2244,7 @@ future.get();
    -

    toString() method

    +

    10.2. toString() method

    It is pretty rare to create separate classes for Runnable or Callable. Typically, one creates an anonymous instance of those classes. @@ -2362,15 +2257,15 @@ To overcome that limitation, if there is no @SpanName annotation pr

    Runnable runnable = new TraceRunnable(this.tracing, spanNamer, new Runnable() {
    -	@Override
    -	public void run() {
    -		// perform logic
    -	}
    +    @Override
    +    public void run() {
    +        // perform logic
    +    }
     
    -	@Override
    -	public String toString() {
    -		return "calculateTax";
    -	}
    +    @Override
    +    public String toString() {
    +        return "calculateTax";
    +    }
     });
     Future<?> future = executorService.submit(runnable);
     // ... some additional logic ...
    @@ -2381,13 +2276,13 @@ future.get();
    -

    Managing Spans with Annotations

    +

    11. Managing Spans with Annotations

    You can manage spans with a variety of annotations.

    -

    Rationale

    +

    11.1. Rationale

    There are a number of good reasons to manage spans with annotations, including:

    @@ -2410,7 +2305,7 @@ Now you can provide annotations over interfaces and the arguments of those inter
    -

    Creating New Spans

    +

    11.2. Creating New Spans

    If you do not want to create local spans manually, you can use the @NewSpan annotation. Also, we provide the @SpanTag annotation to add tags in an automated fashion.

    @@ -2466,7 +2361,7 @@ concrete one wins (in this case customNameOnTestMethod3 is set).

    -

    Continuing Spans

    +

    11.3. Continuing Spans

    If you want to add tags and annotations to an existing span, you can use the @ContinueSpan annotation, as shown in the following example:

    @@ -2502,7 +2397,7 @@ this.testBean.testMethod13();
    -

    Advanced Tag Setting

    +

    11.4. Advanced Tag Setting

    There are 3 different ways to add tags to a span. All of them are controlled by the SpanTag annotation. The precedence is as follows:

    @@ -2524,7 +2419,7 @@ The default implementation uses SPEL expression resolution.
    -

    Custom extractor

    +

    11.4.1. Custom extractor

    The value of the tag for the following method is computed by an implementation of TagValueResolver interface. Its class name has to be passed as the value of the resolver attribute.

    @@ -2536,7 +2431,7 @@ Its class name has to be passed as the value of the resolver attrib
    @NewSpan
     public void getAnnotationForTagValueResolver(
    -		@SpanTag(key = "test", resolver = TagValueResolver.class) String test) {
    +        @SpanTag(key = "test", resolver = TagValueResolver.class) String test) {
     }
    @@ -2547,7 +2442,7 @@ public void getAnnotationForTagValueResolver(
    @Bean(name = "myCustomTagValueResolver")
     public TagValueResolver tagValueResolver() {
    -	return parameter -> "Value from myCustomTagValueResolver";
    +    return parameter -> "Value from myCustomTagValueResolver";
     }
    @@ -2556,7 +2451,7 @@ public TagValueResolver tagValueResolver() {
    -

    Resolving Expressions for a Value

    +

    11.4.2. Resolving Expressions for a Value

    Consider the following annotated method:

    @@ -2564,7 +2459,7 @@ public TagValueResolver tagValueResolver() {
    @NewSpan
     public void getAnnotationForTagValueExpression(@SpanTag(key = "test",
    -		expression = "'hello' + ' characters'") String test) {
    +        expression = "'hello' + ' characters'") String test) {
     }
    @@ -2574,7 +2469,7 @@ If you want to use some other expression resolution mechanism, you can create yo
    -

    Using the toString() method

    +

    11.4.3. Using the toString() method

    Consider the following annotated method:

    @@ -2593,10 +2488,10 @@ public void getAnnotationForArgumentToString(@SpanTag("test") Long param) {
    -

    Customizations

    +

    12. Customizations

    -

    Customizers

    +

    12.1. Customizers

    With Brave 5.7 you have various options of providing customizers for your project. Brave ships with

    @@ -2618,7 +2513,7 @@ public void getAnnotationForArgumentToString(@SpanTag("test") Long param) {
    -

    HTTP

    +

    12.2. HTTP

    If a customization of client / server parsing of the HTTP related spans is required, just register a bean of type brave.http.HttpClientParser or @@ -2631,7 +2526,7 @@ register a bean of type brave.http.HttpSampler and name the bean

    If you want to completely rewrite the HttpTracing bean you can use the SkipPatternProvider @@ -2644,26 +2539,26 @@ an example of usage of SkipPatternProvider inside a server side,

    -

    TracingFilter

    +

    12.3. TracingFilter

    You can also modify the behavior of the TracingFilter, which is the component that is responsible for processing the input HTTP request and adding tags basing on the HTTP response. You can customize the tags or modify the response headers by registering your own instance of the TracingFilter bean.

    @@ -2677,34 +2572,34 @@ You can customize the tags or modify the response headers by registering your ow @Order(TraceWebServletAutoConfiguration.TRACING_FILTER_ORDER + 1) class MyFilter extends GenericFilterBean { - private final Tracer tracer; + private final Tracer tracer; - MyFilter(Tracer tracer) { - this.tracer = tracer; - } + MyFilter(Tracer tracer) { + this.tracer = tracer; + } - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - Span currentSpan = this.tracer.currentSpan(); - if (currentSpan == null) { - chain.doFilter(request, response); - return; - } - // for readability we're returning trace id in a hex form - ((HttpServletResponse) response).addHeader("ZIPKIN-TRACE-ID", - currentSpan.context().traceIdString()); - // we can also add some custom tags - currentSpan.tag("custom", "tag"); - chain.doFilter(request, response); - } + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + Span currentSpan = this.tracer.currentSpan(); + if (currentSpan == null) { + chain.doFilter(request, response); + return; + } + // for readability we're returning trace id in a hex form + ((HttpServletResponse) response).addHeader("ZIPKIN-TRACE-ID", + currentSpan.context().traceIdString()); + // we can also add some custom tags + currentSpan.tag("custom", "tag"); + chain.doFilter(request, response); + } }
    -

    Custom service name

    +

    12.4. Custom service name

    By default, Sleuth assumes that, when you send a span to Zipkin, you want the span’s service name to be equal to the value of the spring.application.name property. That is not always the case, though. @@ -2718,7 +2613,7 @@ To achieve that, you can pass the following property to your application to over

    -

    Customization of Reported Spans

    +

    12.5. Customization of Reported Spans

    Before reporting spans (for example, to Zipkin) you may want to modify that span in some way. You can do so by using the FinishedSpanHandler interface.

    @@ -2735,24 +2630,24 @@ You can implement the FinishedSpanHandler interface to alter that n
    @Bean
     FinishedSpanHandler handlerOne() {
    -	return new FinishedSpanHandler() {
    -		@Override
    -		public boolean handle(TraceContext traceContext, MutableSpan span) {
    -			span.name("foo");
    -			return true; // keep this span
    -		}
    -	};
    +    return new FinishedSpanHandler() {
    +        @Override
    +        public boolean handle(TraceContext traceContext, MutableSpan span) {
    +            span.name("foo");
    +            return true; // keep this span
    +        }
    +    };
     }
     
     @Bean
     FinishedSpanHandler handlerTwo() {
    -	return new FinishedSpanHandler() {
    -		@Override
    -		public boolean handle(TraceContext traceContext, MutableSpan span) {
    -			span.name(span.name() + " bar");
    -			return true; // keep this span
    -		}
    -	};
    +    return new FinishedSpanHandler() {
    +        @Override
    +        public boolean handle(TraceContext traceContext, MutableSpan span) {
    +            span.name(span.name() + " bar");
    +            return true; // keep this span
    +        }
    +    };
     }
    @@ -2761,7 +2656,7 @@ FinishedSpanHandler handlerTwo() {
    -

    Host Locator

    +

    12.6. Host Locator

    @@ -2792,7 +2687,7 @@ If those are not set, we try to retrieve the host name from the network interfac
    -

    Sending Spans to Zipkin

    +

    13. Sending Spans to Zipkin

    By default, if you add spring-cloud-starter-zipkin as a dependency to your project, when the span is closed, it is sent to Zipkin over HTTP. @@ -2845,14 +2740,14 @@ the ZipkinRestTemplateCustomizer bean.

    @Configuration
     class MyConfig {
    -	@Bean ZipkinRestTemplateCustomizer myCustomizer() {
    -		return new ZipkinRestTemplateCustomizer() {
    -			@Override
    -			void customize(RestTemplate restTemplate) {
    -				// customize the RestTemplate
    -			}
    -		};
    -	}
    +    @Bean ZipkinRestTemplateCustomizer myCustomizer() {
    +        return new ZipkinRestTemplateCustomizer() {
    +            @Override
    +            void customize(RestTemplate restTemplate) {
    +                // customize the RestTemplate
    +            }
    +        };
    +    }
     }
    @@ -2862,18 +2757,18 @@ object, you will have to create a bean of zipkin2.reporter.Sender t
    -
    	@Bean Sender myRestTemplateSender(ZipkinProperties zipkin,
    -			ZipkinRestTemplateCustomizer zipkinRestTemplateCustomizer) {
    -		RestTemplate restTemplate = mySuperCustomRestTemplate();
    -		zipkinRestTemplateCustomizer.customize(restTemplate);
    -		return myCustomSender(zipkin, restTemplate);
    -	}
    +
        @Bean Sender myRestTemplateSender(ZipkinProperties zipkin,
    +            ZipkinRestTemplateCustomizer zipkinRestTemplateCustomizer) {
    +        RestTemplate restTemplate = mySuperCustomRestTemplate();
    +        zipkinRestTemplateCustomizer.customize(restTemplate);
    +        return myCustomSender(zipkin, restTemplate);
    +    }
    @@ -2895,10 +2790,10 @@ In the Finchley release, it got removed.
    -

    Integrations

    +

    15. Integrations

    -

    OpenTracing

    +

    15.1. OpenTracing

    Spring Cloud Sleuth is compatible with OpenTracing. If you have OpenTracing on the classpath, we automatically register the OpenTracing Tracer bean. @@ -2906,30 +2801,30 @@ If you wish to disable this, set spring.sleuth.opentracing.enabled

    -

    Runnable and Callable

    +

    15.2. Runnable and Callable

    If you wrap your logic in Runnable or Callable, you can wrap those classes in their Sleuth representative, as shown in the following example for Runnable:

    Runnable runnable = new Runnable() {
    -	@Override
    -	public void run() {
    -		// do some work
    -	}
    +    @Override
    +    public void run() {
    +        // do some work
    +    }
     
    -	@Override
    -	public String toString() {
    -		return "spanNameFromToStringMethod";
    -	}
    +    @Override
    +    public String toString() {
    +        return "spanNameFromToStringMethod";
    +    }
     };
     // Manual `TraceRunnable` creation with explicit "calculateTax" Span name
     Runnable traceRunnable = new TraceRunnable(this.tracing, spanNamer, runnable,
    -		"calculateTax");
    +        "calculateTax");
     // Wrapping `Runnable` with `Tracing`. That way the current span will be available
     // in the thread of `Runnable`
     Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
    -		.wrap(runnable);
    + .wrap(runnable);
    @@ -2938,23 +2833,23 @@ Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
    Callable<String> callable = new Callable<String>() {
    -	@Override
    -	public String call() throws Exception {
    -		return someLogic();
    -	}
    +    @Override
    +    public String call() throws Exception {
    +        return someLogic();
    +    }
     
    -	@Override
    -	public String toString() {
    -		return "spanNameFromToStringMethod";
    -	}
    +    @Override
    +    public String toString() {
    +        return "spanNameFromToStringMethod";
    +    }
     };
     // Manual `TraceCallable` creation with explicit "calculateTax" Span name
     Callable<String> traceCallable = new TraceCallable<>(this.tracing, spanNamer,
    -		callable, "calculateTax");
    +        callable, "calculateTax");
     // Wrapping `Callable` with `Tracing`. That way the current span will be available
     // in the thread of `Callable`
     Callable<String> traceCallableFromTracer = this.tracing.currentTraceContext()
    -		.wrap(callable);
    + .wrap(callable);
    @@ -2962,9 +2857,9 @@ Callable<String> traceCallableFromTracer = this.tracing.currentTraceContex
    -

    Hystrix

    +

    15.3. Hystrix

    -

    Custom Concurrency Strategy

    +

    15.3.1. Custom Concurrency Strategy

    We register a custom HystrixConcurrencyStrategy called TraceCallable that wraps all Callable instances in their Sleuth representative. The strategy either starts or continues a span, depending on whether tracing was already going on before the Hystrix command was called. @@ -2973,17 +2868,17 @@ To disable the custom Hystrix Concurrency Strategy, set the spring.sleuth.

    -

    Manual Command setting

    +

    15.3.2. Manual Command setting

    Assume that you have the following HystrixCommand:

    HystrixCommand<String> hystrixCommand = new HystrixCommand<String>(setter) {
    -	@Override
    -	protected String run() throws Exception {
    -		return someLogic();
    -	}
    +    @Override
    +    protected String run() throws Exception {
    +        return someLogic();
    +    }
     };
    @@ -2994,17 +2889,17 @@ To disable the custom Hystrix Concurrency Strategy, set the spring.sleuth.
    TraceCommand<String> traceCommand = new TraceCommand<String>(tracer, setter) {
    -	@Override
    -	public String doRun() throws Exception {
    -		return someLogic();
    -	}
    +    @Override
    +    public String doRun() throws Exception {
    +        return someLogic();
    +    }
     };
    -

    RxJava

    +

    15.4. RxJava

    We registering a custom RxJavaSchedulersHook that wraps all Action0 instances in their Sleuth representative, which is called TraceAction. The hook either starts or continues a span, depending on whether tracing was already going on before the Action was scheduled. @@ -3029,12 +2924,12 @@ the Reactor support.

    -

    HTTP integration

    +

    15.5. HTTP integration

    Features from this section can be disabled by setting the spring.sleuth.web.enabled property with value equal to false.

    -

    HTTP Filter

    +

    15.5.1. HTTP Filter

    Through the TracingFilter, all sampled incoming requests result in creation of a Span. That Span’s name is http: + the path to which the request was sent. @@ -3058,7 +2953,7 @@ to true.

    -

    HandlerInterceptor

    +

    15.5.2. HandlerInterceptor

    Since we want the span names to be precise, we use a TraceHandlerInterceptor that either wraps an existing HandlerInterceptor or is added directly to the list of existing HandlerInterceptors. The TraceHandlerInterceptor adds a special request attribute to the given HttpServletRequest. @@ -3068,13 +2963,13 @@ In that case, please file an issue in Spring Cloud Sleuth.

    -

    Async Servlet support

    +

    15.5.3. Async Servlet support

    If your controller returns a Callable or a WebAsyncTask, Spring Cloud Sleuth continues the existing span instead of creating a new one.

    -

    WebFlux support

    +

    15.5.4. WebFlux support

    Through TraceWebFilter, all sampled incoming requests result in creation of a Span. That Span’s name is http: + the path to which the request was sent. @@ -3089,7 +2984,7 @@ If you want to reuse Sleuth’s default skip patterns and append your own, p

    -

    Dubbo RPC support

    +

    15.5.5. Dubbo RPC support

    Via the integration with Brave, Spring Cloud Sleuth supports Dubbo. It’s enough to add the brave-instrumentation-dubbo-rpc dependency:

    @@ -3118,9 +3013,9 @@ An example of Spring Cloud Sleuth and Dubbo can be found -

    HTTP Client Integration

    +

    15.6. HTTP Client Integration

    -

    Synchronous Rest Template

    +

    15.6.1. Synchronous Rest Template

    We inject a RestTemplate interceptor to ensure that all the tracing information is passed to the requests. Each time a call is made, a new Span is created. @@ -3142,7 +3037,7 @@ If you create a RestTemplate instance with a new keywo

    @@ -3164,7 +3059,7 @@ to false. If you do not want to create AsyncRestClient at all, set spring.sleuth.web.async.client.template.enabled to false.

    -
    Multiple Asynchronous Rest Templates
    +
    Multiple Asynchronous Rest Templates

    Sometimes you need to use multiple implementations of the Asynchronous Rest Template. In the following snippet, you can see an example of how to set up such a custom AsyncRestTemplate:

    @@ -3175,23 +3070,23 @@ In the following snippet, you can see an example of how to set up such a custom @EnableAutoConfiguration static class Config { - @Bean(name = "customAsyncRestTemplate") - public AsyncRestTemplate traceAsyncRestTemplate() { - return new AsyncRestTemplate(asyncClientFactory(), - clientHttpRequestFactory()); - } + @Bean(name = "customAsyncRestTemplate") + public AsyncRestTemplate traceAsyncRestTemplate() { + return new AsyncRestTemplate(asyncClientFactory(), + clientHttpRequestFactory()); + } - private ClientHttpRequestFactory clientHttpRequestFactory() { - ClientHttpRequestFactory clientHttpRequestFactory = new CustomClientHttpRequestFactory(); - // CUSTOMIZE HERE - return clientHttpRequestFactory; - } + private ClientHttpRequestFactory clientHttpRequestFactory() { + ClientHttpRequestFactory clientHttpRequestFactory = new CustomClientHttpRequestFactory(); + // CUSTOMIZE HERE + return clientHttpRequestFactory; + } - private AsyncClientHttpRequestFactory asyncClientFactory() { - AsyncClientHttpRequestFactory factory = new CustomAsyncClientHttpRequestFactory(); - // CUSTOMIZE HERE - return factory; - } + private AsyncClientHttpRequestFactory asyncClientFactory() { + AsyncClientHttpRequestFactory factory = new CustomAsyncClientHttpRequestFactory(); + // CUSTOMIZE HERE + return factory; + } }
    @@ -3199,7 +3094,7 @@ static class Config {
    -

    WebClient

    +

    15.6.3. WebClient

    We inject a ExchangeFilterFunction implementation that creates a span and, through on-success and on-error callbacks, takes care of closing client-side spans.

    @@ -3221,7 +3116,7 @@ If you create a WebClient instance with a new keyword,
    -

    Traverson

    +

    15.6.4. Traverson

    If you use the Traverson library, you can inject a RestTemplate as a bean into your Traverson object. Since RestTemplate is already intercepted, you get full support for tracing in your client. The following pseudo code @@ -3238,7 +3133,7 @@ Traverson traverson = new Traverson(URI.create("https://some/address"),

    -

    Apache HttpClientBuilder and HttpAsyncClientBuilder

    +

    15.6.5. Apache HttpClientBuilder and HttpAsyncClientBuilder

    We instrument the HttpClientBuilder and HttpAsyncClientBuilder so that tracing context gets injected to the sent requests.

    @@ -3248,7 +3143,7 @@ tracing context gets injected to the sent requests.

    -

    Netty HttpClient

    +

    15.6.6. Netty HttpClient

    We instrument the Netty’s HttpClient.

    @@ -3270,7 +3165,7 @@ If you create a HttpClient instance with a new keyword
    -

    UserInfoRestTemplateCustomizer

    +

    15.6.7. UserInfoRestTemplateCustomizer

    We instrument the Spring Security’s UserInfoRestTemplateCustomizer.

    @@ -3280,7 +3175,7 @@ If you create a HttpClient instance with a new keyword
    -

    Feign

    +

    15.7. Feign

    By default, Spring Cloud Sleuth provides integration with Feign through TraceFeignClientAutoConfiguration. You can disable it entirely by setting spring.sleuth.feign.enabled to false. @@ -3294,14 +3189,14 @@ However, all the default instrumentation is still there.

    -

    gRPC

    +

    15.8. gRPC

    Spring Cloud Sleuth provides instrumentation for gRPC through TraceGrpcAutoConfiguration. You can disable it entirely by setting spring.sleuth.grpc.enabled to false.

    @@ -3319,14 +3214,14 @@ The gRPC integration relies on two external libraries to instrument clients and
    -
    		<dependency>
    -			<groupId>io.github.lognet</groupId>
    -			<artifactId>grpc-spring-boot-starter</artifactId>
    -		</dependency>
    -		<dependency>
    -			<groupId>io.zipkin.brave</groupId>
    -			<artifactId>brave-instrumentation-grpc</artifactId>
    -		</dependency>
    +
            <dependency>
    +            <groupId>io.github.lognet</groupId>
    +            <artifactId>grpc-spring-boot-starter</artifactId>
    +        </dependency>
    +        <dependency>
    +            <groupId>io.zipkin.brave</groupId>
    +            <artifactId>brave-instrumentation-grpc</artifactId>
    +        </dependency>
    @@ -3340,13 +3235,13 @@ The gRPC integration relies on two external libraries to instrument clients and
    -
    Server Instrumentation
    +
    Server Instrumentation

    Spring Cloud Sleuth leverages grpc-spring-boot-starter to register Brave’s gRPC server interceptor with all services annotated with @GRpcService.

    -
    Client Instrumentation
    +
    Client Instrumentation

    gRPC clients leverage a ManagedChannelBuilder to construct a ManagedChannel used to communicate to the gRPC server. The native ManagedChannelBuilder provides static methods as entry points for construction of ManagedChannel instances, however, this mechanism is outside the influence of the Spring application context.

    @@ -3368,16 +3263,16 @@ Spring Cloud Sleuth provides a SpringAwareManagedChannelBuilder tha
    -

    Variant 2

    +

    15.8.2. Variant 2

    Grpc Spring Boot Starter automatically detects the presence of Spring Cloud Sleuth and brave’s instrumentation for gRPC and registers the necessary client and/or server tooling.

    -

    Asynchronous Communication

    +

    15.9. Asynchronous Communication

    -

    @Async Annotated methods

    +

    15.9.1. @Async Annotated methods

    In Spring Cloud Sleuth, we instrument async-related components so that the tracing information is passed between threads. You can disable this behavior by setting the value of spring.sleuth.async.enabled to false.

    @@ -3400,7 +3295,7 @@ You can disable this behavior by setting the value of spring.sleuth.async.
    -

    @Scheduled Annotated Methods

    +

    15.9.2. @Scheduled Annotated Methods

    In Spring Cloud Sleuth, we instrument scheduled method execution so that the tracing information is passed between threads. You can disable this behavior by setting the value of spring.sleuth.scheduled.enabled to false.

    @@ -3425,7 +3320,7 @@ This behavior may be annoying. That’s why, by default, spring.sleuth
    -

    Executor, ExecutorService, and ScheduledExecutorService

    +

    15.9.3. Executor, ExecutorService, and ScheduledExecutorService

    We provide LazyTraceExecutor, TraceableExecutorService, and TraceableScheduledExecutorService. Those implementations create spans each time a new task is submitted, invoked, or scheduled.

    @@ -3435,11 +3330,11 @@ This behavior may be annoying. That’s why, by default, spring.sleuth
    CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> {
    -	// perform some logic
    -	return 1_000_000L;
    +    // perform some logic
    +    return 1_000_000L;
     }, new TraceableExecutorService(beanFactory, executorService,
    -		// 'calculateTax' explicitly names the span - this param is optional
    -		"calculateTax"));
    + // 'calculateTax' explicitly names the span - this param is optional + "calculateTax"));
    @@ -3461,7 +3356,7 @@ to exclude from span creation, you can use the spring.sleuth.async.ignored property where you can provide a list of bean names.

    -
    Customization of Executors
    +
    Customization of Executors

    Sometimes, you need to set up a custom instance of the AsyncExecutor. The following example shows how to set up such a custom Executor:

    @@ -3475,21 +3370,21 @@ The following example shows how to set up such a custom Executor:
    @@ -3512,12 +3407,12 @@ to add the @Role(BeanDefinition.ROLE_INFRASTRUCTURE) on your
    -

    Messaging

    +

    15.10. Messaging

    Features from this section can be disabled by setting the spring.sleuth.messaging.enabled property with value equal to false.

    -

    Spring Integration and Spring Cloud Stream

    +

    15.10.1. Spring Integration and Spring Cloud Stream

    Spring Cloud Sleuth integrates with Spring Integration. It creates spans for publish and subscribe events. @@ -3556,7 +3451,7 @@ it’s enough for you to register beans of types:

    -

    Spring RabbitMq

    +

    15.10.2. Spring RabbitMq

    We instrument the RabbitTemplate so that tracing headers get injected into the message.

    @@ -3566,7 +3461,7 @@ into the message.

    -

    Spring Kafka

    +

    15.10.3. Spring Kafka

    We instrument the Spring Kafka’s ProducerFactory and ConsumerFactory so that tracing headers get injected into the created Spring Kafka’s @@ -3577,7 +3472,7 @@ so that tracing headers get injected into the created Spring Kafka’s

    -

    Spring Kafka Streams

    +

    15.10.4. Spring Kafka Streams

    We instrument the KafkaStreams KafkaClientSupplier so that tracing headers get injected into the Producer and Consumer`s. A `KafkaStreamsTracing bean @@ -3589,7 +3484,7 @@ allows for further instrumentation through additional TransformerSupplier<

    -

    Spring JMS

    +

    15.10.5. Spring JMS

    We instrument the JmsTemplate so that tracing headers get injected into the message. We also support @JmsListener annotated methods on the consumer side.

    @@ -3612,21 +3507,21 @@ We don’t support baggage propagation for JMS
    -

    Zuul

    +

    15.11. Zuul

    We instrument the Zuul Ribbon integration by enriching the Ribbon requests with tracing information. To disable Zuul support, set the spring.sleuth.zuul.enabled property to false.

    -

    Redis

    +

    15.12. Redis

    We set tracing property to Lettcue ClientResources instance to enable Brave tracing built in Lettuce . To disable Redis support, set the spring.sleuth.redis.enabled property to false.

    -

    Quartz

    +

    15.13. Quartz

    We instrument quartz jobs by adding Job/Trigger listeners to the Quartz Scheduler.

    @@ -3637,7 +3532,15 @@ To disable Redis support, set the spring.sleuth.redis.enabled prope
    -

    Running examples

    +

    16. Configuration properties

    +
    +
    +

    To see the list of all Sleuth related configuration properties please check the Appendix page.

    +
    +
    +
    +
    +

    17. Running examples

    You can see the running examples deployed in the Pivotal Web Services. diff --git a/reference/html/spring-cloud-sleuth.html b/reference/html/spring-cloud-sleuth.html index 499c0dc69..c64539f31 100644 --- a/reference/html/spring-cloud-sleuth.html +++ b/reference/html/spring-cloud-sleuth.html @@ -100,194 +100,91 @@ $(addBlockSwitches);

    Table of Contents
    @@ -300,13 +197,13 @@ $(addBlockSwitches);
    -

    Introduction

    +

    1. Introduction

    Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud.

    -

    Terminology

    +

    1.1. Terminology

    Spring Cloud Sleuth borrows Dapper’s terminology.

    @@ -397,12 +294,12 @@ Also, the Client Sent event took place.

    -

    Purpose

    +

    1.2. Purpose

    The following sections refer to the example shown in the preceding image.

    -

    Distributed Tracing with Zipkin

    +

    1.2.1. Distributed Tracing with Zipkin

    This example has seven spans. If you go to traces in Zipkin, you can see this number in the second trace, as shown in the following image:

    @@ -471,7 +368,7 @@ to service1 and three spans related to RPC calls.

    -

    Visualizing errors

    +

    1.2.2. Visualizing errors

    Zipkin lets you visualize errors in your trace. When an exception was thrown and was not caught, we set proper tags on the span, which Zipkin can then properly colorize. @@ -498,7 +395,7 @@ You could see in the list of traces one trace that is red. That appears because

    -

    Distributed Tracing with Brave

    +

    1.2.3. Distributed Tracing with Brave

    Starting with version 2.0.0, Spring Cloud Sleuth uses Brave as the tracing library. Consequently, Sleuth no longer takes care of storing the context but delegates that work to Brave.

    @@ -509,7 +406,7 @@ However, if you want to use the legacy Sleuth approaches, you can set the
    -

    Live examples

    +

    1.2.4. Live examples

    Zipkin deployed on Pivotal Web Services @@ -538,7 +435,7 @@ However, if you want to use the legacy Sleuth approaches, you can set the
    -

    Log correlation

    +

    1.2.5. Log correlation

    When using grep to read the logs of those four applications by scanning for a trace ID equal to (for example) 2485ec27856c56f4, you get output resembling the following:

    @@ -598,7 +495,7 @@ If you want to use Grok together with the logs from Cloud Foundry, you have to u
    -
    JSON Logback with Logstash
    +
    JSON Logback with Logstash

    Often, you do not want to store your logs in a text file but in a JSON file that Logstash can immediately pick. To do so, you have to do the following (for readability, we pass the dependencies in the groupId:artifactId:version notation).

    @@ -626,79 +523,79 @@ To do so, you have to do the following (for readability, we pass the dependencie
    <?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="${BUILD_FOLDER:-build}/${springAppName}"/>​
    +    <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="${BUILD_FOLDER:-build}/${springAppName}"/>​
     
    -	<!-- You can override this to have a custom pattern -->
    -	<property name="CONSOLE_LOG_PATTERN"
    -			  value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
    +    <!-- You can override this to have a custom pattern -->
    +    <property name="CONSOLE_LOG_PATTERN"
    +              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
     
    -	<!-- 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>DEBUG</level>
    -		</filter>
    -		<encoder>
    -			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
    -			<charset>utf8</charset>
    -		</encoder>
    -	</appender>
    +    <!-- 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>DEBUG</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>
    -	​
    -	<!-- Appender to log to file in a JSON format -->
    -	<appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
    -		<file>${LOG_FILE}.json</file>
    -		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    -			<fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
    -			<maxHistory>7</maxHistory>
    -		</rollingPolicy>
    -		<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    -			<providers>
    -				<timestamp>
    -					<timeZone>UTC</timeZone>
    -				</timestamp>
    -				<pattern>
    -					<pattern>
    -						{
    -						"severity": "%level",
    -						"service": "${springAppName:-}",
    -						"trace": "%X{X-B3-TraceId:-}",
    -						"span": "%X{X-B3-SpanId:-}",
    -						"parent": "%X{X-B3-ParentSpanId:-}",
    -						"exportable": "%X{X-Span-Export:-}",
    -						"pid": "${PID:-}",
    -						"thread": "%thread",
    -						"class": "%logger{40}",
    -						"rest": "%message"
    -						}
    -					</pattern>
    -				</pattern>
    -			</providers>
    -		</encoder>
    -	</appender>
    -	​
    -	<root level="INFO">
    -		<appender-ref ref="console"/>
    -		<!-- uncomment this to have also JSON logs -->
    -		<!--<appender-ref ref="logstash"/>-->
    -		<!--<appender-ref ref="flatfile"/>-->
    -	</root>
    +    <!-- 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>
    +    ​
    +    <!-- Appender to log to file in a JSON format -->
    +    <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
    +        <file>${LOG_FILE}.json</file>
    +        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    +            <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
    +            <maxHistory>7</maxHistory>
    +        </rollingPolicy>
    +        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    +            <providers>
    +                <timestamp>
    +                    <timeZone>UTC</timeZone>
    +                </timestamp>
    +                <pattern>
    +                    <pattern>
    +                        {
    +                        "severity": "%level",
    +                        "service": "${springAppName:-}",
    +                        "trace": "%X{X-B3-TraceId:-}",
    +                        "span": "%X{X-B3-SpanId:-}",
    +                        "parent": "%X{X-B3-ParentSpanId:-}",
    +                        "exportable": "%X{X-Span-Export:-}",
    +                        "pid": "${PID:-}",
    +                        "thread": "%thread",
    +                        "class": "%logger{40}",
    +                        "rest": "%message"
    +                        }
    +                    </pattern>
    +                </pattern>
    +            </providers>
    +        </encoder>
    +    </appender>
    +    ​
    +    <root level="INFO">
    +        <appender-ref ref="console"/>
    +        <!-- uncomment this to have also JSON logs -->
    +        <!--<appender-ref ref="logstash"/>-->
    +        <!--<appender-ref ref="flatfile"/>-->
    +    </root>
     </configuration>
    @@ -734,7 +631,7 @@ Otherwise, your custom logback file does not properly read the property.
    -

    Propagating Span Context

    +

    1.2.6. Propagating Span Context

    The span context is the state that must get propagated to any child spans across process boundaries. Part of the Span Context is the Baggage. The trace and span IDs are a required part of the span context. @@ -770,7 +667,7 @@ ExtraFieldPropagation.set(initialSpan.context(), "UPPER_CASE", "someValue");

    -
    Baggage versus Span Tags
    +
    Baggage versus Span Tags

    Baggage travels with the trace (every child span contains the baggage of its parent). Zipkin has no knowledge of baggage and does not receive that information.

    @@ -826,16 +723,16 @@ The span must be in scope.
    The code
    initialSpan.tag("foo",
    -		ExtraFieldPropagation.get(initialSpan.context(), "foo"));
    +        ExtraFieldPropagation.get(initialSpan.context(), "foo"));
     initialSpan.tag("UPPER_CASE",
    -		ExtraFieldPropagation.get(initialSpan.context(), "UPPER_CASE"));
    + ExtraFieldPropagation.get(initialSpan.context(), "UPPER_CASE"));
    -

    Adding Sleuth to the Project

    +

    1.3. Adding Sleuth to the Project

    This section addresses how to add Sleuth to your project with either Maven or Gradle.

    @@ -852,7 +749,7 @@ To ensure that your application name is properly displayed in Zipkin, set the
    -

    Only Sleuth (log correlation)

    +

    1.3.1. Only Sleuth (log correlation)

    If you want to use only Spring Cloud Sleuth without the Zipkin integration, add the spring-cloud-starter-sleuth module to your project.

    @@ -923,7 +820,7 @@ dependencies { (2)
    -

    Sleuth with Zipkin via HTTP

    +

    1.3.2. Sleuth with Zipkin via HTTP

    If you want both Sleuth and Zipkin, add the spring-cloud-starter-zipkin dependency.

    @@ -994,7 +891,7 @@ dependencies { (2)
    -

    Sleuth with Zipkin over RabbitMQ or Kafka

    +

    1.3.3. Sleuth with Zipkin over RabbitMQ or Kafka

    If you want to use RabbitMQ or Kafka instead of HTTP, add the spring-rabbit or spring-kafka dependency. The default destination name is zipkin.

    @@ -1101,7 +998,7 @@ dependencies {
    -

    Overriding the auto-configuration of Zipkin

    +

    1.4. Overriding the auto-configuration of Zipkin

    Spring Cloud Sleuth supports sending traces to multiple tracing systems as of version 2.1.0. In order to get this to work, every tracing system needs to have a Reporter<Span> and Sender. @@ -1113,46 +1010,46 @@ To do this you can use respectively ZipkinAutoConfiguration.REPORTER_BEAN_

    @Configuration
     protected static class MyConfig {
     
    -	@Bean(ZipkinAutoConfiguration.REPORTER_BEAN_NAME)
    -	Reporter<zipkin2.Span> myReporter() {
    -		return AsyncReporter.create(mySender());
    -	}
    +    @Bean(ZipkinAutoConfiguration.REPORTER_BEAN_NAME)
    +    Reporter<zipkin2.Span> myReporter() {
    +        return AsyncReporter.create(mySender());
    +    }
     
    -	@Bean(ZipkinAutoConfiguration.SENDER_BEAN_NAME)
    -	MySender mySender() {
    -		return new MySender();
    -	}
    +    @Bean(ZipkinAutoConfiguration.SENDER_BEAN_NAME)
    +    MySender mySender() {
    +        return new MySender();
    +    }
     
    -	static class MySender extends Sender {
    +    static class MySender extends Sender {
     
    -		private boolean spanSent = false;
    +        private boolean spanSent = false;
     
    -		boolean isSpanSent() {
    -			return this.spanSent;
    -		}
    +        boolean isSpanSent() {
    +            return this.spanSent;
    +        }
     
    -		@Override
    -		public Encoding encoding() {
    -			return Encoding.JSON;
    -		}
    +        @Override
    +        public Encoding encoding() {
    +            return Encoding.JSON;
    +        }
     
    -		@Override
    -		public int messageMaxBytes() {
    -			return Integer.MAX_VALUE;
    -		}
    +        @Override
    +        public int messageMaxBytes() {
    +            return Integer.MAX_VALUE;
    +        }
     
    -		@Override
    -		public int messageSizeInBytes(List<byte[]> encodedSpans) {
    -			return encoding().listSizeInBytes(encodedSpans);
    -		}
    +        @Override
    +        public int messageSizeInBytes(List<byte[]> encodedSpans) {
    +            return encoding().listSizeInBytes(encodedSpans);
    +        }
     
    -		@Override
    -		public Call<Void> sendSpans(List<byte[]> encodedSpans) {
    -			this.spanSent = true;
    -			return Call.create(null);
    -		}
    +        @Override
    +        public Call<Void> sendSpans(List<byte[]> encodedSpans) {
    +            this.spanSent = true;
    +            return Call.create(null);
    +        }
     
    -	}
    +    }
     
     }
    @@ -1161,7 +1058,7 @@ protected static class MyConfig {
    -

    Additional Resources

    +

    2. Additional Resources

    You can watch a video of Reshmi Krishna and Marcin Grzejszczak talking about Spring Cloud @@ -1173,7 +1070,7 @@ Sleuth and Zipkin -

    Features

    +

    3. Features

      @@ -1305,7 +1202,7 @@ If you do not use SLF4J, this pattern is NOT automatically applied.
    -

    Introduction to Brave

    +

    3.1. Introduction to Brave

    @@ -1343,7 +1240,7 @@ Most users do not use Brave directly. They use libraries or frameworks rather th It also includes libraries to propagate the trace context over network boundaries (for example, with HTTP headers).

    -

    Tracing

    +

    3.1.1. Tracing

    Most importantly, you need a brave.Tracer, configured to report to Zipkin.

    @@ -1395,7 +1292,7 @@ After starting a span, you can annotate events of interest or add tags containin
    -

    Local Tracing

    +

    3.1.2. Local Tracing

    When tracing code that never leaves your process, run it inside a scoped span.

    @@ -1445,7 +1342,7 @@ next child in an existing trace.

    -

    Customizing Spans

    +

    3.1.3. Customizing Spans

    Once you have a span, you can add tags to it. The tags can be used as lookup keys or details. @@ -1479,7 +1376,7 @@ The former is simpler to understand and test and does not tempt users with span

    -

    Implicitly Looking up the Current Span

    +

    3.1.4. Implicitly Looking up the Current Span

    Sometimes, you do not know if a trace is in progress or not, and you do not want users to do null checks. brave.CurrentSpanCustomizer handles this problem by adding data to any span that’s in progress or drops, as shown in the following example:

    @@ -1500,7 +1397,7 @@ void userCode() {
    @@ -1547,7 +1444,7 @@ span.finish();
    -
    One-Way tracing
    +
    One-Way tracing

    Sometimes, you need to model an asynchronous operation where there is a request but no response. In normal RPC tracing, you use span.finish() @@ -1607,7 +1504,7 @@ next = tracer.newSpan(oneWayReceive.context()).name("step2").start();

    -

    Sampling

    +

    4. Sampling

    Sampling may be employed to reduce the data collected and reported out of process. @@ -1621,7 +1518,7 @@ When a span is not sampled, it adds no overhead (a noop).

    Tracer.Builder.sampler controls this setting, and it defaults to tracing every request.

    -

    Declarative sampling

    +

    4.1. Declarative sampling

    Some applications need to sample based on the type or annotations of a java method.

    @@ -1657,7 +1554,7 @@ public Object traceThing(ProceedingJoinPoint pjp, Traced traced) throws Throwabl
    -

    Custom sampling

    +

    4.2. Custom sampling

    Depending on what the operation is, you may want to apply different policies. For example, you might not want to trace requests to static resources such as images, or you might want to trace all requests to a new api.

    @@ -1688,7 +1585,7 @@ Span nextSpan(final Request input) {
    -

    Sampling in Spring Cloud Sleuth

    +

    4.3. Sampling in Spring Cloud Sleuth

    By default Spring Cloud Sleuth sets all spans to non-exportable. That means that traces appear in logs but not in any remote store. @@ -1715,7 +1612,7 @@ You can configure the rate limit by setting spring.sleuth.sampler.rate

    @Bean
     public Sampler defaultSampler() {
    -	return Sampler.ALWAYS_SAMPLE;
    +    return Sampler.ALWAYS_SAMPLE;
     }
    @@ -1739,7 +1636,7 @@ Doing so forces the current span to be exportable regardless of the sampling dec
    -

    Propagation

    +

    5. Propagation

    Propagation is needed to ensure activities originating from the same root are collected together in the same trace. @@ -1804,7 +1701,7 @@ span = tracer.nextSpan(extractor.extract(request));

    -

    Propagating extra fields

    +

    5.1. Propagating extra fields

    Sometimes you need to propagate extra fields, such as a request ID or an alternate trace context. For example, if you are in a Cloud Foundry environment, you might want to pass the request ID, as shown in the following example:

    @@ -1847,7 +1744,7 @@ for you to create a bean of that type and we will set it in the Tracing
    -

    Prefixed fields

    +

    5.1.1. Prefixed fields

    If they follow a common pattern, you can also prefix fields. The following example shows how to propagate x-vcap-request-id the field as-is but send the country-code and user-id fields on the wire as x-baggage-country-code and x-baggage-user-id, respectively:

    @@ -1920,7 +1817,7 @@ Remember that adding entries to MDC can drastically decrease the performance of
    -

    Extracting a Propagated Context

    +

    5.1.2. Extracting a Propagated Context

    The TraceContext.Extractor<C> reads trace identifiers and sampling status from an incoming request or message. The carrier is usually a request object or headers.

    @@ -1934,7 +1831,7 @@ sharing span IDs between a client and a server.

    -

    Sharing span IDs between Client and Server

    +

    5.1.3. Sharing span IDs between Client and Server

    A normal instrumentation pattern is to create a span representing the server side of an RPC. Extractor.extract might return a complete trace context when applied to an incoming client request. @@ -1988,7 +1885,7 @@ Doing so forces a new child span on Tracer.joinSpan().

    -

    Implementing Propagation

    +

    5.1.4. Implementing Propagation

    TraceContext.Extractor<C> is implemented by a Propagation.Factory plugin. Internally, this code creates the union type, TraceContextOrSamplingFlags, with one of the following: @@ -2008,7 +1905,7 @@ When implementations have extra data, they handle it as follows:

    -

    Current Tracing Component

    +

    6. Current Tracing Component

    Brave supports a "current tracing component" concept, which should only be used when you have no other way to get a reference. @@ -2023,7 +1920,7 @@ Instead, look them up each time you need them.

    -

    Current Span

    +

    7. Current Span

    Brave supports a "current span" concept which represents the in-flight operation. @@ -2045,7 +1942,7 @@ you can use the traceIdString() method like this: tracer.curr

    -

    Setting a span in scope manually

    +

    7.1. Setting a span in scope manually

    When writing new instrumentation, it is important to place a span you created in scope as the current span. Not only does doing so let users access it with Tracer.currentSpan(), but it also allows customizations such as SLF4J MDC to see the current trace IDs.

    @@ -2081,7 +1978,7 @@ try (SpanInScope cleared = tracer.withSpanInScope(null)) {
    -

    Instrumentation

    +

    8. Instrumentation

    Spring Cloud Sleuth automatically instruments all your Spring applications, so you should not have to do anything to activate it. @@ -2107,7 +2004,7 @@ Tags are collected and exported only if there is a Sampler that all

    -

    Span lifecycle

    +

    9. Span lifecycle

    You can do the following operations on the Span by means of brave.Tracer:

    @@ -2146,7 +2043,7 @@ Spring Cloud Sleuth creates an instance of Tracer for you. In order
    -

    Creating and finishing spans

    +

    9.1. Creating and finishing spans

    You can manually create spans by using the Tracer, as shown in the following example:

    @@ -2156,17 +2053,17 @@ Spring Cloud Sleuth creates an instance of Tracer for you. In order // the `newSpan`'s parent. Span newSpan = this.tracer.nextSpan().name("calculateTax"); try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(newSpan.start())) { - // ... - // You can tag a span - newSpan.tag("taxValue", taxValue); - // ... - // You can log an event on a span - newSpan.annotate("taxCalculated"); + // ... + // You can tag a span + newSpan.tag("taxValue", taxValue); + // ... + // You can log an event on a span + newSpan.annotate("taxCalculated"); } finally { - // Once done remember to finish the span. This will allow collecting - // the span to send it to Zipkin - newSpan.finish(); + // Once done remember to finish the span. This will allow collecting + // the span to send it to Zipkin + newSpan.finish(); }
    @@ -2201,7 +2098,7 @@ Your names have to be explicit and concrete. Big names lead to latency issues an
    -

    Continuing Spans

    +

    9.2. Continuing Spans

    Sometimes, you do not want to create a new span but you want to continue one. An example of such a situation might be as follows:

    @@ -2226,23 +2123,23 @@ It is in fact merely a technical implementation detail that you would not necess // the `initialSpan` from thread X Span continuedSpan = this.tracer.toSpan(newSpan.context()); try { - // ... - // You can tag a span - continuedSpan.tag("taxValue", taxValue); - // ... - // You can log an event on a span - continuedSpan.annotate("taxCalculated"); + // ... + // You can tag a span + continuedSpan.tag("taxValue", taxValue); + // ... + // You can log an event on a span + continuedSpan.annotate("taxCalculated"); } finally { - // Once done remember to flush the span. That means that - // it will get reported but the span itself is not yet finished - continuedSpan.flush(); + // Once done remember to flush the span. That means that + // it will get reported but the span itself is not yet finished + continuedSpan.flush(); }
    -

    Creating a Span with an explicit Parent

    +

    9.3. Creating a Span with an explicit Parent

    You might want to start a new span and provide an explicit parent of that span. Assume that the parent of a span is in one thread and you want to start a new span in another thread. @@ -2256,21 +2153,21 @@ You can put the span in scope and then call nextSpan(), as shown in // of the `newSpan` Span newSpan = null; try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(initialSpan)) { - newSpan = this.tracer.nextSpan().name("calculateCommission"); - // ... - // You can tag a span - newSpan.tag("commissionValue", commissionValue); - // ... - // You can log an event on a span - newSpan.annotate("commissionCalculated"); + newSpan = this.tracer.nextSpan().name("calculateCommission"); + // ... + // You can tag a span + newSpan.tag("commissionValue", commissionValue); + // ... + // You can log an event on a span + newSpan.annotate("commissionCalculated"); } finally { - // Once done remember to finish the span. This will allow collecting - // the span to send it to Zipkin. The tags and events set on the - // newSpan will not be present on the parent - if (newSpan != null) { - newSpan.finish(); - } + // Once done remember to finish the span. This will allow collecting + // the span to send it to Zipkin. The tags and events set on the + // newSpan will not be present on the parent + if (newSpan != null) { + newSpan.finish(); + } }

    @@ -2290,7 +2187,7 @@ After creating such a span, you must finish it. Otherwise it is not reported (fo
    -

    Naming spans

    +

    10. Naming spans

    Picking a span name is not a trivial task. A span name should depict an operation name. @@ -2316,21 +2213,19 @@ The name should be low cardinality, so it should not include identifiers.

    Fortunately, for asynchronous processing, you can provide explicit naming.

    -

    @SpanName Annotation

    +

    10.1. @SpanName Annotation

    You can name the span explicitly by using the @SpanName annotation, as shown in the following example:

    -
    	@SpanName("calculateTax")
    -	class TaxCountingRunnable implements Runnable {
    +
    @SpanName("calculateTax")
    +class TaxCountingRunnable implements Runnable {
     
    -		@Override
    -		public void run() {
    -			// perform logic
    -		}
    -
    -	}
    +    @Override
    +    public void run() {
    +        // perform logic
    +    }
     
     }
    @@ -2341,7 +2236,7 @@ The name should be low cardinality, so it should not include identifiers.

    Runnable runnable = new TraceRunnable(this.tracing, spanNamer,
    -		new TaxCountingRunnable());
    +        new TaxCountingRunnable());
     Future<?> future = executorService.submit(runnable);
     // ... some additional logic ...
     future.get();
    @@ -2349,7 +2244,7 @@ future.get();
    -

    toString() method

    +

    10.2. toString() method

    It is pretty rare to create separate classes for Runnable or Callable. Typically, one creates an anonymous instance of those classes. @@ -2362,15 +2257,15 @@ To overcome that limitation, if there is no @SpanName annotation pr

    Runnable runnable = new TraceRunnable(this.tracing, spanNamer, new Runnable() {
    -	@Override
    -	public void run() {
    -		// perform logic
    -	}
    +    @Override
    +    public void run() {
    +        // perform logic
    +    }
     
    -	@Override
    -	public String toString() {
    -		return "calculateTax";
    -	}
    +    @Override
    +    public String toString() {
    +        return "calculateTax";
    +    }
     });
     Future<?> future = executorService.submit(runnable);
     // ... some additional logic ...
    @@ -2381,13 +2276,13 @@ future.get();
    -

    Managing Spans with Annotations

    +

    11. Managing Spans with Annotations

    You can manage spans with a variety of annotations.

    -

    Rationale

    +

    11.1. Rationale

    There are a number of good reasons to manage spans with annotations, including:

    @@ -2410,7 +2305,7 @@ Now you can provide annotations over interfaces and the arguments of those inter
    -

    Creating New Spans

    +

    11.2. Creating New Spans

    If you do not want to create local spans manually, you can use the @NewSpan annotation. Also, we provide the @SpanTag annotation to add tags in an automated fashion.

    @@ -2466,7 +2361,7 @@ concrete one wins (in this case customNameOnTestMethod3 is set).

    -

    Continuing Spans

    +

    11.3. Continuing Spans

    If you want to add tags and annotations to an existing span, you can use the @ContinueSpan annotation, as shown in the following example:

    @@ -2502,7 +2397,7 @@ this.testBean.testMethod13();
    -

    Advanced Tag Setting

    +

    11.4. Advanced Tag Setting

    There are 3 different ways to add tags to a span. All of them are controlled by the SpanTag annotation. The precedence is as follows:

    @@ -2524,7 +2419,7 @@ The default implementation uses SPEL expression resolution.
    -

    Custom extractor

    +

    11.4.1. Custom extractor

    The value of the tag for the following method is computed by an implementation of TagValueResolver interface. Its class name has to be passed as the value of the resolver attribute.

    @@ -2536,7 +2431,7 @@ Its class name has to be passed as the value of the resolver attrib
    @NewSpan
     public void getAnnotationForTagValueResolver(
    -		@SpanTag(key = "test", resolver = TagValueResolver.class) String test) {
    +        @SpanTag(key = "test", resolver = TagValueResolver.class) String test) {
     }
    @@ -2547,7 +2442,7 @@ public void getAnnotationForTagValueResolver(
    @Bean(name = "myCustomTagValueResolver")
     public TagValueResolver tagValueResolver() {
    -	return parameter -> "Value from myCustomTagValueResolver";
    +    return parameter -> "Value from myCustomTagValueResolver";
     }
    @@ -2556,7 +2451,7 @@ public TagValueResolver tagValueResolver() {
    -

    Resolving Expressions for a Value

    +

    11.4.2. Resolving Expressions for a Value

    Consider the following annotated method:

    @@ -2564,7 +2459,7 @@ public TagValueResolver tagValueResolver() {
    @NewSpan
     public void getAnnotationForTagValueExpression(@SpanTag(key = "test",
    -		expression = "'hello' + ' characters'") String test) {
    +        expression = "'hello' + ' characters'") String test) {
     }
    @@ -2574,7 +2469,7 @@ If you want to use some other expression resolution mechanism, you can create yo
    -

    Using the toString() method

    +

    11.4.3. Using the toString() method

    Consider the following annotated method:

    @@ -2593,10 +2488,10 @@ public void getAnnotationForArgumentToString(@SpanTag("test") Long param) {
    -

    Customizations

    +

    12. Customizations

    -

    Customizers

    +

    12.1. Customizers

    With Brave 5.7 you have various options of providing customizers for your project. Brave ships with

    @@ -2618,7 +2513,7 @@ public void getAnnotationForArgumentToString(@SpanTag("test") Long param) {
    -

    HTTP

    +

    12.2. HTTP

    If a customization of client / server parsing of the HTTP related spans is required, just register a bean of type brave.http.HttpClientParser or @@ -2631,7 +2526,7 @@ register a bean of type brave.http.HttpSampler and name the bean

    If you want to completely rewrite the HttpTracing bean you can use the SkipPatternProvider @@ -2644,26 +2539,26 @@ an example of usage of SkipPatternProvider inside a server side,

    -

    TracingFilter

    +

    12.3. TracingFilter

    You can also modify the behavior of the TracingFilter, which is the component that is responsible for processing the input HTTP request and adding tags basing on the HTTP response. You can customize the tags or modify the response headers by registering your own instance of the TracingFilter bean.

    @@ -2677,34 +2572,34 @@ You can customize the tags or modify the response headers by registering your ow @Order(TraceWebServletAutoConfiguration.TRACING_FILTER_ORDER + 1) class MyFilter extends GenericFilterBean { - private final Tracer tracer; + private final Tracer tracer; - MyFilter(Tracer tracer) { - this.tracer = tracer; - } + MyFilter(Tracer tracer) { + this.tracer = tracer; + } - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - Span currentSpan = this.tracer.currentSpan(); - if (currentSpan == null) { - chain.doFilter(request, response); - return; - } - // for readability we're returning trace id in a hex form - ((HttpServletResponse) response).addHeader("ZIPKIN-TRACE-ID", - currentSpan.context().traceIdString()); - // we can also add some custom tags - currentSpan.tag("custom", "tag"); - chain.doFilter(request, response); - } + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + Span currentSpan = this.tracer.currentSpan(); + if (currentSpan == null) { + chain.doFilter(request, response); + return; + } + // for readability we're returning trace id in a hex form + ((HttpServletResponse) response).addHeader("ZIPKIN-TRACE-ID", + currentSpan.context().traceIdString()); + // we can also add some custom tags + currentSpan.tag("custom", "tag"); + chain.doFilter(request, response); + } }
    -

    Custom service name

    +

    12.4. Custom service name

    By default, Sleuth assumes that, when you send a span to Zipkin, you want the span’s service name to be equal to the value of the spring.application.name property. That is not always the case, though. @@ -2718,7 +2613,7 @@ To achieve that, you can pass the following property to your application to over

    -

    Customization of Reported Spans

    +

    12.5. Customization of Reported Spans

    Before reporting spans (for example, to Zipkin) you may want to modify that span in some way. You can do so by using the FinishedSpanHandler interface.

    @@ -2735,24 +2630,24 @@ You can implement the FinishedSpanHandler interface to alter that n
    @Bean
     FinishedSpanHandler handlerOne() {
    -	return new FinishedSpanHandler() {
    -		@Override
    -		public boolean handle(TraceContext traceContext, MutableSpan span) {
    -			span.name("foo");
    -			return true; // keep this span
    -		}
    -	};
    +    return new FinishedSpanHandler() {
    +        @Override
    +        public boolean handle(TraceContext traceContext, MutableSpan span) {
    +            span.name("foo");
    +            return true; // keep this span
    +        }
    +    };
     }
     
     @Bean
     FinishedSpanHandler handlerTwo() {
    -	return new FinishedSpanHandler() {
    -		@Override
    -		public boolean handle(TraceContext traceContext, MutableSpan span) {
    -			span.name(span.name() + " bar");
    -			return true; // keep this span
    -		}
    -	};
    +    return new FinishedSpanHandler() {
    +        @Override
    +        public boolean handle(TraceContext traceContext, MutableSpan span) {
    +            span.name(span.name() + " bar");
    +            return true; // keep this span
    +        }
    +    };
     }
    @@ -2761,7 +2656,7 @@ FinishedSpanHandler handlerTwo() {
    -

    Host Locator

    +

    12.6. Host Locator

    @@ -2792,7 +2687,7 @@ If those are not set, we try to retrieve the host name from the network interfac
    -

    Sending Spans to Zipkin

    +

    13. Sending Spans to Zipkin

    By default, if you add spring-cloud-starter-zipkin as a dependency to your project, when the span is closed, it is sent to Zipkin over HTTP. @@ -2845,14 +2740,14 @@ the ZipkinRestTemplateCustomizer bean.

    @Configuration
     class MyConfig {
    -	@Bean ZipkinRestTemplateCustomizer myCustomizer() {
    -		return new ZipkinRestTemplateCustomizer() {
    -			@Override
    -			void customize(RestTemplate restTemplate) {
    -				// customize the RestTemplate
    -			}
    -		};
    -	}
    +    @Bean ZipkinRestTemplateCustomizer myCustomizer() {
    +        return new ZipkinRestTemplateCustomizer() {
    +            @Override
    +            void customize(RestTemplate restTemplate) {
    +                // customize the RestTemplate
    +            }
    +        };
    +    }
     }
    @@ -2862,18 +2757,18 @@ object, you will have to create a bean of zipkin2.reporter.Sender t
    -
    	@Bean Sender myRestTemplateSender(ZipkinProperties zipkin,
    -			ZipkinRestTemplateCustomizer zipkinRestTemplateCustomizer) {
    -		RestTemplate restTemplate = mySuperCustomRestTemplate();
    -		zipkinRestTemplateCustomizer.customize(restTemplate);
    -		return myCustomSender(zipkin, restTemplate);
    -	}
    +
        @Bean Sender myRestTemplateSender(ZipkinProperties zipkin,
    +            ZipkinRestTemplateCustomizer zipkinRestTemplateCustomizer) {
    +        RestTemplate restTemplate = mySuperCustomRestTemplate();
    +        zipkinRestTemplateCustomizer.customize(restTemplate);
    +        return myCustomSender(zipkin, restTemplate);
    +    }
    @@ -2895,10 +2790,10 @@ In the Finchley release, it got removed.
    -

    Integrations

    +

    15. Integrations

    -

    OpenTracing

    +

    15.1. OpenTracing

    Spring Cloud Sleuth is compatible with OpenTracing. If you have OpenTracing on the classpath, we automatically register the OpenTracing Tracer bean. @@ -2906,30 +2801,30 @@ If you wish to disable this, set spring.sleuth.opentracing.enabled

    -

    Runnable and Callable

    +

    15.2. Runnable and Callable

    If you wrap your logic in Runnable or Callable, you can wrap those classes in their Sleuth representative, as shown in the following example for Runnable:

    Runnable runnable = new Runnable() {
    -	@Override
    -	public void run() {
    -		// do some work
    -	}
    +    @Override
    +    public void run() {
    +        // do some work
    +    }
     
    -	@Override
    -	public String toString() {
    -		return "spanNameFromToStringMethod";
    -	}
    +    @Override
    +    public String toString() {
    +        return "spanNameFromToStringMethod";
    +    }
     };
     // Manual `TraceRunnable` creation with explicit "calculateTax" Span name
     Runnable traceRunnable = new TraceRunnable(this.tracing, spanNamer, runnable,
    -		"calculateTax");
    +        "calculateTax");
     // Wrapping `Runnable` with `Tracing`. That way the current span will be available
     // in the thread of `Runnable`
     Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
    -		.wrap(runnable);
    + .wrap(runnable);
    @@ -2938,23 +2833,23 @@ Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
    Callable<String> callable = new Callable<String>() {
    -	@Override
    -	public String call() throws Exception {
    -		return someLogic();
    -	}
    +    @Override
    +    public String call() throws Exception {
    +        return someLogic();
    +    }
     
    -	@Override
    -	public String toString() {
    -		return "spanNameFromToStringMethod";
    -	}
    +    @Override
    +    public String toString() {
    +        return "spanNameFromToStringMethod";
    +    }
     };
     // Manual `TraceCallable` creation with explicit "calculateTax" Span name
     Callable<String> traceCallable = new TraceCallable<>(this.tracing, spanNamer,
    -		callable, "calculateTax");
    +        callable, "calculateTax");
     // Wrapping `Callable` with `Tracing`. That way the current span will be available
     // in the thread of `Callable`
     Callable<String> traceCallableFromTracer = this.tracing.currentTraceContext()
    -		.wrap(callable);
    + .wrap(callable);
    @@ -2962,9 +2857,9 @@ Callable<String> traceCallableFromTracer = this.tracing.currentTraceContex
    -

    Hystrix

    +

    15.3. Hystrix

    -

    Custom Concurrency Strategy

    +

    15.3.1. Custom Concurrency Strategy

    We register a custom HystrixConcurrencyStrategy called TraceCallable that wraps all Callable instances in their Sleuth representative. The strategy either starts or continues a span, depending on whether tracing was already going on before the Hystrix command was called. @@ -2973,17 +2868,17 @@ To disable the custom Hystrix Concurrency Strategy, set the spring.sleuth.

    -

    Manual Command setting

    +

    15.3.2. Manual Command setting

    Assume that you have the following HystrixCommand:

    HystrixCommand<String> hystrixCommand = new HystrixCommand<String>(setter) {
    -	@Override
    -	protected String run() throws Exception {
    -		return someLogic();
    -	}
    +    @Override
    +    protected String run() throws Exception {
    +        return someLogic();
    +    }
     };
    @@ -2994,17 +2889,17 @@ To disable the custom Hystrix Concurrency Strategy, set the spring.sleuth.
    TraceCommand<String> traceCommand = new TraceCommand<String>(tracer, setter) {
    -	@Override
    -	public String doRun() throws Exception {
    -		return someLogic();
    -	}
    +    @Override
    +    public String doRun() throws Exception {
    +        return someLogic();
    +    }
     };
    -

    RxJava

    +

    15.4. RxJava

    We registering a custom RxJavaSchedulersHook that wraps all Action0 instances in their Sleuth representative, which is called TraceAction. The hook either starts or continues a span, depending on whether tracing was already going on before the Action was scheduled. @@ -3029,12 +2924,12 @@ the Reactor support.

    -

    HTTP integration

    +

    15.5. HTTP integration

    Features from this section can be disabled by setting the spring.sleuth.web.enabled property with value equal to false.

    -

    HTTP Filter

    +

    15.5.1. HTTP Filter

    Through the TracingFilter, all sampled incoming requests result in creation of a Span. That Span’s name is http: + the path to which the request was sent. @@ -3058,7 +2953,7 @@ to true.

    -

    HandlerInterceptor

    +

    15.5.2. HandlerInterceptor

    Since we want the span names to be precise, we use a TraceHandlerInterceptor that either wraps an existing HandlerInterceptor or is added directly to the list of existing HandlerInterceptors. The TraceHandlerInterceptor adds a special request attribute to the given HttpServletRequest. @@ -3068,13 +2963,13 @@ In that case, please file an issue in Spring Cloud Sleuth.

    -

    Async Servlet support

    +

    15.5.3. Async Servlet support

    If your controller returns a Callable or a WebAsyncTask, Spring Cloud Sleuth continues the existing span instead of creating a new one.

    -

    WebFlux support

    +

    15.5.4. WebFlux support

    Through TraceWebFilter, all sampled incoming requests result in creation of a Span. That Span’s name is http: + the path to which the request was sent. @@ -3089,7 +2984,7 @@ If you want to reuse Sleuth’s default skip patterns and append your own, p

    -

    Dubbo RPC support

    +

    15.5.5. Dubbo RPC support

    Via the integration with Brave, Spring Cloud Sleuth supports Dubbo. It’s enough to add the brave-instrumentation-dubbo-rpc dependency:

    @@ -3118,9 +3013,9 @@ An example of Spring Cloud Sleuth and Dubbo can be found -

    HTTP Client Integration

    +

    15.6. HTTP Client Integration

    -

    Synchronous Rest Template

    +

    15.6.1. Synchronous Rest Template

    We inject a RestTemplate interceptor to ensure that all the tracing information is passed to the requests. Each time a call is made, a new Span is created. @@ -3142,7 +3037,7 @@ If you create a RestTemplate instance with a new keywo

    @@ -3164,7 +3059,7 @@ to false. If you do not want to create AsyncRestClient at all, set spring.sleuth.web.async.client.template.enabled to false.

    -
    Multiple Asynchronous Rest Templates
    +
    Multiple Asynchronous Rest Templates

    Sometimes you need to use multiple implementations of the Asynchronous Rest Template. In the following snippet, you can see an example of how to set up such a custom AsyncRestTemplate:

    @@ -3175,23 +3070,23 @@ In the following snippet, you can see an example of how to set up such a custom @EnableAutoConfiguration static class Config { - @Bean(name = "customAsyncRestTemplate") - public AsyncRestTemplate traceAsyncRestTemplate() { - return new AsyncRestTemplate(asyncClientFactory(), - clientHttpRequestFactory()); - } + @Bean(name = "customAsyncRestTemplate") + public AsyncRestTemplate traceAsyncRestTemplate() { + return new AsyncRestTemplate(asyncClientFactory(), + clientHttpRequestFactory()); + } - private ClientHttpRequestFactory clientHttpRequestFactory() { - ClientHttpRequestFactory clientHttpRequestFactory = new CustomClientHttpRequestFactory(); - // CUSTOMIZE HERE - return clientHttpRequestFactory; - } + private ClientHttpRequestFactory clientHttpRequestFactory() { + ClientHttpRequestFactory clientHttpRequestFactory = new CustomClientHttpRequestFactory(); + // CUSTOMIZE HERE + return clientHttpRequestFactory; + } - private AsyncClientHttpRequestFactory asyncClientFactory() { - AsyncClientHttpRequestFactory factory = new CustomAsyncClientHttpRequestFactory(); - // CUSTOMIZE HERE - return factory; - } + private AsyncClientHttpRequestFactory asyncClientFactory() { + AsyncClientHttpRequestFactory factory = new CustomAsyncClientHttpRequestFactory(); + // CUSTOMIZE HERE + return factory; + } }
    @@ -3199,7 +3094,7 @@ static class Config {
    -

    WebClient

    +

    15.6.3. WebClient

    We inject a ExchangeFilterFunction implementation that creates a span and, through on-success and on-error callbacks, takes care of closing client-side spans.

    @@ -3221,7 +3116,7 @@ If you create a WebClient instance with a new keyword,
    -

    Traverson

    +

    15.6.4. Traverson

    If you use the Traverson library, you can inject a RestTemplate as a bean into your Traverson object. Since RestTemplate is already intercepted, you get full support for tracing in your client. The following pseudo code @@ -3238,7 +3133,7 @@ Traverson traverson = new Traverson(URI.create("https://some/address"),

    -

    Apache HttpClientBuilder and HttpAsyncClientBuilder

    +

    15.6.5. Apache HttpClientBuilder and HttpAsyncClientBuilder

    We instrument the HttpClientBuilder and HttpAsyncClientBuilder so that tracing context gets injected to the sent requests.

    @@ -3248,7 +3143,7 @@ tracing context gets injected to the sent requests.

    -

    Netty HttpClient

    +

    15.6.6. Netty HttpClient

    We instrument the Netty’s HttpClient.

    @@ -3270,7 +3165,7 @@ If you create a HttpClient instance with a new keyword
    -

    UserInfoRestTemplateCustomizer

    +

    15.6.7. UserInfoRestTemplateCustomizer

    We instrument the Spring Security’s UserInfoRestTemplateCustomizer.

    @@ -3280,7 +3175,7 @@ If you create a HttpClient instance with a new keyword
    -

    Feign

    +

    15.7. Feign

    By default, Spring Cloud Sleuth provides integration with Feign through TraceFeignClientAutoConfiguration. You can disable it entirely by setting spring.sleuth.feign.enabled to false. @@ -3294,14 +3189,14 @@ However, all the default instrumentation is still there.

    -

    gRPC

    +

    15.8. gRPC

    Spring Cloud Sleuth provides instrumentation for gRPC through TraceGrpcAutoConfiguration. You can disable it entirely by setting spring.sleuth.grpc.enabled to false.

    @@ -3319,14 +3214,14 @@ The gRPC integration relies on two external libraries to instrument clients and
    -
    		<dependency>
    -			<groupId>io.github.lognet</groupId>
    -			<artifactId>grpc-spring-boot-starter</artifactId>
    -		</dependency>
    -		<dependency>
    -			<groupId>io.zipkin.brave</groupId>
    -			<artifactId>brave-instrumentation-grpc</artifactId>
    -		</dependency>
    +
            <dependency>
    +            <groupId>io.github.lognet</groupId>
    +            <artifactId>grpc-spring-boot-starter</artifactId>
    +        </dependency>
    +        <dependency>
    +            <groupId>io.zipkin.brave</groupId>
    +            <artifactId>brave-instrumentation-grpc</artifactId>
    +        </dependency>
    @@ -3340,13 +3235,13 @@ The gRPC integration relies on two external libraries to instrument clients and
    -
    Server Instrumentation
    +
    Server Instrumentation

    Spring Cloud Sleuth leverages grpc-spring-boot-starter to register Brave’s gRPC server interceptor with all services annotated with @GRpcService.

    -
    Client Instrumentation
    +
    Client Instrumentation

    gRPC clients leverage a ManagedChannelBuilder to construct a ManagedChannel used to communicate to the gRPC server. The native ManagedChannelBuilder provides static methods as entry points for construction of ManagedChannel instances, however, this mechanism is outside the influence of the Spring application context.

    @@ -3368,16 +3263,16 @@ Spring Cloud Sleuth provides a SpringAwareManagedChannelBuilder tha
    -

    Variant 2

    +

    15.8.2. Variant 2

    Grpc Spring Boot Starter automatically detects the presence of Spring Cloud Sleuth and brave’s instrumentation for gRPC and registers the necessary client and/or server tooling.

    -

    Asynchronous Communication

    +

    15.9. Asynchronous Communication

    -

    @Async Annotated methods

    +

    15.9.1. @Async Annotated methods

    In Spring Cloud Sleuth, we instrument async-related components so that the tracing information is passed between threads. You can disable this behavior by setting the value of spring.sleuth.async.enabled to false.

    @@ -3400,7 +3295,7 @@ You can disable this behavior by setting the value of spring.sleuth.async.
    -

    @Scheduled Annotated Methods

    +

    15.9.2. @Scheduled Annotated Methods

    In Spring Cloud Sleuth, we instrument scheduled method execution so that the tracing information is passed between threads. You can disable this behavior by setting the value of spring.sleuth.scheduled.enabled to false.

    @@ -3425,7 +3320,7 @@ This behavior may be annoying. That’s why, by default, spring.sleuth
    -

    Executor, ExecutorService, and ScheduledExecutorService

    +

    15.9.3. Executor, ExecutorService, and ScheduledExecutorService

    We provide LazyTraceExecutor, TraceableExecutorService, and TraceableScheduledExecutorService. Those implementations create spans each time a new task is submitted, invoked, or scheduled.

    @@ -3435,11 +3330,11 @@ This behavior may be annoying. That’s why, by default, spring.sleuth
    CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> {
    -	// perform some logic
    -	return 1_000_000L;
    +    // perform some logic
    +    return 1_000_000L;
     }, new TraceableExecutorService(beanFactory, executorService,
    -		// 'calculateTax' explicitly names the span - this param is optional
    -		"calculateTax"));
    + // 'calculateTax' explicitly names the span - this param is optional + "calculateTax"));
    @@ -3461,7 +3356,7 @@ to exclude from span creation, you can use the spring.sleuth.async.ignored property where you can provide a list of bean names.

    -
    Customization of Executors
    +
    Customization of Executors

    Sometimes, you need to set up a custom instance of the AsyncExecutor. The following example shows how to set up such a custom Executor:

    @@ -3475,21 +3370,21 @@ The following example shows how to set up such a custom Executor:
    @@ -3512,12 +3407,12 @@ to add the @Role(BeanDefinition.ROLE_INFRASTRUCTURE) on your
    -

    Messaging

    +

    15.10. Messaging

    Features from this section can be disabled by setting the spring.sleuth.messaging.enabled property with value equal to false.

    -

    Spring Integration and Spring Cloud Stream

    +

    15.10.1. Spring Integration and Spring Cloud Stream

    Spring Cloud Sleuth integrates with Spring Integration. It creates spans for publish and subscribe events. @@ -3556,7 +3451,7 @@ it’s enough for you to register beans of types:

    -

    Spring RabbitMq

    +

    15.10.2. Spring RabbitMq

    We instrument the RabbitTemplate so that tracing headers get injected into the message.

    @@ -3566,7 +3461,7 @@ into the message.

    -

    Spring Kafka

    +

    15.10.3. Spring Kafka

    We instrument the Spring Kafka’s ProducerFactory and ConsumerFactory so that tracing headers get injected into the created Spring Kafka’s @@ -3577,7 +3472,7 @@ so that tracing headers get injected into the created Spring Kafka’s

    -

    Spring Kafka Streams

    +

    15.10.4. Spring Kafka Streams

    We instrument the KafkaStreams KafkaClientSupplier so that tracing headers get injected into the Producer and Consumer`s. A `KafkaStreamsTracing bean @@ -3589,7 +3484,7 @@ allows for further instrumentation through additional TransformerSupplier<

    -

    Spring JMS

    +

    15.10.5. Spring JMS

    We instrument the JmsTemplate so that tracing headers get injected into the message. We also support @JmsListener annotated methods on the consumer side.

    @@ -3612,21 +3507,21 @@ We don’t support baggage propagation for JMS
    -

    Zuul

    +

    15.11. Zuul

    We instrument the Zuul Ribbon integration by enriching the Ribbon requests with tracing information. To disable Zuul support, set the spring.sleuth.zuul.enabled property to false.

    -

    Redis

    +

    15.12. Redis

    We set tracing property to Lettcue ClientResources instance to enable Brave tracing built in Lettuce . To disable Redis support, set the spring.sleuth.redis.enabled property to false.

    -

    Quartz

    +

    15.13. Quartz

    We instrument quartz jobs by adding Job/Trigger listeners to the Quartz Scheduler.

    @@ -3637,7 +3532,15 @@ To disable Redis support, set the spring.sleuth.redis.enabled prope
    -

    Running examples

    +

    16. Configuration properties

    +
    +
    +

    To see the list of all Sleuth related configuration properties please check the Appendix page.

    +
    +
    +
    +
    +

    17. Running examples

    You can see the running examples deployed in the Pivotal Web Services.