Todos os produtos
Search
Central de documentação

Managed Service for OpenTelemetry:Report Go trace data through SkyWalking

Última atualização: Jul 05, 2026

Instrumente sua aplicação Go com um agente SkyWalking para enviar rastros distribuídos ao console do Managed Service for OpenTelemetry. Após o recebimento dos rastros, explore a topologia da aplicação, rastros, transações lentas, análise de erros e análises de SQL.

Dois agentes SkyWalking oferecem suporte ao Go:

Agente

Estilo de instrumentação

Status

skywalking-go (recomendado)

Não intrusivo — injeção em tempo de compilação via -toolexec

Mantido ativamente

Go2Sky (legado)

Intrusivo — requer hooks por plug-in no código-fonte

Descontinuado, sem manutenção

Use o skywalking-go, a menos que seu projeto já dependa do Go2Sky. O SkyWalking migra gradualmente os plug-ins do Go2Sky para o agente skywalking-go, que também adiciona suporte ao framework gRPC.

Nota

O ARMS também fornece um agente proprietário para Go, com suporte comercial. Ele permite instrumentação não intrusiva com mais recursos e maior estabilidade.

Enviar rastros com o agente skywalking-go

As etapas a seguir descrevem como compilar o agente skywalking-go, configurá-lo para o Managed Service for OpenTelemetry e recompilar seu projeto Go com instrumentação em tempo de compilação.

Etapa 1: Obter o endpoint do SkyWalking

  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 na aba Access point information.

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

  4. Defina o parâmetro Client como SkyWalking.

  5. Copie o endpoint da coluna Related Information.

SkyWalking endpoint information

Nota

Se sua aplicação for executada em um ambiente de produção da Alibaba Cloud, use o endpoint de VPC. Caso contrário, use o endpoint público.

Etapa 2: Compilar o binário do agente

Clone e compile o agente skywalking-go:

git clone https://github.com/apache/skywalking-go.git
cd skywalking-go && make build

A compilação gera um executável no diretório skywalking-go/bin/. O nome do arquivo varia conforme o sistema operacional — por exemplo, skywalking-go-agent--darwin-amd64 no macOS.

Executable files in the skywalking-go/bin directory

Etapa 3: Adicionar o módulo SkyWalking ao projeto

Escolha um dos métodos abaixo:

Opção A — Importar no código

Adicione ao seu pacote principal:

package main

import (
	_ "github.com/apache/skywalking-go"
)

Opção B — Injetar com o binário do agente

skywalking-go/bin/skywalking-go-agent--darwin-amd64 -inject path/to/your-project
Nota

Se o método de injeção falhar, use a Opção A.

Etapa 4: Configurar o agente

Crie um arquivo config.yaml com pelo menos os três parâmetros a seguir:

agent:
  service_name: ${SW_AGENT_NAME:<your-service-name>}

reporter:
  grpc:
    backend_service: ${SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE:<your-skywalking-endpoint>}
    authentication: ${SW_AGENT_REPORTER_GRPC_AUTHENTICATION:<your-auth-token>}

Substitua os placeholders pelos seus valores:

Placeholder

Descrição

Exemplo

<your-service-name>

Nome que identifica sua aplicação no console

my-go-service

<your-skywalking-endpoint>

Endpoint obtido na Etapa 1

xxx.api.aliyuncs.com:11800

<your-auth-token>

Token de autenticação exibido ao lado do endpoint

abcdef123456

Defina esses valores diretamente no arquivo config.yaml (recomendado) ou por variáveis de ambiente:

export SW_AGENT_NAME=my-go-service
export SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE=xxx.api.aliyuncs.com:11800
export SW_AGENT_REPORTER_GRPC_AUTHENTICATION=abcdef123456

Desativar plug-ins específicos

Por padrão, o agente skywalking-go instrumenta todos os plug-ins suportados. Para excluir plug-ins específicos, adicione o parâmetro excluded:

plugin:
  # Disable a single plug-in
  excluded: ${SW_AGENT_PLUGIN_EXCLUDES:sql}

  # Disable multiple plug-ins (comma-separated)
  # excluded: ${SW_AGENT_PLUGIN_EXCLUDES:sql,gorm}

Referência completa do config.yaml

