开始使用

在不到5分钟内为您的应用获取遥测数据!

本页面将向您展示如何在Swift中开始使用OpenTelemetry。

您将了解如何编写一个简单应用程序,以便将跟踪信息发送到控制台。

先决条件

请确保已在本地安装以下软件:

示例应用程序

以下示例使用基本的Vapor应用程序。如果您没有使用Vapor,没关系-您可以在任何运行在服务器或iOS设备上的Swift应用程序中使用OpenTelemetry Swift。

有关更多示例,请参阅示例

依赖项

首先,在一个新目录中创建一个名为Package.swift的文件,并添加以下内容:

// swift-tools-version:5.9
import PackageDescription

let package = Package(
    name: "dice-server",
    platforms: [
       .macOS(.v13)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.83.1")
    ],
    targets: [
        .executableTarget(
            name: "DiceApp",
            dependencies: [
                .product(name: "Vapor", package: "vapor")
            ],
            path: "."
        )
    ]
)

创建并启动HTTP服务器

在同一个文件夹中,创建一个名为main.swift的文件,并将以下代码添加到该文件中:

import Vapor

@main
enum Entrypoint {
    static func main() async throws {
        let app = try Application(.detect())
        defer { app.shutdown() }
        app.get("rolldice") { req in
            let result = Int.random(in: 1..<7)
            return result
        }
        try app.run()
    }
}

使用以下命令构建和运行应用程序,然后在Web浏览器中打开http://localhost:8080/rolldice以确保它正常工作。

$ swift run
正在构建以进行调试...
构建完成!(0.31秒)
2023-10-04T17:16:13+0200 notice codes.vapor.application : [Vapor] 服务器正在 http://127.0.0.1:8080 启动

仪表化

要将OpenTelemetry添加到您的应用程序中,请使用以下附加依赖项更新Package.swift

// swift-tools-version:5.9
import PackageDescription


let package = Package(
    name: "dice-server",
    platforms: [
       .macOS(.v13)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.83.1"),
        .package(url: "https://github.com/open-telemetry/opentelemetry-swift", from: "1.0.0"),
    ],
    targets: [
        .executableTarget(
            name: "DiceApp",
            dependencies: [
                .product(name: "Vapor", package: "vapor"),
                .product(name: "OpenTelemetryApi", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift"),
                .product(name: "StdoutExporter", package: "opentelemetry-swift"),
                .product(name: "ResourceExtension", package: "opentelemetry-swift"),
            ],
            path: "."
        )
    ]
)

使用以下代码更新main.swift文件以初始化跟踪器并在调用rolldice请求处理程序时发出跨度:

import Vapor
import OpenTelemetryApi
import OpenTelemetrySdk
import StdoutExporter
import ResourceExtension

@main
enum Entrypoint {
    static func main() async throws {

        let spanExporter = StdoutExporter();
        let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
        let resources = DefaultResources().get()

        let instrumentationScopeName = "DiceServer"
        let instrumentationScopeVersion = "semver:0.1.0"

        OpenTelemetry.registerTracerProvider(tracerProvider:
            TracerProviderBuilder()
                .add(spanProcessor: spanProcessor)
                .with(resource: resources)
                .build()
        )
        let tracer = OpenTelemetry.instance.tracerProvider.get(instrumentationName: instrumentationScopeName, instrumentationVersion: instrumentationScopeVersion) as! TracerSdk


        let app = try Application(.detect())
        defer { app.shutdown() }

        app.get("rolldice") { req in
            let span = tracer.spanBuilder(spanName: "GET /rolldice").setSpanKind(spanKind: .client).startSpan()
            let result = Int.random(in: 1..<7)
            span.end();
            return result
        }

        try app.run()
    }
}

再次启动您的服务器:

swift run

当您向位于http://localhost:8080/rolldice的服务器发送请求时,您将在控制台上看到发出的跨度(为方便起见,输出进行了漂亮打印):

{
  "attributes": {},
  "duration": 2.70605087280273e-5,
  "parentSpanId": "0000000000000000",
  "span": "GET /rolldice",
  "spanId": "635455eb236a1592",
  "spanKind": "client",
  "start": 718126321.210727,
  "traceFlags": {
    "sampled": true
  },
  "traceId": "c751f7af0586dac8ef3607c6fc128884",
  "traceState": {
    "entries": []
  }
}

后续步骤

通过手动仪表化来丰富自动生成的仪表化代码,以获得定制的可观察性数据。

查看可用的仪表化库,这些库为流行的框架和库生成遥测数据。

最后修改 December 13, 2023: improve glossary translation (46f8201b)