Skip to content

Add Span.updateAttributes #133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Sources/Tracing/SpanProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,23 @@ extension Span {
}
}

extension Span {
/// Update Span attributes in a block instead of individually
///
/// Updating a span attribute will involve some type of thread synchronisation
/// primitive to avoid multiple threads updating the attributes at the same
/// time. If you update each attributes individually this can cause slowdown.
/// This function updates the attributes in one call to avoid hitting the
/// thread synchronisation code multiple times
///
/// - Parameter update: closure used to update span attributes
public func updateAttributes(_ update: (inout SpanAttributes) -> Void) {
var attributes = self.attributes
update(&attributes)
self.attributes = attributes
}
}

// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Span Event

Expand Down
17 changes: 17 additions & 0 deletions Tests/TracingTests/SpanTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,23 @@ final class SpanTests: XCTestCase {
XCTAssertEqual(statusCode, 418)
XCTAssertEqual(attributes.get("http.status_code"), SpanAttribute.int32(418))
}

func testSpanUpdateAttributes() {
let span = TestSpan(
operationName: "client",
startTime: DefaultTracerClock.now,
context: ServiceContext.topLevel,
kind: .client,
onEnd: { _ in }
)
span.updateAttributes { attributes in
attributes.set("http.status_code", value: .int32(200))
attributes.set("http.method", value: .string("GET"))
}

XCTAssertEqual(span.attributes.get("http.status_code"), .int32(200))
XCTAssertEqual(span.attributes.get("http.method"), .string("GET"))
}
}

// ==== ----------------------------------------------------------------------------------------------------------------
Expand Down