open-telemetry / open-telemetry/opentelemetry-java

Provide optional attributes in SpanBuilder chains

Open
#5,350 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Feature Request
Dominant language
Java
Stars
2.5k
Forks
1k
Avg merge
3d 17h
Merged PRs (30d)
58

Description

These types of chains seem common:

Span span = tracer.spanBuilder("mySpan")
        .setAttribute(SemanticAttributes.HTTP_METHOD, method)
        .setAttribute(SemanticAttributes.HTTP_ROUTE, route)
        .startSpan();

Suppose that route might be null. The documentation for setAttribute() says that "the behavior of null values is undefined", so there's no way to do this without breaking the chain and assigning the SpanBuilder to a variable.

We could add a setAttribute(AttributeKey<T> key, Optional<T> value) method:

Span span = tracer.spanBuilder("mySpan")
        .setAttribute(SemanticAttributes.HTTP_METHOD, method)
        .setAttribute(SemanticAttributes.HTTP_ROUTE, Optional.ofNullable(route))
        .startSpan();

Another possibility is an apply(Consumer<SpanBuilder> consumer) method:

Optional<String> route = ...;
Span span = tracer.spanBuilder("mySpan")
        .setAttribute(SemanticAttributes.HTTP_METHOD, method)
        .apply(builder -> route.ifPresent(value -> builder.setAttribute(SemanticAttributes.HTTP_ROUTE, value)))
        .startSpan();

The Optional method is very convenient, especially if you already use Optional, whereas apply() is generic and makes it easy to handle anything within the chain, including delegating to a helper method. I'm happy to add both, and add the equivalent methods to AttributesBuilder.

Thoughts?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the SpanBuilder and AttributesBuilder APIs, especially their existing setAttribute methods and fluent chaining behavior. The issue presents Optional and apply alternatives without selecting one; resolve the intended API shape, then define tests showing optional attributes can be handled in the chain and that the equivalent AttributesBuilder behavior is complete.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend-api-design, observability-sre
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.