Skip to content

Commit bb00b98

Browse files
committed
+span additional withSpan to ease entering async world from non-async world
1 parent f0d6746 commit bb00b98

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Sources/Tracing/Tracer.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,5 +150,36 @@ extension Tracer {
150150
throw error // rethrow
151151
}
152152
}
153+
154+
/// Execute the given async operation within a newly created `Span`,
155+
/// started as a child of the passed in `Baggage` or as a root span if `nil`.
156+
///
157+
/// DO NOT `end()` the passed in span manually. It will be ended automatically when the `operation` returns.
158+
///
159+
/// - Parameters:
160+
/// - operationName: The name of the operation being traced. This may be a handler function, database call, ...
161+
/// - baggage: The baggage to be used for the newly created span. It may be obtained by the user manually from the `Baggage.current`,
162+
// task local and modified before passing into this function. The baggage will be made the current task-local baggage for the duration of the `operation`.
163+
/// - kind: The `SpanKind` of the `Span` to be created. Defaults to `.internal`.
164+
/// - operation: operation to wrap in a span start/end and execute immediately
165+
/// - Returns: the value returned by `operation`
166+
/// - Throws: the error the `operation` has thrown (if any)
167+
public func withSpan<T>(
168+
_ operationName: String,
169+
baggage: Baggage?,
170+
ofKind kind: SpanKind = .internal,
171+
_ operation: (Span) async throws -> T
172+
) async rethrows -> T {
173+
let span = self.startSpan(operationName, baggage: baggage ?? .topLevel, ofKind: kind)
174+
defer { span.end() }
175+
do {
176+
return try await Baggage.$current.withValue(span.baggage) {
177+
try await operation(span)
178+
}
179+
} catch {
180+
span.recordError(error)
181+
throw error // rethrow
182+
}
183+
}
153184
}
154185
#endif

0 commit comments

Comments
 (0)