Todos os produtos
Search
Central de documentação

Managed Service for OpenTelemetry:Usar o Managed Service for OpenTelemetry para relatar dados de aplicativos Swift

Última atualização: Jul 05, 2026

Após usar o Managed Service for OpenTelemetry da Alibaba Cloud para instrumentar um aplicativo e relatar os dados de rastreamento ao Managed Service for OpenTelemetry, o monitoramento do aplicativo é iniciado. Você pode visualizar dados como topologia do aplicativo, traces, transações anômalas, transações lentas e análise de SQL. Este tópico descreve como usar o Managed Service for OpenTelemetry para instrumentar um aplicativo Swift e relatar seus dados de rastreamento.

Antes de começar

Para obter o endpoint do Managed Service for OpenTelemetry, execute as etapas a seguir:

  1. Faça login no console do Managed Service for OpenTelemetry.

  2. No painel de navegação à esquerda, clique em Cluster Configurations. Na página exibida, clique em a aba Access point information.

  3. Na barra de navegação superior, selecione uma região. Na seção Cluster Information, ative a opção Show Token.

  4. Defina o parâmetro Client como OpenTelemetry.

    Obtenha o endpoint do Managed Service for OpenTelemetry na coluna Related Information da tabela na parte inferior.OT接入点信息

    Nota

    Se o seu aplicativo estiver implantado em um ambiente de produção da Alibaba Cloud, utilize o endpoint da Virtual Private Cloud (VPC). Caso contrário, use o endpoint público.

Código de exemplo

Neste exemplo, o Managed Service for OpenTelemetry relata os dados de rastreamento de um aplicativo de linha de comando macOS escrito em Swift. O método apresentado aqui também se aplica a aplicativos iOS.

Baixe o código de exemplo em opentelemetry-swift-demo.

Etapa 1: Crie um aplicativo e adicionar dependências

  1. Selecione o tipo de aplicativo que deseja criar. Por exemplo, escolha macOS > Command Line Tool.

    Command Line Tool

  2. No XCode, escolha File > Add Packages..., insira https://github.com/open-telemetry/opentelemetry-swift na caixa de pesquisa e selecione a versão 1.4.1.

    Nota

    Para mais informações sobre as versões, visite a página do opentelemetry-swift no GitHub.

    opentelemetry-swift

  3. Selecione os pacotes necessários.

    A figura a seguir mostra os pacotes utilizados neste exemplo.Package Products

Etapa 2: Inicializar o OpenTelemetry

  1. Crie um exporter para exportar os dados de monitoramento.

    Escolha um dos métodos a seguir para relatar os dados de rastreamento:

    • Método 1: Relatar dados de rastreamento usando o protocolo gRPC

      • Substitua <gRPC-endpoint> e <gRPC-port> pelo endpoint e número de porta obtidos na seção "Antes de começar" deste tópico. Neste exemplo, utiliza-se host: "http://tracing-analysis-dc-hz.aliyuncs.com", port:8090.

      • Substitua <your-token> pelo token de autenticação obtido na seção "Antes de começar" deste tópico.

      let grpcChannel = ClientConnection(
          configuration: ClientConnection.Configuration.default(
              target: .hostAndPort("<gRPC-endpoint>", 8090), // Specify the endpoint that does not contain the http:// prefix. In this example, tracing-analysis-dc-hz.aliyuncs.com is used.
              eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1)
          )
      )
      
      let otlpGrpcConfiguration = OtlpConfiguration(
          timeout: OtlpConfiguration.DefaultTimeoutInterval,
          headers: [
              ("Authentication","xxxxxx")
          ]
      
      )
      let otlpGrpcTraceExporter = OtlpTraceExporter(channel: grpcChannel, config: otlpGrpcConfiguration)
    • Método 2: Relatar dados de rastreamento usando o protocolo HTTP

      Substitua <HTTP-endpoint> pelo endpoint obtido na seção "Antes de começar" deste tópico. Neste exemplo, utiliza-se http://tracing-analysis-dc-hz.aliyuncs.com/adapt_xxxx@xxxx_xxxx@xxxx/api/otlp/traces.

      let url = URL(string: "<HTTP-endpoint>")
      let otlpHttpTraceExporter = OtlpHttpTraceExporter(endpoint: url!)
    • Método 3: Obter dados de rastreamento na linha de comando

      let consoleTraceExporter = StdoutExporter(isDebug: true)
  2. Obtenha o tracer usado para criar um span.

    • Substitua <your-service-name> pelo nome do aplicativo cujos dados você deseja relatar e <your-host-name> pelo nome do host.

    • Substitua <trace-exporter> por valores diferentes conforme o método escolhido para relatar os dados de rastreamento na Etapa 1.

      • Método 1: Substitua <trace-exporter> por otlpGrpcTraceExporter.

      • Método 2: Substitua <trace-exporter> por otlpHttpTraceExporter.

      • Método 3: Substitua <trace-exporter> por consoleTraceExporter.

    // Specify the application name and the hostname.
    let resource = Resource(attributes: [
        ResourceAttributes.serviceName.rawValue: AttributeValue.string("<your-service-name>"),
        ResourceAttributes.hostName.rawValue: AttributeValue.string("<your-host-name>")
    ])
    
    // Configure the TracerProvider.
    OpenTelemetry.registerTracerProvider(tracerProvider: TracerProviderBuilder()
                                         .add(spanProcessor: BatchSpanProcessor(spanExporter: <trace-exporter>)) // Report data to Managed Service for OpenTelemetry.
                                         .with(resource: resource)
                                         .build())
    
    // Obtain the tracer that is used to create a span.
    let tracer = OpenTelemetry.instance.tracerProvider.get(instrumentationName: "instrumentation-library-name", instrumentationVersion: "1.0.0")

