Skip to content

Commit 9bfc1fb

Browse files
authored
Add Span.updateAttributes (apple#133)
1 parent 632a837 commit 9bfc1fb

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Sources/Tracing/SpanProtocol.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,23 @@ extension Span {
161161
}
162162
}
163163

164+
extension Span {
165+
/// Update Span attributes in a block instead of individually.
166+
///
167+
/// Updating a span attribute will involve some type of thread synchronisation
168+
/// primitive to avoid multiple threads updating the attributes at the same
169+
/// time. If you update each attributes individually this can cause slowdown.
170+
/// This function updates the attributes in one call to avoid hitting the
171+
/// thread synchronisation code multiple times.
172+
///
173+
/// - Parameter update: closure used to update span attributes
174+
public func updateAttributes(_ update: (inout SpanAttributes) -> Void) {
175+
var attributes = self.attributes
176+
update(&attributes)
177+
self.attributes = attributes
178+
}
179+
}
180+
164181
// ==== ----------------------------------------------------------------------------------------------------------------
165182
// MARK: Span Event
166183

Tests/TracingTests/SpanTests.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,23 @@ final class SpanTests: XCTestCase {
248248
XCTAssertEqual(statusCode, 418)
249249
XCTAssertEqual(attributes.get("http.status_code"), SpanAttribute.int32(418))
250250
}
251+
252+
func testSpanUpdateAttributes() {
253+
let span = TestSpan(
254+
operationName: "client",
255+
startTime: DefaultTracerClock.now,
256+
context: ServiceContext.topLevel,
257+
kind: .client,
258+
onEnd: { _ in }
259+
)
260+
span.updateAttributes { attributes in
261+
attributes.set("http.status_code", value: .int32(200))
262+
attributes.set("http.method", value: .string("GET"))
263+
}
264+
265+
XCTAssertEqual(span.attributes.get("http.status_code"), .int32(200))
266+
XCTAssertEqual(span.attributes.get("http.method"), .string("GET"))
267+
}
251268
}
252269

253270
// ==== ----------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)