> ## Documentation Index
> Fetch the complete documentation index at: https://docs.appsignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Instalação do OpenTelemetry para Go

Por favor, siga primeiro o [guia de instalação](/guides/new-application) ao adicionar uma nova aplicação ao AppSignal.

Em seguida, certifique-se de [instalar o collector do AppSignal](/collector/installation) antes de prosseguir.

## Configurar o OpenTelemetry na sua aplicação

O OpenTelemetry precisa ser inicializado antes da sua aplicação iniciar, para garantir que todos os dados de telemetria sejam enviados através do exporter para o AppSignal. Por exemplo, em uma aplicação web, o OpenTelemetry deve ser inicializado antes que as rotas sejam carregadas e o servidor inicie.

Crie uma função `initOpenTelemetry()` como a do exemplo abaixo e adicione-a ao arquivo principal da sua aplicação.

Lembre-se de atualizar os valores abaixo com o nome da sua aplicação no AppSignal, o environment e a push API key, e de substituir o endpoint do exporter pelo endereço do seu collector do AppSignal, se necessário.

<CodeGroup>
  ```go Go theme={null}
  package main

  import (
  	// Import these standard libraries used in the OpenTelemetry configuration
  	"context"
  	"log"
  	"os"
  	"os/exec"
  	"strings"

  	// Import these OpenTelemetry libraries
  	"go.opentelemetry.io/otel"
  	"go.opentelemetry.io/otel/attribute"
  	"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
  	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
  	"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
  	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
  	"go.opentelemetry.io/otel/log/global"
  	"go.opentelemetry.io/otel/propagation"
  	sdklog "go.opentelemetry.io/otel/sdk/log"
  	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
  	sdkresource "go.opentelemetry.io/otel/sdk/resource"
  	sdktrace "go.opentelemetry.io/otel/sdk/trace"
  )

  func initOpenTelemetry() func() {
  	// Replace these values with your AppSignal application name, environment
  	// and push API key. These are used by the resource attributes configuration below.
  	name := "My app"
  	push_api_key := "0000-0000-0000-0000"
  	environment := "development"

  	// Set the name of the service that is being monitored. A common choice is the
  	// name of the framework used. This is used to group traces and metrics in AppSignal.
  	service_name := "My service name"

  	// Replace `localhost:8099` with the address of your AppSignal collector
  	// if it's running on another host.
  	endpoint := "localhost:8099"

  	hostname, err := os.Hostname()
  	if err != nil {
  		hostname = "unknown"
  	}

  	var revision string
  	cmd := exec.Command("git", "rev-parse", "--short", "HEAD")
  	output, err := cmd.Output()
  	if err != nil {
  		revision = "unknown"
  	} else {
  		revision = strings.TrimSpace(string(output))
  	}

  	resource, err := sdkresource.Merge(
  		sdkresource.Default(),
  		sdkresource.NewSchemaless(
  			attribute.String("appsignal.config.name", name),
  			attribute.String("appsignal.config.environment", environment),
  			attribute.String("appsignal.config.push_api_key", push_api_key),
  			attribute.String("appsignal.config.revision", revision),
  			attribute.String("appsignal.config.language_integration", "go"),
  			attribute.String("appsignal.config.app_path", os.Getenv("PWD")),
  			attribute.String("service.name", service_name),
  			attribute.String("host.name", hostname),
  		),
  	)
  	if err != nil {
  		log.Fatalf("Error creating OTLP resource: %v", err)
  	}

  	// Tracing
  	traceClient := otlptracehttp.NewClient(
  		otlptracehttp.WithInsecure(), // Remove if the collector is accessible via HTTPS
  		otlptracehttp.WithEndpoint(endpoint),
  	)

  	traceExporter, err := otlptrace.New(context.Background(), traceClient)
  	if err != nil {
  		log.Fatalf("Error creating OTLP trace exporter: %v", err)
  	}

  	tracerProvider := sdktrace.NewTracerProvider(
  		sdktrace.WithBatcher(traceExporter),
  		sdktrace.WithResource(resource),
  	)

  	otel.SetTracerProvider(tracerProvider)
  	otel.SetTextMapPropagator(
  		propagation.NewCompositeTextMapPropagator(
  			propagation.TraceContext{},
  			propagation.Baggage{},
  		),
  	)

  	// Metrics
  	metricExporter, err := otlpmetrichttp.New(
  		context.Background(),
  		otlpmetrichttp.WithInsecure(), // Remove if the collector is accessible via HTTPS
  		otlpmetrichttp.WithEndpoint(endpoint),
  	)
  	if err != nil {
  		log.Fatalf("creating OTLP metric exporter: %v", err)
  	}

  	meterProvider := sdkmetric.NewMeterProvider(
  		sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExporter)),
  		sdkmetric.WithResource(resource),
  	)
  	otel.SetMeterProvider(meterProvider)

  	// Logs
  	logExporter, err := otlploghttp.New(
  		context.Background(),
  		otlploghttp.WithInsecure(), // Remove if the collector is accessible via HTTPS
  		otlploghttp.WithEndpoint(endpoint),
  	)
  	if err != nil {
  		log.Fatalf("creating OTLP log exporter: %v", err)
  	}

  	loggerProvider := sdklog.NewLoggerProvider(
  		sdklog.WithResource(resource),
  		sdklog.WithProcessor(
  			sdklog.NewBatchProcessor(logExporter),
  		),
  	)
  	global.SetLoggerProvider(loggerProvider)

  	// Cleanup
  	return func() {
  		ctx := context.Background()
  		if err := tracerProvider.Shutdown(ctx); err != nil {
  			log.Println("Error shutting down tracer provider:", err)
  		}
  		if err := meterProvider.Shutdown(ctx); err != nil {
  			log.Println("Error shutting down meter provider:", err)
  		}
  		if err := loggerProvider.Shutdown(ctx); err != nil {
  			log.Println("Error shutting down logger provider:", err)
  		}
  	}
  }

  func main() {
  	cleanup := initOpenTelemetry()
  	defer cleanup()

  	// ... your application's initialization code
  }
  ```
