otelgin

package module
v0.63.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2025 License: Apache-2.0, BSD-3-Clause Imports: 13 Imported by: 597

Documentation

Overview

Package otelgin instruments the github.com/gin-gonic/gin package.

Currently there are two ways the code can be instrumented. One is instrumenting the routing of a received message (the Middleware function) and instrumenting the response generation through template evaluation (the HTML function).

Example
package main

import (
	"context"
	"html/template"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	oteltrace "go.opentelemetry.io/otel/trace"

	"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
)

var tracer = otel.Tracer("gin-server")

func main() {
	tp, err := initTracer()
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := tp.Shutdown(context.Background()); err != nil {
			log.Printf("Error shutting down tracer provider: %v", err)
		}
	}()
	r := gin.New()
	r.Use(otelgin.Middleware("my-server"))
	tmplName := "user"
	tmplStr := "user {{ .name }} (id {{ .id }})\n"
	tmpl := template.Must(template.New(tmplName).Parse(tmplStr))
	r.SetHTMLTemplate(tmpl)
	r.GET("/users/:id", func(c *gin.Context) {
		id := c.Param("id")
		name := getUser(c, id)
		otelgin.HTML(c, http.StatusOK, tmplName, gin.H{
			"name": name,
			"id":   id,
		})
	})
	_ = r.Run(":8080")
}

func initTracer() (*sdktrace.TracerProvider, error) {
	exporter, err := stdout.New(stdout.WithPrettyPrint())
	if err != nil {
		return nil, err
	}
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(exporter),
	)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
	return tp, nil
}

func getUser(c *gin.Context, id string) string {
	// Pass the built-in `context.Context` object from http.Request to OpenTelemetry APIs
	// where required. It is available from gin.Context.Request.Context()
	_, span := tracer.Start(c.Request.Context(), "getUser", oteltrace.WithAttributes(attribute.String("id", id)))
	defer span.End()
	if id == "123" {
		return "otelgin tester"
	}
	return "unknown"
}

Index

Examples

Constants

View Source
const (

	// ScopeName is the instrumentation scope name.
	ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
)

Variables

This section is empty.

Functions

func HTML

func HTML(c *gin.Context, code int, name string, obj any)

HTML will trace the rendering of the template as a child of the span in the given context. This is a replacement for gin.Context.HTML function - it invokes the original function after setting up the span.

func Middleware

func Middleware(service string, opts ...Option) gin.HandlerFunc

Middleware returns middleware that will trace incoming requests. The service parameter should describe the name of the (virtual) server handling the request.

func Version added in v0.24.0

func Version() string

Version is the current release version of the gin instrumentation.

Types

type Filter added in v0.37.0

type Filter func(*http.Request) bool

Filter is a predicate used to determine whether a given http.request should be traced. A Filter must return true if the request should be traced.

type GinFilter added in v0.54.0

type GinFilter func(*gin.Context) bool

GinFilter filters an net/http.Request based on content of a gin.Context.

type GinMetricAttributeFn added in v0.61.0

type GinMetricAttributeFn func(*gin.Context) []attribute.KeyValue

GinMetricAttributeFn is used to extract additional attributes from the gin.Context and return them as a slice of attribute.KeyValue.

type MetricAttributeFn added in v0.60.0

type MetricAttributeFn func(*http.Request) []attribute.KeyValue

MetricAttributeFn is used to extract additional attributes from the http.Request and return them as a slice of attribute.KeyValue.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option specifies instrumentation configuration options.

func WithFilter added in v0.37.0

func WithFilter(f ...Filter) Option

WithFilter adds a filter to the list of filters used by the handler. If any filter indicates to exclude a request then the request will not be traced. All gin and net/http filters must allow a request to be traced for a Span to be created. If no filters are provided then all requests are traced. Filters will be invoked for each processed request, it is advised to make them simple and fast.

func WithGinFilter added in v0.54.0

func WithGinFilter(f ...GinFilter) Option

WithGinFilter adds a gin filter to the list of filters used by the handler.

func WithGinMetricAttributeFn added in v0.61.0

func WithGinMetricAttributeFn(f GinMetricAttributeFn) Option

WithGinMetricAttributeFn specifies a function that extracts additional attributes from the gin.Context and returns them as a slice of attribute.KeyValue.

If attributes are duplicated between this method and `WithMetricAttributeFn`, the attributes in this method will be used.

func WithMeterProvider added in v0.60.0

func WithMeterProvider(mp metric.MeterProvider) Option

WithMeterProvider specifies a meter provider to use for creating a meter. If none is specified, the global provider is used.

func WithMetricAttributeFn added in v0.60.0

func WithMetricAttributeFn(f MetricAttributeFn) Option

WithMetricAttributeFn specifies a function that extracts additional attributes from the http.Request and returns them as a slice of attribute.KeyValue.

If attributes are duplicated between this method and `WithGinMetricAttributeFn`, the attributes in this method will be overridden.

func WithPropagators

func WithPropagators(propagators propagation.TextMapPropagator) Option

WithPropagators specifies propagators to use for extracting information from the HTTP requests. If none are specified, global ones will be used.

func WithSpanNameFormatter added in v0.40.0

func WithSpanNameFormatter(f SpanNameFormatter) Option

WithSpanNameFormatter takes a function that will be called on every request and the returned string will become the Span Name.

func WithSpanStartOptions added in v0.61.0

func WithSpanStartOptions(opts ...oteltrace.SpanStartOption) Option

WithSpanStartOptions configures an additional set of trace.SpanStartOptions, which are applied to each new span.

func WithTracerProvider

func WithTracerProvider(provider oteltrace.TracerProvider) Option

WithTracerProvider specifies a tracer provider to use for creating a tracer. If none is specified, the global provider is used.

type SpanNameFormatter added in v0.40.0

type SpanNameFormatter func(*gin.Context) string

SpanNameFormatter is used by `WithSpanNameFormatter` to customize the request's span name.

Directories

Path Synopsis
example module
internal
semconv
Package semconv provides OpenTelemetry semantic convention types and functionality.
Package semconv provides OpenTelemetry semantic convention types and functionality.
semconv/test module
test module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL