Swift 分布式追踪扩展

模块

Swift 分布式追踪扩展包含以下额外模块

OpenTelemetry 语义约定

入门指南

此模块是 swift-distributed-tracing 的补充,因此您需要依赖它(API 包)。

然后,您可以依赖 extras 包

.package(url: "https://github.com/apple/swift-distributed-tracing.git", from: "..."),
.package(url: "https://github.com/apple/swift-distributed-tracing-extras.git", from: "..."),

如果您正在编写应用程序,而不是库,您还需要依赖特定的追踪器实现。 有关可用的实现,请参阅 swift-distributed-tracing README.md

用法

OpenTelemetry 语义约定包提供了与 OpenTelemetry 的语义约定一起使用的 span 属性。

语义属性使 swift-distributed-tracing 的用户能够使用类型安全、预定义且广为人知的属性在 span 上设置属性,如下所示:

import Tracing
import TracingOpenTelemetrySemanticConventions

// Example framework code, which handles an incoming request and starts a span for handling a request:
func wrapHandleRequest(exampleRequest: ExampleHTTPRequest) async throws -> ExampleHTTPResponse {
    try await InstrumentationSystem.tracer.withSpan(named: "test") { span in

        // Set semantic HTTP attributes before
        span.attributes.http.method = exampleRequest.method
        span.attributes.http.url = exampleRequest.url
        // ...

        // Hand off to user code to handle the request;
        // The current span already has all important semantic attributes set.
        let response = try await actualHandleRequest(exampleRequest: exampleRequest)

        // ... set any response attributes ... 
        
        return response
    }
}

您还可以使用相同的属性语法读取 span 上设置的属性

assert(span.attributes.http.method == "GET")
// etc.

如果没有语义属性包,人们可以使用类型不安全的方法来设置属性,如下所示:

span.attributes["http.method"] = "\(exampleRequest.method)"
span.attributes["http.url"] = "\(exampleRequest.url)"

然而,这种方法容易出错,因为人们可能会意外地记录不太正确的数值类型,或者意外地使用错误的、意想不到的键,而这些键随后不会被 Otel 追踪后端所理解。

支持的版本

此模块支持:Swift 5.4+,适用于所有 Swift 可用的平台。