agent:
  # Service name is showed in UI.
  service_name: ${SW_AGENT_NAME:Your_ApplicationName}
  # To obtain the environment variable key for the instance name, if it cannot be obtained, an instance name will be automatically generated.
  instance_env_name: SW_AGENT_INSTANCE_NAME
  # Sampling rate of tracing data, which is a floating-point value that must be between 0 and 1.
  sampler: ${SW_AGENT_SAMPLE:1}
  meter:
    # The interval of collecting metrics, in seconds.
    collect_interval: ${SW_AGENT_METER_COLLECT_INTERVAL:20}

reporter:
  grpc:
    # The gRPC server address of the backend service.
    backend_service: ${SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE:127.0.0.1:11800}
    # The maximum count of segment for reporting tracing data.
    max_send_queue: ${SW_AGENT_REPORTER_GRPC_MAX_SEND_QUEUE:5000}
    # The interval(s) of checking service and backend service
    check_interval: ${SW_AGENT_REPORTER_GRPC_CHECK_INTERVAL:20}
    # The authentication string for communicate with backend.
    authentication: ${SW_AGENT_REPORTER_GRPC_AUTHENTICATION:}
    # The interval(s) of fetching dynamic configuration from backend.
    cds_fetch_interval: ${SW_AGENT_REPORTER_GRPC_CDS_FETCH_INTERVAL:20}
    tls:
      # Whether to enable TLS with backend.
      enable: ${SW_AGENT_REPORTER_GRPC_TLS_ENABLE:false}
      # The file path of ca.crt. The config only works when opening the TLS switch.
      ca_path: ${SW_AGENT_REPORTER_GRPC_TLS_CA_PATH:}
      # The file path of client.pem. The config only works when mTLS.
      client_key_path: ${SW_AGENT_REPORTER_GRPC_TLS_CLIENT_KEY_PATH:}
      # The file path of client.crt. The config only works when mTLS.
      client_cert_chain_path: ${SW_AGENT_REPORTER_GRPC_TLS_CLIENT_CERT_CHAIN_PATH:}
      # Controls whether a client verifies the server's certificate chain and host name.
      insecure_skip_verify: ${SW_AGENT_REPORTER_GRPC_TLS_INSECURE_SKIP_VERIFY:false}

log:
  # The type determines which logging type is currently used by the system.
  # The Go agent wourld use this log type to generate custom logs. It supports: "auto", "logrus", or "zap".
  # auto: Automatically identifies the source of the log.
  #       If logrus is present in the project, it wourld automatically use logrus.
  #       If zap has been initialized in the project, it would use the zap framework.
  #       By default, it would use std errors to output log content.
  # logrus: Specifies that the Agent should use the logrus framework.
  # zap: Specifies that the Agent should use the zap framework.
  # The system must have already been initialized through methods such as "zap.New", "zap.NewProduction", etc.
  type: ${SW_AGENT_LOG_TYPE:auto}
  tracing:
    # Whether to automatically integrate Tracing information into the logs.
    enable: ${SW_AGENT_LOG_TRACING_ENABLE:true}
    # If tracing information is enabled, the tracing information would be stored in the current Key in each log.
    key: ${SW_AGENT_LOG_TRACING_KEY:SW_CTX}
  reporter:
    # Whether to upload logs to the backend.
    enable: ${SW_AGENT_LOG_REPORTER_ENABLE:true}
    # The fields name list that needs to added to the label of the log.(multiple split by ",")
    label_keys: ${SW_AGENT_LOG_REPORTER_LABEL_KEYS:}

plugin:
  # List the names of excluded plugins, multiple plugin names should be splitted by ","
  # NOTE: This parameter only takes effect during the compilation phase.
  excluded: ${SW_AGENT_PLUGIN_EXCLUDES:}
  config:
    http:
      # Collect the parameters of the HTTP request on the server side
      server_collect_parameters: ${SW_AGENT_PLUGIN_CONFIG_HTTP_SERVER_COLLECT_PARAMETERS:false}
    mongo:
      # Collect the statement of the MongoDB request
      collect_statement: ${SW_AGENT_PLUGIN_CONFIG_MONGO_COLLECT_STATEMENT:false}
    sql:
      # Collect the parameter of the SQL request
      collect_parameter: ${SW_AGENT_PLUGIN_CONFIG_SQL_COLLECT_PARAMETER:false}

