Skip to content

Commit

Permalink
Updates to latest Brave, removing deprecated usage
Browse files Browse the repository at this point in the history
Notably, this avoids `Span.remoteEndpoint` and deprecated test helpers.
  • Loading branch information
Adrian Cole authored and adriancole committed Sep 14, 2018
1 parent 7fc10e8 commit e2ec762
Show file tree
Hide file tree
Showing 24 changed files with 174 additions and 84 deletions.
99 changes: 64 additions & 35 deletions docs/src/main/asciidoc/spring-cloud-sleuth.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -75,35 +75,47 @@ Spans have a context that includes trace identifiers that place the span at the

==== Local Tracing

When tracing local code, you can run it inside a span, as shown in the following example:
When tracing code that never leaves your process, run it inside a scoped span.

```java

@Autowired Tracer tracer;

Span span = tracer.newTrace().name("encode").start();
// Start a new trace or a span within an existing trace representing an operation
ScopedSpan span = tracer.startScopedSpan("encode");
try {
doSomethingExpensive();
// The span is in "scope" meaning downstream code such as loggers can see trace IDs
return encoder.encode();
} catch (RuntimeException | Error e) {
span.error(e); // Unless you handle exceptions, you might not know the operation failed!
throw e;
} finally {
span.finish();
span.finish(); // always finish the span
}
```

In the preceding example, the span is the root of the trace.
In many cases, the span is part of an existing trace.
When this is the case, call `newChild` instead of `newTrace`, as shown in the following example:

When you need more features, or finer control, use the `Span` type:
```java
@Autowired Tracer tracer;

Span span = tracer.newChild(root.context()).name("encode").start();
try {
doSomethingExpensive();
// Start a new trace or a span within an existing trace representing an operation
Span span = tracer.nextSpan().name("encode").start();
// Put the span in "scope" so that downstream code such as loggers can see trace IDs
try (SpanInScope ws = tracer.withSpanInScope(span)) {
return encoder.encode();
} catch (RuntimeException | Error e) {
span.error(e); // Unless you handle exceptions, you might not know the operation failed!
throw e;
} finally {
span.finish();
span.finish(); // note the scope is independent of the span. Always finish a span.
}
```

Both of the above examples report the exact same span on finish!

In the above example, the span will be either a new root span or the
next child in an existing trace.


==== Customizing Spans

Once you have a span, you can add tags to it.
Expand Down Expand Up @@ -156,23 +168,26 @@ RPC tracing is often done automatically by interceptors. Behind the scenes, they
The following example shows how to add a client span:

```java
@Autowired Tracing tracing;
@Autowired Tracer tracer;

// before you send a request, add metadata that describes the operation
span = tracer.newTrace().name("get").type(CLIENT);
span.tag("clnt/finagle.version", "6.36.0");
span.tag(TraceKeys.HTTP_PATH, "/api");
span.remoteEndpoint(Endpoint.builder()
.serviceName("backend")
.ipv4(127 << 24 | 1)
.port(8080).build());
span = tracer.nextSpan().name(service + "/" + method).kind(CLIENT);
span.tag("myrpc.version", "1.0.0");
span.remoteServiceName("backend");
span.remoteIpAndPort("172.3.4.1", 8108);

// Add the trace context to the request, so it can be propagated in-band
tracing.propagation().injector(Request::addHeader)
.inject(span.context(), request);

// when the request is scheduled, start the span
span.start();

// if you have callbacks for when data is on the wire, note those events
span.annotate(Constants.WIRE_SEND);
span.annotate(Constants.WIRE_RECV);
// if there is an error, tag the span
span.tag("error", error.getCode());
// or if there is an exception
span.error(exception);

// when the response is complete, finish the span
span.finish();
Expand All @@ -187,10 +202,11 @@ to indicate that the response was received. In one-way tracing, you use

The following example shows how a client might model a one-way operation:
```java
@Autowired Tracing tracing;
@Autowired Tracer tracer;

// start a new span representing a client request
oneWaySend = tracer.newSpan(parent).kind(Span.Kind.CLIENT);
oneWaySend = tracer.nextSpan().name(service + "/" + method).kind(CLIENT);

// Add the trace context to the request, so it can be propagated in-band
tracing.propagation().injector(Request::addHeader)
Expand Down Expand Up @@ -243,16 +259,24 @@ Most users use a framework interceptor to automate this sort of policy.
The following example shows how that might work internally:

```java
@Autowired Tracing tracing;
@Autowired Tracer tracer;

// derives a sample rate from an annotation on a java method
DeclarativeSampler<Traced> sampler = DeclarativeSampler.create(Traced::sampleRate);

@Around("@annotation(traced)")
public Object traceThing(ProceedingJoinPoint pjp, Traced traced) throws Throwable {
Span span = tracing.tracer().newTrace(sampler.sample(traced))...
// When there is no trace in progress, this decides using an annotation
Sampler decideUsingAnnotation = declarativeSampler.toSampler(traced);
Tracer tracer = tracer.withSampler(decideUsingAnnotation);

// This code looks the same as if there was no declarative override
ScopedSpan span = tracer.startScopedSpan(spanName(pjp));
try {
return pjp.proceed();
} catch (RuntimeException | Error e) {
span.error(e);
throw e;
} finally {
span.finish();
}
Expand All @@ -269,15 +293,20 @@ The following example shows how that might work internally:

```java
@Autowired Tracer tracer;

