Instrument your Go application with OpenTelemetry
This walkthrough shows how to add observability to your Go application using the OpenTelemetry Go libraries and tools.
Feature | Supported |
---|---|
Automatic Instrumentation | Yes |
Automatic OneAgent Ingestion | Yes |
Prerequisites
- Dynatrace version 1.222+
- For tracing, W3C Trace Context is enabled
- From the Dynatrace menu, go to Settings > Preferences > OneAgent features.
- Turn on Send W3C Trace Context HTTP headers.
Choose how to ingest data into Dynatrace
OneAgent currently only ingests traces automatically. If you are recording metrics or logs, choose the OTLP export route.
Apart from the following prerequisites, there are no other steps necessary when using OneAgent to ingest Go OpenTelemetry data.
Prerequisites
- OneAgent version 1.207+
Traces-only data
- OpenTelemetry Go Instrumentation agent support is enabled
- From the Dynatrace menu, go to Settings > Preferences > OneAgent features.
- Find and turn on OpenTelemetry (Go).
Choose how you want to instrument your application
OpenTelemetry supports on Go automatic and manual instrumentation, or a combination of both.
It's a good idea to start with automatic instrumentation and add manual instrumentation if the automatic approach doesn't work or doesn't provide enough information.
Initialize OpenTelemetry
The initialization of OpenTelemetry varies, depending on whether you use OneAgent to send data to Dynatrace or perform an OTLP export.
-
Run the following command to install the OpenTelemetry SDK.
1go get go.opentelemetry.io/otel/sdk2go get go.opentelemetry.io/otel/sdk/resource -
Add the following import statements.
1import (2 "context"3 "go.opentelemetry.io/otel"4 "go.opentelemetry.io/otel/attribute"5 "go.opentelemetry.io/otel/propagation"6 sdktrace "go.opentelemetry.io/otel/sdk/trace"7 "log"8) -
Add the following code to your
main
function, to initialize OpenTelemetry.1otel.SetTracerProvider(sdktrace.NewTracerProvider())2otel.SetTextMapPropagator(propagation.TraceContext{})
Automatically instrument your application optional
-
Browse the OpenTelemetry registry and pick the instrumentation libraries matching your application libraries.
-
Install the applicable support libraries using
go get
.1go get go.opentelemetry.io/contrib/instrumentation/[PACKAGE_DETAILS] -
Add the package to your import statements.
1import (2 "go.opentelemetry.io/[PACKAGE]"3) -
Wrap your existing code with calls to the support libraries.
Example for net/http
-
Install the instrumentation library for
net/http
. -
Add the package to your import statements.
1import (2 // other packages3 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"4) -
Wrap your HTTP handler function.
1handler := http.HandlerFunc(httpHandler)2wrappedHandler := otelhttp.NewHandler(handler, "my-span") //TODO Replace with the name of your span34//Use the wrappedHandler with your handle5http.Handle("/", wrappedHandler)
Manually instrument your application
Add tracing
-
You first need to get a tracer object.
1tracer := otel.Tracer("my-tracer") -
With
tracer
, you can now use a span builder to create and start new spans.1_, span := tracer.Start(r.Context(), "Call to /myendpoint")2defer span.End()34span.SetAttributes(attribute.String("http.method", "GET"), attribute.String("net.protocol.version", "1.1"))56// TODO your code goes hereIn the code above, we:
Create a new span and name it "Call to /myendpoint"
- Schedule a deferred call to
End()
, to ensure the span is properly closed when the function returns - Add two attributes, following the semantic naming convention, specific to the action of this span: information on the HTTP method and version
- Add a
TODO
in place of the eventual business logic
Collect metrics
-
Obtain a meter object.
1meter := otel.Meter("my-meter") -
With
meter
, we can now create individual instruments, such as a counter.1requestCounter, _ := meter.Int64Counter("request_counter") -
Now we can invoke the
Add()
method ofrequestCounter
to record new values with the counter.1requestCounter.Add(context.Background(), 1)
Connect logs
OpenTelemetry logging is currently not yet available for Go and is still under development.
Ensure context propagation optional
Context propagation is particularly important when network calls (for example, REST) are involved.
Extracting the context when receiving a request
In the following example, we assume that we have received a network call via the net/http
library and its Request
type.
To obtain a handle to the original context (which was provided by the calling service), we pass the HTTP header object (r.Header
) to the Extract
function of the global propagator singleton, which instantiates that context and returns in parentCtx
. This allows us to continue the previous trace with our own spans.
1func httpHandler(w http.ResponseWriter, r *http.Request) {2 parentCtx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))34 tracer := otel.Tracer("my-tracer")5 ctx, span := tracer.Start(6 parentCtx,7 "manual-server", //TODO Replace with the name of your span8 trace.WithAttributes(9 attribute.String("my-key-1", "my-value-1"), //TODO Add attributes10 ),11 )12 defer span.End()1314 //TODO your code goes here15}
Injecting the context when sending requests
In the following example, we set up a new instance of Request
and pass the object to the Inject
call of the global propagator singleton. This adds the necessary HTTP headers to the request object, which we eventually pass to Do
to execute the network request.
1client := http.Client{}23req, err := http.NewRequest("<method>", "<url>", <body>)4if err != nil {5 // TODO handle error6}78//Method to inject the current context in the request headers9otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))1011client.Do(req) // Your call goes here
Configure data capture to meet privacy requirements optional
While Dynatrace automatically captures all OpenTelemetry attributes, only attribute values specified in the allowlist are stored and displayed in the Dynatrace web UI. This prevents accidental storage of personal data, so you can meet your privacy requirements and control the amount of monitoring data stored.
To view your custom attributes, you need to allow them in the Dynatrace web UI first. To learn how to configure attribute storage and masking, see Attribute redaction.
Verify data ingestion into Dynatrace
Once you have finished the instrumentation of your application, perform a couple of test actions to create and send demo traces, metrics, and logs and verify that they were correctly ingested into Dynatrace.
To do that for traces, in the Dynatrace menu, go to Distributed traces and select the Ingested traces tab. If you use OneAgent, select PurePaths instead.
Metrics and logs can be found under their respective entries at Observe and explore.