</CodeGroup>

*Se o seu collector estiver acessível via HTTPS, remova as três linhas que contêm a chamada do método `WithInsecure()` no exemplo de configuração.*

Para instalar as bibliotecas do OpenTelemetry importadas no exemplo acima, execute este comando.

<CodeGroup>
  ```sh Shell theme={null}
  go mod tidy
  ```
</CodeGroup>

## Configurar pacotes de instrumentação do OpenTelemetry

A stack do OpenTelemetry não emite nenhum dado por si só. Para instrumentar sua aplicação, instale e configure os pacotes de instrumentação para as bibliotecas e frameworks usados pela sua aplicação. Você pode [encontrar pacotes de instrumentação do OpenTelemetry no registro do OpenTelemetry](https://opentelemetry.io/ecosystem/registry/?s=\&component=instrumentation\&language=go\&flag=all).

Para algumas instrumentações populares do OpenTelemetry, você pode encontrar instruções de configuração específicas nestas páginas:

* [Gin-gonic](/go/instrumentations/gin-gonic)
* [Gorilla mux](/go/instrumentations/gorilla-mux)
* [MongoDB](/go/instrumentations/mongo)
* [Redis](/go/instrumentations/redis)
* [SQL](/go/instrumentations/sql)

## Teste a aplicação!

Agora que todos os componentes estão conectados, inicie sua aplicação e verifique se você vê dados chegando ao AppSignal. Confira especificamente as páginas ["Errors > Issue list"](https://appsignal.com/redirect-to/app?to=exceptions) e ["Performance > Traces"](https://appsignal.com/redirect-to/app?to=performance/traces).

Se, depois de seguir nossas instruções de instalação, você ainda não ver dados no AppSignal, [nos avise](mailto:support@appsignal.com?subject=OpenTelemetry%20beta%20issue) e nós te ajudaremos a finalizar a instalação do OpenTelemetry!

## Adicionar pacotes de instrumentação

O próximo passo é instrumentar pacotes Go como Gin-gonic, Gorilla, etc. Isso fornecerá muito mais dados para realmente investigar a performance das suas aplicações.

Os passos para cada pacote normalmente são os seguintes:

* Instalar o pacote de instrumentação do OpenTelemetry para a biblioteca que você quer instrumentar.
* Seguir as instruções de instalação do pacote de instrumentação.

Para mais informações de instalação e configuração por biblioteca, consulte a [seção de instrumentações do Go][instrumentations].

[Go language]: https://go.dev/

[OpenTelemetry]: https://opentelemetry.io/

[instrumentations]: /go/instrumentations.html