Span newTrace(Request input) {
SamplingFlags flags = SamplingFlags.NONE;
if (input.url().startsWith("/experimental")) {
flags = SamplingFlags.SAMPLED;
} else if (input.url().startsWith("/static")) {
flags = SamplingFlags.NOT_SAMPLED;
}
return tracer.newTrace(flags);
@Autowired Sampler fallback;

Span nextSpan(final Request input) {
Sampler requestBased = Sampler() {
@Override public boolean isSampled(long traceId) {
if (input.url().startsWith("/experimental")) {
return true;
} else if (input.url().startsWith("/static")) {
return false;
}
return fallback.isSampled(traceId);
}
};
return tracer.withSampler(requestBased).nextSpan();
}
```

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@
<spring-cloud-stream.version>Fishtown.BUILD-SNAPSHOT</spring-cloud-stream.version>
<spring-cloud-netflix.version>2.1.0.BUILD-SNAPSHOT</spring-cloud-netflix.version>
<spring-cloud-openfeign.version>2.1.0.BUILD-SNAPSHOT</spring-cloud-openfeign.version>
<brave.version>5.3.0</brave.version>
<brave.version>5.3.3</brave.version>
<spring-security-boot-autoconfigure.version>2.0.4.RELEASE</spring-security-boot-autoconfigure.version>
</properties>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.ClassUtils;
import zipkin2.Endpoint;

/**
* This starts and propagates {@link Span.Kind#PRODUCER} span for each message sent (via native
Expand Down Expand Up @@ -145,7 +144,7 @@ public Span nextSpan(Message<?> message) {
this.injector.inject(span.context(), headers);
if (!span.isNoop()) {
span.kind(Span.Kind.PRODUCER).name("send").start();
span.remoteEndpoint(Endpoint.newBuilder().serviceName(REMOTE_SERVICE_NAME).build());
span.remoteServiceName(REMOTE_SERVICE_NAME);
addTags(message, span, channel);
}
if (log.isDebugEnabled()) {
Expand Down Expand Up @@ -211,7 +210,7 @@ private boolean isDirectChannel(MessageChannel channel) {
this.injector.inject(span.context(), headers);
if (!span.isNoop()) {
span.kind(Span.Kind.CONSUMER).name("receive").start();
span.remoteEndpoint(Endpoint.newBuilder().serviceName(REMOTE_SERVICE_NAME).build());
span.remoteServiceName(REMOTE_SERVICE_NAME);
addTags(message, span, channel);
}
if (log.isDebugEnabled()) {
Expand Down Expand Up @@ -248,7 +247,7 @@ public void afterReceiveCompletion(Message<?> message, MessageChannel channel,
Span consumerSpan = this.tracer.nextSpan(extracted);
if (!consumerSpan.isNoop()) {
consumerSpan.kind(Span.Kind.CONSUMER).start();
consumerSpan.remoteEndpoint(Endpoint.newBuilder().serviceName(REMOTE_SERVICE_NAME).build());
consumerSpan.remoteServiceName(REMOTE_SERVICE_NAME);
addTags(message, consumerSpan, channel);
consumerSpan.finish();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import brave.sampler.Sampler;
import org.assertj.core.api.BDDAssertions;
import org.junit.Before;
Expand All @@ -53,7 +54,9 @@ public class SpringCloudSleuthDocTests {

ArrayListSpanReporter reporter = new ArrayListSpanReporter();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.sampler(Sampler.ALWAYS_SAMPLE)
.spanReporter(this.reporter)
.build();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package org.springframework.cloud.sleuth.instrument.async;

import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.assertj.core.api.BDDAssertions;
Expand All @@ -19,7 +20,9 @@ public class TraceAsyncAspectTest {

ArrayListSpanReporter reporter = new ArrayListSpanReporter();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.spanReporter(this.reporter)
.build();
ProceedingJoinPoint point = Mockito.mock(ProceedingJoinPoint.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.assertj.core.api.BDDAssertions;
import org.awaitility.Awaitility;
import org.junit.Test;
Expand All @@ -37,7 +38,9 @@ public class TraceAsyncListenableTaskExecutorTest {

AsyncListenableTaskExecutor delegate = new SimpleAsyncTaskExecutor();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.build();
Tracer tracer = this.tracing.tracer();
TraceAsyncListenableTaskExecutor traceAsyncListenableTaskExecutor = new TraceAsyncListenableTaskExecutor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand All @@ -40,7 +41,9 @@ public class TraceCallableTests {
ExecutorService executor = Executors.newSingleThreadExecutor();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.spanReporter(this.reporter)
.build();
Tracer tracer = this.tracing.tracer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand All @@ -40,7 +41,9 @@ public class TraceRunnableTests {
ExecutorService executor = Executors.newSingleThreadExecutor();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.spanReporter(this.reporter)
.build();
Tracer tracer = this.tracing.tracer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.assertj.core.api.BDDAssertions;
import org.junit.After;
import org.junit.Before;
Expand Down Expand Up @@ -60,7 +61,9 @@ public class TraceableExecutorServiceTests {
ExecutorService traceManagerableExecutorService;
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.spanReporter(this.reporter)
.build();
Tracer tracer = this.tracing.tracer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
import java.util.function.Predicate;

import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand All @@ -46,7 +47,9 @@
public class TraceableScheduledExecutorServiceTest {

Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.build();
@Mock
BeanFactory beanFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import java.util.concurrent.TimeUnit;

import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.StrictScopeDecorator;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -51,7 +52,9 @@ public class SleuthHystrixConcurrencyStrategyTest {

ArrayListSpanReporter reporter = new ArrayListSpanReporter();
Tracing tracing = Tracing.newBuilder()
.currentTraceContext(new StrictCurrentTraceContext())
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(StrictScopeDecorator.create())
.build())
.spanReporter(this.reporter)
.build();

Expand Down
Loading

0 comments on commit e2ec762

Please sign in to comment.