0

I'm looking for the proper way to set the trace-id for a Span in Brave. Pre-Brave we had:

Span span = Span.builder().traceId(someLong).build();

What's the brave equivalent? I have the following, but it's obviously not correct, as there's no way to set the Span's context explicitly.

Span span = tracer.nextSpan().start();
span.context().toBuilder().traceId(someLong).build();

blackcompe
  • 3,180
  • 16
  • 27

3 Answers3

3

You can use the TraceContext Builder to set your own TraceId.

    TraceContext traceContext = TraceContext.newBuilder().traceId(traceId).build();
    Span span =
            this.tracing.tracer()
                    .toSpan(traceContext)
                    .name("application.name"))
                    .start();

This is optional though; you could let the Tracer generate its own traceId when you create a new Span :-

this.tracing.tracer().nextSpan().name("application.name").start();
Sahil
  • 786
  • 5
  • 15
3

We can build up TraceContext first and then we can use this to create TraceContextOrSamplingFlags which can be then used to create Span as follws:

TraceContext traceContext = TraceContext.newBuilder()
                            .traceId(someTraceId)
                            .spanId(someSpanId)
                            .build();

Span span = tracer.nextSpan(TraceContextOrSamplingFlags.create(traceContext))
                            .name(someName).start();

BishalG
  • 1,414
  • 13
  • 24
2

You can do it like this brave.Span span = tracer.nextSpan().name("name").traceId(someLong).start();

Or more advance

brave.Span span = tracer.nextSpan().name("name").traceId(someLong);
try (SpanInScope ws = tracer.withSpanInScope(span.start())) {
  // do sth
} finally {
  span.finish();
}

Take look at spring cloud sleuth migration guide to catch all changes

yevtsy
  • 564
  • 1
  • 6
  • 18
  • 5
    `traceId()` isn't a setter. – blackcompe Nov 05 '18 at 21:10
  • 1
    You are correct. Root tracers generate 64-bit or 128-bit `traceId`s by default. Nevertheless, you can set `traceId` is via `TraceContext` at least for child traces as same as newly created ones – yevtsy Nov 14 '18 at 09:59