Top Description Methods
io.opentelemetry.api.trace

public Interface SpanBuilder

Known Direct Implementers
io.opentelemetry.api.trace.DefaultTracer.NoopSpanBuilder
Static Imports
java.util.concurrent.TimeUnit.NANOSECONDS, .TimeUnit.SECONDS

SpanBuilder is used to construct Span instances which define arbitrary scopes of code that are sampled for distributed tracing as a single atomic unit.

This is a simple example where all the work is being done within a single scope and a single thread and the Context is automatically propagated:

class MyClass {
  private final Tracer tracer;

  MyClass(OpenTelemetry openTelemetry) {
    tracer = openTelemetry.getTracer("com.anyco.rpc");
  }

  void doWork() {
    // Create a Span as a child of the current Span.
    Span span = tracer.spanBuilder("MyChildSpan").startSpan();
    try (Scope ss = span.makeCurrent()) {
      span.addEvent("my event");
      doSomeWork();  // Here the new span is in the current Context, so it can be used
                     // implicitly anywhere down the stack.
    } finally {
      span.end();
    }
  }
}

There might be cases where you do not perform all the work inside one static scope and the Context is automatically propagated:

class MyRpcServerInterceptorListener implements RpcServerInterceptor.Listener {
  private final Tracer tracer;
  private Span mySpan;

  public MyRpcInterceptor(OpenTelemetry openTelemetry) {
    tracer = openTelemetry.getTracer("com.example.rpc");
  }

  public void onRequest(String rpcName, Metadata metadata) {
    // Create a Span as a child of the remote Span.
    mySpan = tracer.spanBuilder(rpcName)
        .setParent(extractContextFromMetadata(metadata)).startSpan();
  }

  public void onExecuteHandler(ServerCallHandler serverCallHandler) {
    try (Scope ws = mySpan.makeCurrent()) {
      Span.current().addEvent("Start rpc execution.");
      serverCallHandler.run();  // Here the new span is in the current Context, so it can be
                                // used implicitly anywhere down the stack.
    }
  }

  // Called when the RPC is canceled and guaranteed onComplete will not be called.
  public void onCancel() {
    // IMPORTANT: DO NOT forget to ended the Span here as the work is done.
    mySpan.setStatus(StatusCode.ERROR);
    mySpan.end();
  }

  // Called when the RPC is done and guaranteed onCancel will not be called.
  public void onComplete(RpcStatus rpcStatus) {
    // IMPORTANT: DO NOT forget to ended the Span here as the work is done.
    mySpan.setStatus(rpcStatusToCanonicalTraceStatus(status);
    mySpan.end();
  }
}

This is a simple example where all the work is being done within a single scope and the Context is manually propagated:

class MyClass {
  private final Tracer tracer;

  MyClass(OpenTelemetry openTelemetry) {
    tracer = openTelemetry.getTracer("com.example.rpc");
  }

