open-telemetry / open-telemetry/opentelemetry-java
Provide optional attributes in SpanBuilder chains
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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