Scala Using with OpenTelemetry Span to automatically end the Span Block

Scala Using with OpenTelemetry Span to automatically end the Span Block

Past couple of years, I've been spending quite a bit of time with OpenTelemetry (OTEL). As always, always looking for shortcuts in code.

One of the things that is always just annoying is that span.end() just doesn't mesh well with "close" or "release" etc. all the time. So, things like try-resource and Scala's Using won't understand it without some help.

So, this little bit of code using implicit support in Scala (I'm still on Scala 2.13 much) will help that along.

First need to define the implicit type of class for Span to make it Releaseable

import scala.util.Using
import io.opentelemetry.api.trace.Span
  
implicit val releaseable: Using.Releasable[Span] = s => {
    s.end()
}

>Note: Obviously, or perhaps not so obvious, is that can be put in a separate class and imported.

Then, just wrap it in a using and release gets called and at the end of the block whatever you define in the wrap above – for Span we need the end() called.

Using{Span.current()}(s => {
	s.addEvent("doing some span stuff")
})