Etapa 5: Recompilar o projeto

Compile com a flag -toolexec apontando para o binário do agente e seu arquivo de configuração:

sudo go build -toolexec "path/to/skywalking-go-agent -config path/to/config.yaml" -a
  • path/to/skywalking-go-agent — caminho absoluto para o executável compilado na Etapa 2

  • path/to/config.yaml — caminho absoluto para o arquivo de configuração criado na Etapa 4

Etapa 6: Iniciar a aplicação e verificar

Execute o binário compilado. O agente instrumenta automaticamente todos os plug-ins suportados e começa a relatar rastros via gRPC.

Após iniciar o projeto, o SkyWalking relata dados ao console do Managed Service for OpenTelemetry.

Referência de variáveis de ambiente

Variável de ambiente

Descrição

Padrão

SW_AGENT_NAME

Nome da aplicação exibido no console

Nenhum

SW_AGENT_INSTANCE_NAME

Nome da instância

Gerado automaticamente

SW_AGENT_SAMPLE

Taxa de amostragem (0 a 1, onde 1 = 100%)

1

SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE

Endpoint gRPC para relatório de rastros

127.0.0.1:11800

SW_AGENT_REPORTER_GRPC_AUTHENTICATION

Token de autenticação

Nenhum

SW_AGENT_PLUGIN_EXCLUDES

Lista separada por vírgulas de plug-ins a desativar

Nenhum

Plug-ins suportados

O agente skywalking-go instrumenta automaticamente as bibliotecas a seguir em tempo de compilação. Não é necessária instalação individual por biblioteca.

Biblioteca

sql

dubbo-go

gear

gin

go-restful

gorm

http

go-kratos v2

logrus

go-micro v3.5.0

mongo

go-resty v2.2.0

zap v1.16.0

Enviar rastros com o agente Go2Sky (legado)

Nota

O SkyWalking descontinuou o Go2Sky. Não aceita mais pull requests nem fornece atualizações. Use o agente skywalking-go para novos projetos.

Etapa 1: Configurar o reporter

Configure o reporter gRPC codificando os parâmetros diretamente ou definindo variáveis de ambiente.

Opção A — Codificar diretamente no projeto

report, err := reporter.NewGRPCReporter(
    "<your-backend-server-address>",
    reporter.WithAuthentication("<your-auth-token>"))

Opção B — Definir variáveis de ambiente

# Permanent -- add to your shell profile
export SW_AGENT_COLLECTOR_BACKEND_SERVICES=<your-collector-address>
export SW_AGENT_AUTHENTICATION=<your-auth-token>

# Then start your application (the agent reads these variables automatically)

Etapa 2: Criar um tracer

ServiceName := "<your-service-name>"
tracer, err := go2sky.NewTracer(ServiceName, go2sky.WithReporter(report))

Etapa 3: Adicionar hooks de plug-in

O Go2Sky exige um hook para cada biblioteca instrumentada. Consulte o repositório go2sky-plugins no GitHub — cada pasta de plug-in contém um README com instruções de integração.

Exemplo — framework gin:

package main

import (
	"log"

	"github.com/SkyAPM/go2sky"
	v3 "github.com/SkyAPM/go2sky-plugins/gin/v3"
	"github.com/SkyAPM/go2sky/reporter"
	"github.com/gin-gonic/gin"
)

func main() {
	// Use gRPC reporter for production
	re, err := reporter.NewLogReporter()
	if err != nil {
		log.Fatalf("new reporter error %v \n", err)
	}
	defer re.Close()

	tracer, err := go2sky.NewTracer("gin-server", go2sky.WithReporter(re))
	if err != nil {
		log.Fatalf("create tracer error %v \n", err)
	}

	gin.SetMode(gin.ReleaseMode)
	r := gin.New()

	// Use go2sky middleware with tracing
	r.Use(v3.Middleware(r, tracer))

	// Add your routes here
}

Etapa 4: Reiniciar a aplicação

Após adicionar os hooks, reinicie sua aplicação. Os rastros começarão a fluir para o console do Managed Service for OpenTelemetry.

Bibliotecas de plug-ins suportadas

