Skip to content

Commit abe9794

Browse files
Java: how to set a transaction to the current Scope. (#3025)
1 parent f30463c commit abe9794

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
## Set Transaction to Current Scope
2+
3+
To avoid passing `ITransaction` objects to method calls when creating child spans, you can bind the transaction to the current scope using `Sentry#configureScope` and `Scope#setTransaction` methods:
4+
5+
```java {tabTitle:Java}
6+
import io.sentry.ISpan;
7+
import io.sentry.ITransaction;
8+
import io.sentry.Sentry;
9+
10+
void executeTask() {
11+
ITransaction transaction = Sentry.startTransaction("task");
12+
Sentry.configureScope(scope -> scope.setTransaction(transaction));
13+
14+
executeSubTask();
15+
16+
transaction.finish();
17+
}
18+
19+
private void executeSubTask() {
20+
ISpan span = Sentry.getSpan();
21+
if (span == null) {
22+
span = Sentry.startTransaction("sub-task");
23+
} else {
24+
span = span.startChild();
25+
}
26+
// ...
27+
span.finish();
28+
}
29+
```
30+
31+
```kotlin {tabTitle:Kotlin}
32+
import io.sentry.ISpan
33+
import io.sentry.ITransaction
34+
import io.sentry.Sentry
35+
36+
fun executeTask() {
37+
val transaction = Sentry.startTransaction("task")
38+
Sentry.configureScope(scope -> scope.setTransaction(transaction))
39+
40+
executeSubTask()
41+
42+
transaction.finish()
43+
}
44+
45+
private fun executeSubTask() {
46+
var span = Sentry.getSpan()
47+
span = if (span == null) {
48+
Sentry.startTransaction("sub-task")
49+
} else {
50+
span.startChild()
51+
}
52+
// ...
53+
span.finish()
54+
}
55+
```

src/platforms/common/performance/custom-instrumentation.mdx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,6 @@ To instrument certain regions of your code, you can create transactions to captu
3232

3333
<PlatformContent includePath="performance/connect-errors-spans" />
3434

35+
<PlatformContent includePath="performance/set-transaction-current-scope" />
36+
3537
</PlatformSection>

0 commit comments

Comments
 (0)