OpenTelemetry guide for Gin and GORM
Distributed tracingopen in new window allows you to see how a request progresses through different services and systems, timings of each operation, any logs and errors as they occur.
In a distributed environment, tracing also helps you understand relationships and interactions between microservices. Distributed tracing gives an insight into how a particular microservice is performing and how that service affects other microservices.
Using tracing, you can break down requests into . Span is an operation (unit of work) your app performs handling a request, for example, a database query or a network call.
Trace is a tree of spans that shows the path that a request makes through an app. Root span is the first span in a trace.
To learn more about tracing, see Distributed tracing using OpenTelemetryopen in new window.
What is OpenTelemetry?
OpenTelemetryopen in new window is an open source and vendor-neutral API for (including logs and errors) and metricsopen in new window.
OpenTelemetry is available for most programming languages and provides interoperability across different languages and environments.
Creating spans
You can create spans using OpenTelemetry Go APIopen in new window like this:
You can also record and errors:
ctx, span := tracer.Start(ctx, "some-func")
defer span.End()
if span.IsRecording() {
span.SetAttributes(
attribute.Int64("enduser.id", userID),
attribute.String("enduser.email", userEmail),
)
}
if err := someOtherFunc(ctx); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
return nil
}
Uptraceopen in new window is an open source and blazingly fast powered by OpenTelemetry and ClickHouse. It allows you to identify and fix bugs in production faster knowing what conditions lead to which errors
You can install Uptraceopen in new window by downloading a DEB/RPM package or a pre-compiled binary.
Example application
In this tutorial, you will be instrumenting a toy appopen in new window that uses Gin router and GORM database client. You can retrieve the source code with the following command:
cd example/gin-gorm
Configuring OpenTelemetry
Uptrace provides OpenTelemetry Goopen in new window distro that configures OpenTelemetry SDK for you. To install the distro:
go get github.com/uptrace/uptrace-go
Then you need to initialize the distro whenever you app is started:
See for details.
import (
"github.com/gin-gonic/gin"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
)
router := gin.Default()
router.Use(otelgin.Middleware("service-name"))
otelgin instrumentation will save the active spanopen in new window in the Go context.Context
. You can retrieve the context from the http.Request
, extract the span from it, and use the span to record :
func (h *Handler) Index(c *gin.Context) {
ctx := c.Request.Context()
// Extract span from the request context.
span := trace.SpanFromContext(ctx)
// Check if the span was sampled and is recording the data.
if span.IsRecording() {
span.SetAttributes(
attribute.String("string_key", "string_value"),
attribute.Int("int_key", 42),
attribute.StringSlice("string_slice_key", []string{"foo", "bar"}),
)
}
otelgin.HTML(c, http.StatusOK, indexTmpl, gin.H{
"traceURL": otelplay.TraceURL(trace.SpanFromContext(ctx)),
})
}
Instrumenting GORM
You can instrument GORM database client using instrumentation:
import (
"gorm.io/gorm"
)
if err := db.Use(otelgorm.NewPlugin()); err != nil {
panic(err)
}
After the database is instrumented, you should use WithContext
method to propagateopen in new window the active trace context:
Recording logs
You can also record log messages using otelzapopen in new window instrumentation for Zap logging library:
// Create Zap logger.
log := otelzap.New(zap.NewExample())
// Extract the active context from the request.
ctx := c.Request.Context()
// Use the logger and the context to record log messages on the active span.
log.Ctx(ctx).Error("hello from zap",
zap.Error(errors.New("hello world")),
zap.String("foo", "bar"))
// otelzap also supports an alternative syntax.
log.ErrorContext(ctx, "hello from zap",
zap.Error(errors.New("hello world")),
zap.String("foo", "bar"))
}
You can start Uptrace backend with a single command using :
docker-compose up -d
And then start the appopen in new window passing Uptrace DSN as an env variable:
The app should be serving requests on http://localhost:9999
and should render a link to Uptrace UI. After opening the link, you should see this:
What’s next?
Next, you can learn about OpenTelemetry Go APIopen in new window to create your own instrumentations or browse existing provided by the community.