Cada plug-in requer instalação separada via go get:

Biblioteca

Comando de instalação

sql

go get -u github.com/SkyAPM/go2sky-plugins/sql

dubbo-go

go get -u github.com/SkyAPM/go2sky-plugins/dubbo-go

gear

go get -u github.com/SkyAPM/go2sky-plugins/gear

gin

go get -u github.com/SkyAPM/go2sky-plugins/gin/v2 ou gin/v3

go-restful

go get -u github.com/SkyAPM/go2sky-plugins/go-restful

gorm

go get -u github.com/SkyAPM/go2sky-plugins/gorm

http

go get -u github.com/SkyAPM/go2sky

go-kratos v2

go get -u github.com/SkyAPM/go2sky-plugins/kratos

logrus

go get -u github.com/SkyAPM/go2sky-plugins/logrus

go-micro v3.5.0

go get -u github.com/SkyAPM/go2sky-plugins/micro

mongo

go get -u github.com/SkyAPM/go2sky-plugins/mongo

go-resty v2.2.0

go get -u github.com/SkyAPM/go2sky-plugins/resty

zap v1.16.0

go get -u github.com/SkyAPM/go2sky-plugins/zap

Referência de variáveis de ambiente

Variável de ambiente

Descrição

Padrão

SW_AGENT_NAME

Nome da aplicação

Nenhum

SW_AGENT_LAYER

Nome da camada da instância

Nenhum

SW_AGENT_INSTANCE_NAME

Nome da instância

Aleatório

SW_AGENT_SAMPLE

Taxa de amostragem (1 = amostragem completa)

1

SW_AGENT_COLLECTOR_BACKEND_SERVICES

Endpoint do servidor para relatório de rastros

Nenhum

SW_AGENT_AUTHENTICATION

Token de autenticação

Nenhum

SW_AGENT_COLLECTOR_HEARTBEAT_PERIOD

Intervalo de heartbeat em segundos

20

SW_AGENT_COLLECTOR_GET_AGENT_DYNAMIC_CONFIG_INTERVAL

Intervalo de busca de configuração dinâmica em segundos

20

SW_AGENT_COLLECTOR_MAX_SEND_QUEUE_SIZE

Tamanho do buffer da fila de spans

30000

SW_AGENT_PROCESS_STATUS_HOOK_ENABLE

Ativar hook de status do processo

false

SW_AGENT_PROCESS_LABELS

Rótulos de processo separados por vírgula

Nenhum

Perguntas frequentes

O que fazer se o comando inject do skywalking-go falhar?

Error when inject fails

Se o método -inject falhar, adicione a importação do SkyWalking diretamente no seu pacote principal:

import _ "github.com/apache/skywalking-go"

Em seguida, recompile com -toolexec conforme descrito na Etapa 5.

Por que o console mostra rastros quebrados em chamadas entre processos com Go2Sky?

O Managed Service for OpenTelemetry correlaciona spans por IDs de rastro transportados nos cabeçalhos HTTP. Se os rastros parecerem desconectados entre serviços, o contexto de rastro não está sendo propagado corretamente.

Para corrigir isso, crie spans de entrada e saída que propaguem o contexto de rastro pelas fronteiras HTTP:

// CreateEntrySpan -- extract trace context from an incoming HTTP request
span, ctx, err := tracer.CreateEntrySpan(r.Context(), "/api/login", func(key string) (string, error) {
    return r.Header.Get(key), nil
})

// CreateExitSpan -- inject trace context into an outgoing HTTP request
span, err := tracer.CreateExitSpan(req.Context(), "/service/validate", "tomcat-service:8080", func(key, value string) error {
    req.Header.Set(key, value)
    return nil
})

Para spans dentro do mesmo processo (sem fronteira de rede), use CreateLocalSpan:

span, ctx, err := tracer.CreateLocalSpan(context.Background())
subSpan, newCtx, err := tracer.CreateLocalSpan(ctx)

Toda chamada HTTP que cruza uma fronteira de processo deve transportar o contexto de rastro. Sem CreateEntrySpan e CreateExitSpan em cada fronteira, o serviço downstream inicia um novo rastro desconectado.

Código de exemplo

Para um exemplo funcional completo, consulte o repositório skywalking-demo no GitHub.

Veja também