Swift Opentelemetry Instrumentation

This documentation contains instructions on how to set up OpenTelemetry(OTel) instrumentation in your Swift application. OpenTelemetry, also known as OTel for short, is an open-source observability framework that can help you generate and collect telemetry data - traces, metrics, and logs from your Swift application.

Once the telemetry data is generated, you can configure an exporter to send the data to SigNoz for monitoring and visualization.

There are three major steps to using OpenTelemetry:

  • Instrumenting your Swift application with OpenTelemetry
  • Configuring the exporter to send data to SigNoz
  • Validating the configuration to ensure that data is being sent as expected.

In this tutorial, we will instrument a Swift application for traces and send it to SigNoz.

Requirements

Swift

Send traces to SigNoz Cloud

Based on your application environment, you can choose the setup below to send traces to SigNoz Cloud.

From VMs, there are two ways to send data to SigNoz Cloud.

Send traces directly to SigNoz cloud

Here we will be sending traces to SigNoz cloud in 4 easy steps, if you want to send traces to self hosted SigNoz , you can refer to this.

✅ Info

If you are using the sample swift application, then you just need to update the ingestion key and SigNoz endpoint after that you are good to go!

Step 1 : Instrument your application with OpenTelemetry

To configure your Swift application to send traces to OpenTelemetry you need to install opentelemetry-swift and grpc-swift as dependency in your project.

