Skip to content

Commit b124e35

Browse files
committed
more docs on restoring baggage
1 parent 712d7be commit b124e35

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Sources/Tracing/Docs.docc/Guides/InstrumentYourLibrary.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,35 @@ It is worth noting that double-ending a span should be considered a programmer e
293293
>
294294
> Please also take care to never `end()` a span that was created using `withSpan()` APIs, because `withSpan` will automatically end the span when the closure returns.
295295
296+
### Storing and restoring baggage across callbacks
297+
298+
Note also since a `Span` contains an instrumentation `Baggage`, you can also pass the span's baggage to any APIs which may need it, or even restore the baggage e.g. for loggers to pick it up while emitting log statements:
299+
300+
```swift
301+
class StatefulHandler {
302+
var span: Span
303+
304+
func startHandling(request: HTTPRequest) {
305+
self.span = InstrumentationSystem.tracer.startSpan("\(request.path)")
306+
}
307+
308+
// callback, form other task, so we don't have the task-local information here anymore
309+
func onSomethingHappening(event: SomeEvent) {
310+
Baggage.withValue(span.baggage) { // restore task-local baggage
311+
// which allows the baggage to be used by loggers and tracers as usual again:
312+
log.info("Event happened: \(event)")
313+
314+
// since the baggage was restored here, the startSpan will pick it up,
315+
// and the "event-id" span will be a child of the "request.path" span we started before.
316+
InstrumentationSystem.tracer.startSpan("event-\(event.id)") {
317+
// ... handle the event ...
318+
}
319+
}
320+
}
321+
}
322+
323+
```
324+
296325
### Global vs. "Stored" Tracers and Instruments
297326

298327
Tracing functions similarily to swift-log and swift-metrics, in the sense that there is a global "backend" configured at application start, by end-users (developers) of an application. And this is how using ``InstrumentationSystem/tracer`` gets the "right" tracer at runtime.

0 commit comments

Comments
 (0)