otelmux

package module
v0.61.0 Latest Latest
Warning

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

Go to latest
Published: May 22, 2025 License: Apache-2.0 Imports: 12 Imported by: 215

Documentation

Overview

Package otelmux instruments the github.com/gorilla/mux package.

Currently only the routing of a received message can be instrumented. To do it, use the Middleware function.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/mux"

	"go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
	"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"
)

var tracer = otel.Tracer("mux-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 := mux.NewRouter()
	r.Use(otelmux.Middleware("my-server"))
	r.HandleFunc("/users/{id:[0-9]+}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		id := vars["id"]
		name := getUser(r.Context(), id)
		reply := fmt.Sprintf("user %s (id %s)\n", name, id)
		_, _ = w.Write(([]byte)(reply))
	}))
	http.Handle("/", r)
	_ = http.ListenAndServe(":8080", nil) //nolint:gosec // Ignoring G114: Use of net/http serve function that has no support for setting timeouts.
}

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(ctx context.Context, id string) string {
	_, span := tracer.Start(ctx, "getUser", oteltrace.WithAttributes(attribute.String("id", id)))
	defer span.End()
	if id == "123" {
		return "otelmux tester"
	}
	return "unknown"
}

Index

Examples

Constants

View Source
const (
	// ScopeName is the instrumentation scope name.
	ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
)

Variables

This section is empty.

Functions

func Middleware

func Middleware(service string, opts ...Option) mux.MiddlewareFunc

Middleware sets up a handler to start tracing the 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 gorilla/mux instrumentation.

Types

type Filter added in v0.44.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 Option

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

Option specifies instrumentation configuration options.

func WithFilter added in v0.44.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 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 WithMeterProvider added in v0.60.0

func WithMeterProvider(provider metric.MeterProvider) Option

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

func WithMetricAttributesFn added in v0.60.0

func WithMetricAttributesFn(metricAttributesFn func(r *http.Request) []attribute.KeyValue) Option

WithMetricAttributesFn returns an Option to set a function that maps an HTTP request to a slice of attribute.KeyValue. These attributes will be included in metrics for every request.

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 WithPublicEndpoint added in v0.41.1

func WithPublicEndpoint() Option

WithPublicEndpoint configures the Handler to link the span with an incoming span context. If this option is not provided, then the association is a child association instead of a link.

func WithPublicEndpointFn added in v0.41.1

func WithPublicEndpointFn(fn func(*http.Request) bool) Option

WithPublicEndpointFn runs with every request, and allows conditionally configuring the Handler to link the span with an incoming span context. If this option is not provided or returns false, then the association is a child association instead of a link. Note: WithPublicEndpoint takes precedence over WithPublicEndpointFn.

func WithSpanNameFormatter added in v0.38.0

func WithSpanNameFormatter(fn func(routeName string, r *http.Request) string) Option

WithSpanNameFormatter specifies a function to use for generating a custom span name. By default, the route name (path template or regexp) is used. The route name is provided so you can use it in the span name without needing to duplicate the logic for extracting it from the request.

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.

Directories

Path Synopsis
example module
internal
request
Package request provides types and functionality to handle HTTP request handling.
Package request provides types and functionality to handle HTTP request handling.
semconv
Package semconv provides OpenTelemetry semantic convention types and functionality.
Package semconv provides OpenTelemetry semantic convention types and functionality.
semconvutil
Package semconvutil provides OpenTelemetry semantic convention utilities.
Package semconvutil provides OpenTelemetry semantic convention utilities.
semconv/test Module
test module

Jump to

Keyboard shortcuts

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