Etapa 3: Crie um span para rastrear dados de trace

  1. Crie um span, configure atributos e um evento para ele e obtenha o ID de rastreamento do span.

    let span = tracer.spanBuilder(spanName: "first span").startSpan()
    // Configure attributes.
    span.setAttribute(key: "http.method", value: "GET")
    span.setAttribute(key: "http.url", value: "www.aliyun.com")
    let attributes = [
        "key": AttributeValue.string("value"),
        "result": AttributeValue.int(100)
    ]
    
    // your code...
    
    // Configure an event.
    span.addEvent(name: "computation complete", attributes: attributes)
    
    // Display the trace ID.
    print(span.context.traceId.hexString)
    
    // your code...
    
    // End the current span.
    span.end()
  2. Crie um span aninhado.

    let parentSpan = tracer.spanBuilder(spanName: "parent span").startSpan()
    
    // your code...
    
    let childSpan = tracer.spanBuilder(spanName: "child span").setParent(parentSpan).startSpan()
    
    // your code...
    
    childSpan.end()
    
    // your code...
    
    parentSpan.end()
  3. Inicie o aplicativo.

    Na página Applications do console do Managed Service for OpenTelemetry, clique em o nome do aplicativo. Na página exibida, visualize os dados de rastreamento.

    Faça login no console do ARMS. No painel de navegação à esquerda, escolha Application Monitoring > Applications. Na página Applications, clique em o nome do aplicativo. Na página exibida, visualize os dados de rastreamento.

    Nota

    Se o ícone image aparecer na coluna Language, o aplicativo está conectado ao Application Monitoring. Se um hífen (-) for exibido, o aplicativo está conectado ao Managed Service for OpenTelemetry.