  void doWork(Span parent) {
    Span childSpan = tracer.spanBuilder("MyChildSpan")
        .setParent(Context.current().with(parent))
        .startSpan();
    childSpan.addEvent("my event");
    try {
      doSomeWork(childSpan); // Manually propagate the new span down the stack.
    } finally {
      // To make sure we end the span even in case of an exception.
      childSpan.end();  // Manually end the span.
    }
  }
}

see SpanBuilder#startSpan for usage examples.

Method Summary

Modifier and TypeMethod and Description
public default SpanBuilder

Returns:

this.
setAllAttributes
(Attributes
the attributes
attributes
)

Sets attributes to the SpanBuilder.

public SpanBuilder

Returns:

this.
setAttribute
(String
the key for this attribute.
key
,
String
the value for this attribute.
value
)

Sets an attribute to the newly created Span.

public SpanBuilder

Returns:

this.
setAttribute
(String
the key for this attribute.
key
,
long
the value for this attribute.
value
)

Sets an attribute to the newly created Span.

public SpanBuilder

Returns:

this.
setAttribute
(String
the key for this attribute.
key
,
double
the value for this attribute.
value
)

Sets an attribute to the newly created Span.

public SpanBuilder

Returns:

this.
setAttribute
(String
the key for this attribute.
key
,
boolean
the value for this attribute.
value
)

Sets an attribute to the newly created Span.

public <T> SpanBuilder

Returns:

this.
setAttribute
(AttributeKey<T>
the key for this attribute.
key
,
T
the value for this attribute.
value
)

Sets an attribute to the newly created Span.

public default SpanBuilder

Returns:

this.
setAttribute
(AttributeKey<Long>
the key for this attribute.
key
,
int
the value for this attribute.
value
)

Sets an attribute to the newly created Span.

public SpanBuilder

Returns:

this.
setNoParent
()

Sets the option to become a root Span for a new trace.

public SpanBuilder

Returns:

this.
setParent
(Context
the Context.
context
)

Sets the parent to use from the specified Context.

public SpanBuilder

Returns:

this.
setSpanKind
(SpanKind
the kind of the newly created Span.
spanKind
)

Sets the SpanKind for the newly created Span.

public SpanBuilder

Returns:

this.
setStartTimestamp
(long
the explicit start timestamp from the epoch of the newly created Span.
startTimestamp
,
TimeUnit
the unit of the timestamp.
unit
)

Sets an explicit start timestamp for the newly created Span.

public default SpanBuilder

Returns:

this.
setStartTimestamp
(Instant
the explicit start timestamp from the epoch of the newly created Span.
startTimestamp
)

Sets an explicit start timestamp for the newly created Span.

public Span

Returns:

the newly created Span.
startSpan
()

Starts a new Span.

Method Detail

setAllAttributesback to summary
public default SpanBuilder setAllAttributes(Attributes attributes)

Sets attributes to the SpanBuilder. If the SpanBuilder previously contained a mapping for any of the keys, the old values are replaced by the specified values.

Parameters
attributes:Attributes

the attributes

Returns:SpanBuilder

this.

Annotations
@SuppressWarnings:unchecked
Since
1.2.0
setAttributeback to summary
public SpanBuilder setAttribute(String key, String value)

Sets an attribute to the newly created Span. If SpanBuilder previously contained a mapping for the key, the old value is replaced by the specified value.

If a null or empty String value is passed in, the behavior is undefined, and hence strongly discouraged.

Note

It is strongly recommended to use setAttribute(AttributeKey, Object), and pre-allocate your keys, if possible.

Parameters
key:String

the key for this attribute.

value:String

the value for this attribute.

Returns:SpanBuilder

this.

setAttributeback to summary
public SpanBuilder setAttribute(String key, long value)

Sets an attribute to the newly created Span. If SpanBuilder previously contained a mapping for the key, the old value is replaced by the specified value.

Note

It is strongly recommended to use setAttribute(AttributeKey, Object), and pre-allocate your keys, if possible.

Parameters
key:String

the key for this attribute.

value:long

the value for this attribute.

Returns:SpanBuilder

this.

setAttributeback to summary
public SpanBuilder setAttribute(String key, double value)

Sets an attribute to the newly created Span. If SpanBuilder previously contained a mapping for the key, the old value is replaced by the specified value.

Note

It is strongly recommended to use setAttribute(AttributeKey, Object), and pre-allocate your keys, if possible.

Parameters
key:String

the key for this attribute.

value:double

the value for this attribute.

Returns:SpanBuilder

this.

setAttributeback to summary
public SpanBuilder setAttribute(String key, boolean value)

Sets an attribute to the newly created Span. If SpanBuilder previously contained a mapping for the key, the old value is replaced by the specified value.

Note

It is strongly recommended to use setAttribute(AttributeKey, Object), and pre-allocate your keys, if possible.

Parameters
key:String

the key for this attribute.

value:boolean

the value for this attribute.

Returns:SpanBuilder

this.

setAttributeback to summary
public <T> SpanBuilder setAttribute(AttributeKey<T> key, T value)

Sets an attribute to the newly created Span. If SpanBuilder previously contained a mapping for the key, the old value is replaced by the specified value.

Note

the behavior of null values is undefined, and hence strongly discouraged.

Parameters
key:AttributeKey<T>

the key for this attribute.

value:T

the value for this attribute.

Returns:SpanBuilder

this.

setAttributeback to summary
public default SpanBuilder setAttribute(AttributeKey<Long> key, int value)

Sets an attribute to the newly created Span. If SpanBuilder previously contained a mapping for the key, the old value is replaced by the specified value.

Parameters
key:AttributeKey<Long>

the key for this attribute.

value:int

the value for this attribute.

Returns:SpanBuilder

this.

Since
1.45.0
setNoParentback to summary
public SpanBuilder setNoParent()

Sets the option to become a root Span for a new trace. If not set, the value of Span.current() at startSpan() time will be used as parent.

Observe that any previously set parent will be discarded.

Returns:SpanBuilder

this.

setParentback to summary
public SpanBuilder setParent(Context context)

Sets the parent to use from the specified Context. If not set, the value of Span.current() at startSpan() time will be used as parent.

If no Span is available in the specified Context, the resulting Span will become a root instance, as if setNoParent() had been called.

If called multiple times, only the last specified value will be used. Observe that the state defined by a previous call to setNoParent() will be discarded.

Parameters
context:Context

the Context.

Returns:SpanBuilder

this.

setSpanKindback to summary
public SpanBuilder setSpanKind(SpanKind spanKind)

Sets the SpanKind for the newly created Span. If not called, the implementation will provide a default value SpanKind#INTERNAL.

Parameters
spanKind:SpanKind

the kind of the newly created Span.

Returns:SpanBuilder

this.

setStartTimestampback to summary
public SpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit)

Sets an explicit start timestamp for the newly created Span.

LIRInstruction.Use this method to specify an explicit start timestamp. If not called, the implementation will use the timestamp value at startSpan() time, which should be the default case.

Important this is NOT equivalent with System.nanoTime().

Parameters
startTimestamp:long

the explicit start timestamp from the epoch of the newly created Span.

unit:TimeUnit

the unit of the timestamp.

Returns:SpanBuilder

this.

setStartTimestampback to summary
public default SpanBuilder setStartTimestamp(Instant startTimestamp)

Sets an explicit start timestamp for the newly created Span.

Use this method to specify an explicit start timestamp. If not called, the implementation will use the timestamp value at startSpan() time, which should be the default case.

Important this is NOT equivalent with System.nanoTime().

Parameters
startTimestamp:Instant

the explicit start timestamp from the epoch of the newly created Span.

Returns:SpanBuilder

this.

startSpanback to summary
public Span startSpan()

Starts a new Span.

Users must manually call Span#end() to end this Span.

Does not install the newly created Span to the current Context.

Important Note

This method can be called only once per SpanBuilder instance and as the last method called. After this method is called calling any method is undefined behavior.

Example of usage:

class MyClass {
  private final Tracer tracer;

  MyClass(OpenTelemetry openTelemetry) {
    tracer = openTelemetry.getTracer("com.example.rpc");
  }

  void doWork(Span parent) {
    Span childSpan = tracer.spanBuilder("MyChildSpan")
         .setParent(Context.current().with(parent))
         .startSpan();
    childSpan.addEvent("my event");
    try {
      doSomeWork(childSpan); // Manually propagate the new span down the stack.
    } finally {
      // To make sure we end the span even in case of an exception.
      childSpan.end();  // Manually end the span.
    }
  }
}
Returns:Span

the newly created Span.