otelfiber

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 14 Imported by: 7

README


id: otelfiber

Otelfiber

Release Discord Test Security Linter

OpenTelemetry support for Fiber.

Can be found on OpenTelemetry Registry.

Note: Requires Go 1.19 and above

Install

This middleware supports Fiber v2.

go get -u github.com/gofiber/contrib/otelfiber/v2

Signature

otelfiber.Middleware(opts ...otelfiber.Option) fiber.Handler

Config

You can configure the middleware using functional parameters

Function Argument Type Description Default
WithNext func(*fiber.Ctx) bool Define a function to skip this middleware when returned true . nil
WithTracerProvider oteltrace.TracerProvider Specifies a tracer provider to use for creating a tracer. nil - the global tracer provider is used
WithMeterProvider otelmetric.MeterProvider Specifies a meter provider to use for reporting. nil - the global meter provider is used
WithPort int Specifies the value to use when setting the net.host.port attribute on metrics/spans. Defaults to (80 for http, 443 for https)
WithPropagators propagation.TextMapPropagator Specifies propagators to use for extracting information from the HTTP requests. If none are specified, global ones will be used
WithServerName string Specifies the value to use when setting the http.server_name attribute on metrics/spans. -
WithSpanNameFormatter func(*fiber.Ctx) string Takes a function that will be called on every request and the returned string will become the span Name. Default formatter returns the route pathRaw
WithCustomAttributes func(*fiber.Ctx) []attribute.KeyValue Define a function to add custom attributes to the span. nil
WithCollectClientIP bool Specifies whether to collect the client's IP address from the request. true

Usage

Please refer to example

Example

package main

import (
	"context"
	"errors"
	"log"

	"go.opentelemetry.io/otel/sdk/resource"

	"github.com/gofiber/fiber/v2"

	"github.com/gofiber/contrib/otelfiber"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"

	//"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
	oteltrace "go.opentelemetry.io/otel/trace"
)

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

func main() {
	tp := initTracer()
	defer func() {
		if err := tp.Shutdown(context.Background()); err != nil {
			log.Printf("Error shutting down tracer provider: %v", err)
		}
	}()

	app := fiber.New()

	app.Use(otelfiber.Middleware())

	app.Get("/error", func(ctx *fiber.Ctx) error {
		return errors.New("abc")
	})

	app.Get("/users/:id", func(c *fiber.Ctx) error {
		id := c.Params("id")
		name := getUser(c.UserContext(), id)
		return c.JSON(fiber.Map{"id": id, name: name})
	})

	log.Fatal(app.Listen(":3000"))
}

func initTracer() *sdktrace.TracerProvider {
	exporter, err := stdout.New(stdout.WithPrettyPrint())
	if err != nil {
		log.Fatal(err)
	}
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(exporter),
		sdktrace.WithResource(
			resource.NewWithAttributes(
				semconv.SchemaURL,
				semconv.ServiceNameKey.String("my-service"),
			)),
	)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
	return tp
}

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 "otelfiber tester"
	}
	return "unknown"
}

Documentation

Overview

Package otelfiber instruments the github.com/gofiber/fiber package. (https://github.com/gofiber/fiber).

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

Index

Constants

View Source
const (
	MetricNameHttpServerDuration       = "http.server.duration"
	MetricNameHttpServerRequestSize    = "http.server.request.size"
	MetricNameHttpServerResponseSize   = "http.server.response.size"
	MetricNameHttpServerActiveRequests = "http.server.active_requests"

	// Unit constants for deprecated metric units
	UnitDimensionless = "1"
	UnitBytes         = "By"
	UnitMilliseconds  = "ms"
)

Variables

This section is empty.

Functions

func HasBasicAuth

func HasBasicAuth(auth string) (string, bool)

func Middleware

func Middleware(opts ...Option) fiber.Handler

Middleware returns fiber handler which will trace incoming requests.

Types

type Option

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

Option specifies instrumentation configuration options.

func WithCollectClientIP added in v2.1.0

func WithCollectClientIP(collect bool) Option

WithCollectClientIP specifies whether to collect the client's IP address from the request. This is enabled by default.

func WithCustomAttributes

func WithCustomAttributes(f func(ctx *fiber.Ctx) []attribute.KeyValue) Option

WithCustomAttributes specifies a function that will be called on every request and the returned attributes will be added to the span.

func WithMeterProvider

func WithMeterProvider(provider otelmetric.MeterProvider) Option

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

func WithNext

func WithNext(f func(ctx *fiber.Ctx) bool) Option

WithNext takes a function that will be called on every request, the middleware will be skipped if returning true

func WithPort

func WithPort(port int) Option

WithPort specifies the value to use when setting the `net.host.port` attribute on metrics/spans. Attribute is "Conditionally Required: If not default (`80` for `http`, `443` for `https`).

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 WithServerName

func WithServerName(serverName string) Option

WithServerName specifies the value to use when setting the `http.server_name` attribute on metrics/spans.

func WithSpanNameFormatter

func WithSpanNameFormatter(f func(ctx *fiber.Ctx) string) Option

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

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.

Jump to

Keyboard shortcuts

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