For that, paste the following inside Package.swift of your project.

 dependencies: [
        .package(url: "https://github.com/open-telemetry/opentelemetry-swift.git", .upToNextMajor(from: "1.9.1")),
        .package(url: "https://github.com/grpc/grpc-swift", from: "1.15.0"),
    ],
    targets: [
        .executableTarget(
            name: "<NAME_OF_APP>",
            dependencies: [
                .product(name: "OpenTelemetryApi", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift"),
                .product(name: "StdoutExporter", package: "opentelemetry-swift"),
                .product(name: "ResourceExtension", package: "opentelemetry-swift"),
                .product(name: "ZipkinExporter", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetryProtocolExporter", package: "opentelemetry-swift"),
                .product(name: "SignPostIntegration", package: "opentelemetry-swift"),
                .product(name: "GRPC", package: "grpc-swift")
            ],
            path: "."
        )
    ]

Replace NAME_OF_APP with the name of app, you will see this name in SigNoz Services section.

You also need to add the following imports to use the methods and functions from the packages/dependencies which you just imported in Package.swift file.

import Foundation
import GRPC
import NIO
import NIOSSL
import OpenTelemetryApi
import OpenTelemetryProtocolExporterCommon
import OpenTelemetryProtocolExporterGrpc
import OpenTelemetrySdk
import ResourceExtension
import SignPostIntegration
import StdoutExporter
import ZipkinExporter

Step 2: Initialize the tracer

To enable tracing and send traces to the SigNoz cloud, you need to initialize the tracer, to do that insert the following code snippet into your main.swift file

var resources = DefaultResources().get()

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

let otlpConfiguration: OtlpConfiguration = OtlpConfiguration(timeout: TimeInterval(10), headers: [("signoz-access-token", <SIGNOZ_INGESTION_KEY>)])

let grpcChannel = ClientConnection.usingPlatformAppropriateTLS(for: MultiThreadedEventLoopGroup(numberOfThreads:1)).connect(host: <SIGNOZ_INGESTION_URL>, port: <PORT>)

let otlpTraceExporter = OtlpTraceExporter(channel: grpcChannel,
                                      config: otlpConfiguration)
let stdoutExporter = StdoutExporter()

let spanExporter = MultiSpanExporter(spanExporters: [otlpTraceExporter, stdoutExporter])

let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
OpenTelemetry.registerTracerProvider(tracerProvider:
    TracerProviderBuilder()
        .add(spanProcessor: spanProcessor)
        .build()
)

Ensure to replace <SIGNOZ_INGESTION_KEY>, <PORT>, and <SIGNOZ_INGESTION_URL> with your actual SigNoz ingestion key, Port, and URL, respectively.

You can find your Ingestion Key in the following places:

  • mail which you recieved from SigNoz after signing up.
  • inside settings on SigNoz dashboard

Depending on the choice of your region for SigNoz cloud, the ingest endpoint will vary according to this table.

RegionEndpoint
USingest.us.signoz.cloud:443/v1/traces
INingest.in.signoz.cloud:443/v1/traces
EUingest.eu.signoz.cloud:443/v1/traces

These are the variables you need to replace :

PlaceholderDescription
<SIGNOZ_INGESTION_KEY>Your SigNoz ingestion key
<PORT>Port (default: 443)
<SIGNOZ_INGESTION_URL>URL for SigNoz ingestion

Step 3: Send Telemetry data to SigNoz

To send telemetry data to SigNoz, you can create a function to add spans and data. This is a sample function

let sampleKey = "sampleKey"
let sampleValue = "sampleValue"

func doWork() {
    let childSpan = tracer.spanBuilder(spanName: "doWork").setSpanKind(spanKind: .client).startSpan()
    childSpan.setAttribute(key: sampleKey, value: sampleValue)
    Thread.sleep(forTimeInterval: Double.random(in: 0 ..< 10) / 100)
    childSpan.end()
}

Step 4: Run app

Execute your application by issuing the following command in terminal:

swift run

Send traces via OTel Collector binary

Step 1 : Install OTel Collector OTel Collector binary helps to collect logs, hostmetrics, resource and infra attributes. It is recommended to install Otel Collector binary to collect and send traces to SigNoz cloud. You can correlate signals and have rich contextual data through this way.

📝 Note

You can find instructions to install OTel Collector binary here in your VM. Once you are done setting up your OTel Collector binary, you can follow the below steps for instrumenting your Swift application.

Step 2 : Instrument your application with OpenTelemetry

To configure your Swift application to send traces to OpenTelemetry you need to install opentelemetry-swift and grpc-swift as dependency in your project.

For that, paste the following inside Package.swift of your project.

 dependencies: [
        .package(url: "https://github.com/open-telemetry/opentelemetry-swift.git", .upToNextMajor(from: "1.9.1")),
        .package(url: "https://github.com/grpc/grpc-swift", from: "1.15.0"),
    ],
    targets: [
        .executableTarget(
            name: "<NAME_OF_APP>",
            dependencies: [
                .product(name: "OpenTelemetryApi", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift"),
                .product(name: "StdoutExporter", package: "opentelemetry-swift"),
                .product(name: "ResourceExtension", package: "opentelemetry-swift"),
                .product(name: "ZipkinExporter", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetryProtocolExporter", package: "opentelemetry-swift"),
                .product(name: "SignPostIntegration", package: "opentelemetry-swift"),
                .product(name: "GRPC", package: "grpc-swift")
            ],
            path: "."
        )
    ]

Replace NAME_OF_APP with the name of app, you will see this name in SigNoz Services section.

You also need to add the following imports to use the methods and functions from the packages/dependencies which you just imported in Package.swift file.

import Foundation
import GRPC
import NIO
import NIOSSL
import OpenTelemetryApi
import OpenTelemetryProtocolExporterCommon
import OpenTelemetryProtocolExporterGrpc
import OpenTelemetrySdk
import ResourceExtension
import SignPostIntegration
import StdoutExporter
import ZipkinExporter

Step 3: Initialize the tracer

Add these statements to initialize tracer in the main.swift file inside the main function or you can create another function for initializing the tracer and call it in some other block of code.

var resources = DefaultResources().get()

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

let otlpConfiguration: OtlpConfiguration = OtlpConfiguration(timeout: TimeInterval(10), headers: [("signoz-access-token", "<SIGNOZ_INGESTION_KEY>")])

let grpcChannel = ClientConnection.usingPlatformAppropriateTLS(for: MultiThreadedEventLoopGroup(numberOfThreads:1)).connect(host: "http://localhost", port: 4317)

let otlpTraceExporter = OtlpTraceExporter(channel: grpcChannel,
                                      config: otlpConfiguration)
let stdoutExporter = StdoutExporter()
let spanExporter = MultiSpanExporter(spanExporters: [otlpTraceExporter, stdoutExporter])

let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
OpenTelemetry.registerTracerProvider(tracerProvider:
    TracerProviderBuilder()
        .add(spanProcessor: spanProcessor)
        .build()
)

let tracer = OpenTelemetry.instance.tracerProvider.get(instrumentationName: instrumentationScopeName, instrumentationVersion: instrumentationScopeVersion)

Ensure to replace <SIGNOZ_INGESTION_KEY> with your actual SigNoz ingestion key.

Step 4: Send Telemetry data to SigNoz

To send telemetry data to SigNoz, you can create a function to add spans and data. This is a sample function

let sampleKey = "sampleKey"
let sampleValue = "sampleValue"

func doWork() {
    let childSpan = tracer.spanBuilder(spanName: "doWork").setSpanKind(spanKind: .client).startSpan()
    childSpan.setAttribute(key: sampleKey, value: sampleValue)
    Thread.sleep(forTimeInterval: Double.random(in: 0 ..< 10) / 100)
    childSpan.end()
}

Step 5: Run app

Run your app using the below command to send your traces:

swift run

Send Traces to Self-Hosted SigNoz

Step 1 : Instrument your application with OpenTelemetry

To configure your Swift application to send traces to OpenTelemetry you need to install opentelemetry-swift and grpc-swift as dependency in your project.

For that, paste the following inside Package.swift of your project.

 dependencies: [
        .package(url: "https://github.com/open-telemetry/opentelemetry-swift.git", .upToNextMajor(from: "1.9.1")),
        .package(url: "https://github.com/grpc/grpc-swift", from: "1.15.0"),
    ],
    targets: [
        .executableTarget(
            name: "<NAME_OF_APP>",
            dependencies: [
                .product(name: "OpenTelemetryApi", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift"),
                .product(name: "StdoutExporter", package: "opentelemetry-swift"),
                .product(name: "ResourceExtension", package: "opentelemetry-swift"),
                .product(name: "ZipkinExporter", package: "opentelemetry-swift"),
                .product(name: "OpenTelemetryProtocolExporter", package: "opentelemetry-swift"),
                .product(name: "SignPostIntegration", package: "opentelemetry-swift"),
                .product(name: "GRPC", package: "grpc-swift")
            ],
            path: "."
        )
    ]

Replace NAME_OF_APP with the name of app, you will see this name in SigNoz Services section.

You also need to add the following imports to use the methods and functions from the packages/dependencies which you just imported in Package.swift file.

import Foundation
import GRPC
import NIO
import NIOSSL
import OpenTelemetryApi
import OpenTelemetryProtocolExporterCommon
import OpenTelemetryProtocolExporterGrpc
import OpenTelemetrySdk
import ResourceExtension
import SignPostIntegration
import StdoutExporter
import ZipkinExporter

Step 2: Initialize the tracer

To enable tracing and send traces to the SigNoz cloud, you need to initialize the tracer, to do that insert the following code snippet into your main.swift file

var resources = DefaultResources().get()

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

let otlpConfiguration: OtlpConfiguration = OtlpConfiguration(timeout: TimeInterval(10))

let grpcChannel = ClientConnection.usingPlatformAppropriateTLS(for: MultiThreadedEventLoopGroup(numberOfThreads:1)).connect(host: <SELF_HOSTED_SIGNOZ_URL>, port: <PORT>)

let otlpTraceExporter = OtlpTraceExporter(channel: grpcChannel,
                                      config: otlpConfiguration)
let stdoutExporter = StdoutExporter()

let spanExporter = MultiSpanExporter(spanExporters: [otlpTraceExporter, stdoutExporter])

let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
OpenTelemetry.registerTracerProvider(tracerProvider:
    TracerProviderBuilder()
        .add(spanProcessor: spanProcessor)
        .build()
)

| Placeholder | Description | |----------------------------|---------------------------------------------| | | <PORT> | Port exposed by Self-Hosted | | <SELF_HOSTED_SIGNOZ_URL> | URL for Self-Hosted SigNoz |

Step 3: Send Telemetry data to SigNoz

To send telemetry data to SigNoz, you can create a function to add spans and data. This is a sample function

let sampleKey = "sampleKey"
let sampleValue = "sampleValue"

func doWork() {
    let childSpan = tracer.spanBuilder(spanName: "doWork").setSpanKind(spanKind: .client).startSpan()
    childSpan.setAttribute(key: sampleKey, value: sampleValue)
    Thread.sleep(forTimeInterval: Double.random(in: 0 ..< 10) / 100)
    childSpan.end()
}

Step 4: Run app

Execute your application by issuing the following command in terminal:

swift run

Sample Swift Application

We have included a sample Swift application at Sample swift App Github Repo,

Frequently Asked Questions

  1. How to find what to use in IP of SigNoz if I have installed SigNoz in Kubernetes cluster?

    Based on where you have installed your application and where you have installed SigNoz, you need to find the right value for this. Please use this grid to find the value you should use for IP of SigNoz

  2. I am sending data from my application to SigNoz, but I don't see any events or graphs in the SigNoz dashboard. What should I do?

    This could be because of one of the following reasons:

    1. Your application is generating telemetry data, but not able to connect with SigNoz installation

      Please use this troubleshooting guide to find if your application is able to access SigNoz installation and send data to it.

    2. Your application is not actually generating telemetry data

      Please check if the application is generating telemetry data first. You can use Console Exporter to just print your telemetry data in console first. Join our Slack Community if you need help on how to export your telemetry data in console

    3. Your SigNoz installation is not running or behind a firewall

      Please double check if the pods in SigNoz installation are running fine. docker ps or kubectl get pods -n platform are your friends for this.

What Cloud Endpoint Should I Use?

The primary method for sending data to SigNoz Cloud is through OTLP exporters. You can either send the data directly from your application using the exporters available in SDKs/language agents or send the data to a collector agent, which batches/enriches telemetry and sends it to the Cloud.

My Collector Sends Data to SigNoz Cloud

Using gRPC Exporter

The endpoint should be ingest.{region}.signoz.cloud:443, where {region} should be replaced with in, us, or eu. Note that the exporter endpoint doesn't require a scheme for the gRPC exporter in the collector.

# Sample config with `us` region
exporters:
    otlp:
        endpoint: "ingest.us.signoz.cloud:443"
        tls:
            insecure: false
        headers:
            "signoz-access-token": "<SIGNOZ_INGESTION_KEY>"

Using HTTP Exporter

The endpoint should be https://ingest.{region}.signoz.cloud:443, where {region} should be replaced with in, us, or eu. Note that the endpoint includes the scheme https for the HTTP exporter in the collector.

# Sample config with `us` region
exporters:
    otlphttp:
        endpoint: "https://ingest.us.signoz.cloud:443"
        tls:
            insecure: false
        headers:
            "signoz-access-token": "<SIGNOZ_INGESTION_KEY>"

My Application Sends Data to SigNoz Cloud

The endpoint should be configured either with environment variables or in the SDK setup code.

Using Environment Variables

Using gRPC Exporter

Examples with us region

  • OTEL_EXPORTER_OTLP_PROTOCOL=grpc OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.us.signoz.cloud:443 OTEL_EXPORTER_OTLP_HEADERS=signoz-access-token=<SIGNOZ_INGESTION_KEY>
Using HTTP Exporter
  • OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.us.signoz.cloud:443 OTEL_EXPORTER_OTLP_HEADERS=signoz-access-token=<SIGNOZ_INGESTION_KEY>

Configuring Endpoint in Code

Please refer to the agent documentation.

Sending Data from a Third-Party Service

The endpoint configuration here depends on the export protocol supported by the third-party service. They may support either gRPC, HTTP, or both. Generally, you will need to adjust the host and port. The host address should be ingest.{region}.signoz.cloud:443, where {region} should be replaced with in, us, or eu, and port 443 should be used.