Make Spans autoClosable

Hello,

I am currently evaluating the APM API to enrich the apm data sown in kibana. I am currently following the guideline createSpan.
Would it be possible to implement AutoClosable in Span/Transaction? I find it easier to read:
try(Span span = parent.createSpan()) {
span.setName("SELECT FROM customer");
span.setType("db.mysql.query");
}

In comparison to:
Span span = parent.createSpan();
try {
span.setName("SELECT FROM customer");
span.setType("db.mysql.query");
} finally {
span.end();
}

Hi Wolfram and thanks for your question.

We did actually consider this but unfortunately, try-with-resources doesn't really work out nicely for spans. The reason is that the close() method gets executed before any exceptions are caught. So this would be invalid, for example:

try (Span span = parent.createSpan()) {
    span.setName("SELECT FROM customer");
    span.setType("db.mysql.query");
} catch (Exception e) {
    // invalid, because span has already been ended
    span.captureException(e);
}

To simplify span creation you can also use the @CaptureSpan annotation.

Hello Felix,

Thanks for your response - I didn't see that coming! This order of events was really unexpected to me but good to know. I will try to use the Annotation way then.

1 Like

AutoClosable is designed for resource management where this order of events makes sense but for Spans it unfortunately does not map nicely.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.