Etapa 4: Conectar o aplicativo cliente e o aplicativo servidor

  1. Altere o formato para transmitir dados de rastreamento no cabeçalho da solicitação HTTP.

    • Protocolos diferentes utilizam cabeçalhos de solicitação HTTP distintos para passar o contexto de rastreamento. Por exemplo, o OpenTelemetry usa o formato W3C Trace Context por padrão, mas suporta outros formatos, enquanto o Zipkin utiliza o formato B3 ou B3 Multi. Para mais detalhes, consulte Configurar formatos de propagação de contexto de rastreamento.

    • Configure o formato de transmissão de dados de rastreamento do aplicativo cliente com base no protocolo utilizado pelo aplicativo servidor. Dessa forma, o aplicativo cliente iOS e o aplicativo servidor poderão se comunicar.

      • Caso o aplicativo servidor utilize o formato W3C Trace Context do OpenTelemetry, não é necessário especificar os parâmetros textPropagators e baggagePropagator para o aplicativo cliente.

      • Se o aplicativo servidor usar o formato B3 ou B3 Multi do Zipkin, defina o parâmetro textPropagators como B3Propagator e o parâmetro baggagePropagator como ZipkinBaggagePropagator no aplicativo cliente.

        // Specify the B3 format to pass trace data. 
        OpenTelemetry.registerPropagators(textPropagators: [B3Propagator()],
                                          baggagePropagator: ZipkinBaggagePropagator())
      • Quando o aplicativo servidor utilizar o protocolo Jaeger, será necessário definir o parâmetro textPropagators como JaegerPropagator e o parâmetro baggagePropagator como JaegerBaggagePropagator no aplicativo cliente.

        // Specify the Jaeger format to pass trace data. 
        OpenTelemetry.registerPropagators(textPropagators: [JaegerPropagator()],
                                          baggagePropagator: JaegerBaggagePropagator())
      • Também é possível especificar múltiplos formatos para a transmissão dos dados de rastreamento.

        // Specify the W3C Trace Context, B3, and Jaeger formats to pass trace data. 
        OpenTelemetry.registerPropagators(textPropagators: [W3CTraceContextPropagator(), 
                                                            B3Propagator(), 
                                                            JaegerPropagator()],
                                          baggagePropagator: W3CBaggagePropagator())
  2. Importe o plug-in URLSessionInstrumentation.

    O URLSessionInstrumentation é um plug-in de instrumentação automática fornecido pelo OpenTelemetry para a classe URLSession. Ele intercepta automaticamente todas as solicitações de rede enviadas pela classe URLSession e cria traces.

    import URLSessionInstrumentation
    
    ...
    let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration())
  3. Utilize a classe URLSession para enviar uma solicitação de acesso ao aplicativo servidor.

    let url = URL(string: "<Server address>")!
    let request = URLRequest(url: url)
    let semaphore = DispatchSemaphore(value: 0)
    
    let task = URLSession.shared.dataTask(with: request) { data, _, _ in
        if let data = data {
            let string = String(decoding: data, as: UTF8.self)
            print(string)
        }
        semaphore.signal()
    }
    task.resume()
    
    semaphore.wait()

    Visualize o código de exemplo completo

    OpenTelemetryUtil.swift

    import Foundation
    
    import GRPC
    import NIO
    import OpenTelemetryApi
    import OpenTelemetrySdk
    import OpenTelemetryProtocolExporter
    import StdoutExporter
    
    class OpenTelemetryUtil {
        
        private static let tracerProvider: TracerProvider = {
            // Report trace data by using the gRPC protocol.
            let grpcChannel = ClientConnection(
                configuration: ClientConnection.Configuration.default(
                    target: .hostAndPort("tracing-analysis-dc-hz.aliyuncs.com", 8090),
                    eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1)
                )
            )
            
    
            let otlpGrpcConfiguration = OtlpConfiguration(
                timeout: OtlpConfiguration.DefaultTimeoutInterval,
                headers: [
                    ("Authentication","${Authentication token}")
                ]
    
            )
            let otlpGrpcTraceExporter = OtlpTraceExporter(channel: grpcChannel, config: otlpGrpcConfiguration)
            let consoleTraceExporter = StdoutExporter(isDebug: true)
            
            // Specify the application name and the hostname.
            let resource = Resource(attributes: [
                ResourceAttributes.serviceName.rawValue: AttributeValue.string("otel-swift-demo-grpc"),
                ResourceAttributes.hostName.rawValue: AttributeValue.string("adam.mac")
            ])
    
            let tracerProvider = TracerProviderBuilder()
                .add(spanProcessor: BatchSpanProcessor(spanExporter: otlpGrpcTraceExporter))
    //            .add(spanProcessor: BatchSpanProcessor(spanExporter: consoleTraceExporter)) // Display trace data in the console, which is used for debugging.
                .with(resource: resource)
                .build()
            
            
            // Configure the TracerProvider.
            OpenTelemetry.registerTracerProvider(tracerProvider: tracerProvider)
            // Modify the format to pass trace data.
            OpenTelemetry.registerPropagators(textPropagators: [W3CTraceContextPropagator(),
                                                                B3Propagator(),
                                                                JaegerPropagator()],
                                              baggagePropagator: W3CBaggagePropagator())
            
            return tracerProvider
            
        }()
        
        
        // Obtain the tracer that is used to create a span.
        static func getTracer(name: String, version: String) -> Tracer {
            return tracerProvider.get(instrumentationName: name, instrumentationVersion: version)
        }
    
    }
    

    main.swift

    import Foundation
    
    import OpenTelemetryApi
    import OpenTelemetrySdk
    // Perform automatic instrumentation on network requests.
    import URLSessionInstrumentation
    
    let tracer = OpenTelemetryUtil.getTracer(name: "ios-demo", version: "1.0.0")
    
    // Create a nested span.
    let parentSpan = tracer.spanBuilder(spanName: "parent span").startSpan()
    
    let childSpan = tracer.spanBuilder(spanName: "child span").setParent(parentSpan).startSpan()
    
    // Configure attributes.
    childSpan.setAttribute(key: "http.method", value: "GET")
    childSpan.setAttribute(key: "http.url", value: "www.aliyun.com")
    let attributes = [
        "stringKey": AttributeValue.string("value"),
        "intKey": AttributeValue.int(100)
    ]
    // Configure an event.
    childSpan.addEvent(name: "event", attributes: attributes)
    // Display the trace ID.
    print(childSpan.context.traceId.hexString)
    
    // Send a network request to access the server application.
    let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration())
    
    let url = URL(string: "${Server address}")!
    let request = URLRequest(url: url)
    let semaphore = DispatchSemaphore(value: 0)
    
    let task = URLSession.shared.dataTask(with: request) { data, _, _ in
        if let data = data {
            let string = String(decoding: data, as: UTF8.self)
            print(string)
        }
        semaphore.signal()
    }
    task.resume()
    
    semaphore.wait()
    
    // Manually end the created span.
    childSpan.end()
    parentSpan.end()
    
    sleep(60)
    
    print("end")
    
  4. Inicie o aplicativo e visualize o rastreamento entre o aplicativo cliente e o servidor na página Trace Explorer.

    A figura a seguir mostra um exemplo. Nele, HTTP GET representa um aplicativo iOS e zipkin-demo-server é o aplicativo servidor.

    image