# Java self-attach agent + public API - How to properly pass the scope and close span-children without closing parent-span

**URL:** <https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337>\
**Category:** APM\
**Tags:** java\
**Created:** [February 14, 2020, 9:17am UTC](https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337 "2020-02-14T09:17:35Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![KoPee](https://avatars.discourse-cdn.com/v4/letter/k/76d3ee/32.png) [@KoPee](https://discuss.elastic.co/u/KoPee)\
**Post date:** [February 14, 2020, 9:17am UTC](https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337/1 "2020-02-14T09:17:36Z")

</div>

Hi ,

**Kibana version** : 7.4.0 , running on ECE  
**Elasticsearch version** : 7.4.0 , running on ECE  
**APM Server version** : 7.4.0 , running on ECE  
**APM Agent language and version** : Java - 1.11.0 - standalone attach

I have a proprietary, OSGI based backend application that compiles into java in the background. (SoftwareAG webMethods)  
Within this backend application, i can call custom java snippets where needed.  
The backend application uses several springboot microservices which are also monitored using APM.

I'm trying to manually instrument APM transactions and spans within the backend application, however I'm struggling a bit with the documentation on how to activate/deactivate spans before creating children.

Agent is set to not instrument automatically since this doesn't really result in valid spans due to the way the application works.

Bear with me, this might take some explaining...

My test case should end up looking like this:

> ```
> Parent Transaction1
> --- Child Span 1
> ---------GrandChild Span 2
> --- Child Span 3
> ---------GrandChild Span 4
> 
> ```

Or in apm timeline format:

> ```
> --------------------------parent-----------------------
> --------child1--------
> --grandchild2--
> --------child1--------
> --grandchild2--
> 
> ```

I've created seperate snippets to create/close transactions and spans.  
All spans are created within the same thread, java objects created in earlier snippets are accessible, but not easily passable throughout the code (so not as an input to the snippet).

Start transaction:

> ```
> Transaction transaction = ElasticApm.startTransactionWithRemoteParent(key -> MessageID).setStartTimestamp(unixtime);
> transaction.activate();
> transaction.setName(service);
> transaction.setType(Transaction.TYPE_REQUEST);
> 
> ```

Stop transaction:

> ```
> Transaction transaction = ElasticApm.currentTransaction();
> long unixtime = timeStampToEpoch(stopTimeStamp);
> transaction.setResult(status);
> transaction.end(unixtime);
> 
> ```

Start Span: --\> I image I need to do something here to check if there is a possible parent span that's still active.

> ```
> Transaction transaction = ElasticApm.currentTransaction();
> Span span = transaction.startSpan("webmethods", "flow", "invoke");
> Scope scope = span.activate();
> scope.end();	
> 
> ```

Stop Span:

> ```
> Span span = ElasticApm.currentSpan();
> Scope scope = span.activate();	
> span.end(unixtime);
> scope.end();	
> 
> ```

On the higher level, i'm then calling my snippets as in this pseudo code:  
If this where normal java code, I image it would look more or less the same:

Transaction1:

> ```
> StartTransaction()
> Child1()
> Otherfunctionalities()
> Child2()
> StopTransaction()
> 
> ```

Children:

> ```
> StartSpan()
> GrandChild()
> Otherfunctionalities()
> StopSpan() 
> 
> ```

Grandchildren:

> ```
> StartSpan()
> GrandChild()
> StopSpan() 
> 
> ```

Now, ...  
this works without throwing any errors; however it seems my spans are not gettign created correctly.

What I see in APM is:

> ```
> Parent Transaction1
> ---------GrandChild Span 2
> ---------GrandChild Span 4
> 
> ```

Furthermore,  
Span 2 has the starttime of what was supposed to be Span 1 and Span 4 has the starttime of Span 3.

The same goes for simpler use cases where I call the snippets in this order:

> ```
> Parent.startSpan()
> Child.startSpan()
> Child.endSpan() --> actually ends parent
> Parent.endSpan() --> actually ends child
> 
> ```

This results in my child having a later endtime than my parent.

So my question is:  
If this where normal Java, how should I be manually creating and ending scopes while calling nested functions, to prevent a child function from picking up and ending the parent transaction?

---

<div class="post-metadata">

**Author:** ![felixbarny](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/felixbarny/32/27341_2.png) [@felixbarny](https://discuss.elastic.co/u/felixbarny)\
**Post date:** [February 18, 2020, 8:23am UTC](https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337/2 "2020-02-18T08:23:57Z")

</div>

In general, you should also ways activate within a try/finally. See also [https://www.elastic.co/guide/en/apm/agent/java/current/public-api.html#api-span-activate](https://www.elastic.co/guide/en/apm/agent/java/current/public-api.html#api-span-activate)

It seems you are activating your transaction but not deactivating it and you activate your span twice. Seems like that's the problem here. If you forget to deactivate (aka leak a scope) bad things can happen.

---

<div class="post-metadata">

**Author:** ![KoPee](https://avatars.discourse-cdn.com/v4/letter/k/76d3ee/32.png) [@KoPee](https://discuss.elastic.co/u/KoPee)\
**Post date:** [February 18, 2020, 8:42am UTC](https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337/3 "2020-02-18T08:42:15Z")

</div>

Hi Felix,

So, should I deactivate my transaction before entering the child method?  
And reactivate it when exiting the child method?

Same for when I enter a child-function from within a span?

The docs are rather clear on how to create single spans within a function, but i'm not entirely following how i can make sure that a newly created span for a child-function doesn't activate the parent-span.

---

<div class="post-metadata">

**Author:** ![felixbarny](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/felixbarny/32/27341_2.png) [@felixbarny](https://discuss.elastic.co/u/felixbarny)\
**Post date:** [February 18, 2020, 9:00am UTC](https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337/4 "2020-02-18T09:00:09Z")

</div>

Something similar to this should work:

```auto
public void parentMethod() {
    Transaction transaction = ElasticApm.startTransactionWithRemoteParent(key -> MessageID).setStartTimestamp(unixtime);
    try (final Scope scope = transaction.activate()) {
        transaction.setName("transaction name");
        transaction.setType(Transaction.TYPE_REQUEST);
        childMethod();
    } catch (Exception e) {
        transaction.captureException(e);
        throw e;
    } finally {
        long unixtime = timeStampToEpoch(stopTimeStamp);
        transaction.setResult(status);
        transaction.end(unixtime);
    }
}

public void childMethod() {
    Span span = ElasticApm.currentSpan().startSpan("webmethods", "flow", "invoke");
    span.setName("span name");
    try (final Scope scope = span.activate()) {
        //
    } catch (Exception e) {
        span.captureException(e);
        throw e;
    } finally {
        span.end(unixtime);
    }
}
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [March 10, 2020, 5:09am UTC](https://discuss.elastic.co/t/java-self-attach-agent-public-api-how-to-properly-pass-the-scope-and-close-span-children-without-closing-parent-span/219337/5 "2020-03-10T05:09:26Z")

</div>

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