Skip to content

Extracts OpenTelemetry span attributes and baggage members from a struct based on tags.

License

Notifications You must be signed in to change notification settings

remychantenay/otel-tag

Repository files navigation

otel-tag

Simple package that extracts OpenTelemetry span attributes and baggage members from a struct based on tags.

Warning

Please bear in mind that this package does not intend to cater to all use cases and please everyone. The code could also do with some refactoring here and there, but it's doing the job.

Shortcomings

  • Does not support basic type pointers (only struct pointers).

Usage

package main

import (
	"context"

	"go.opentelemetry.io/otel/baggage"
	"go.opentelemetry.io/otel/trace"

	oteltag "github.com/remychantenay/otel-tag"
)

type User struct {
	ID        string `otel:"app.user.id"`
	Username  string `otel:"app.user.username"`
	IsPremium bool   `otel:"app.user.premium"`

	UserDetails UserDetails
}

type UserDetails struct {
	Website string `otel:"app.user.website,omitempty"`
	Bio     string // Not tagged, will be ignored.
}

func main() {
	// Span attributes.
	_, span := tracer.Start(context.Background(), "someOperation",
		trace.WithAttributes(oteltag.SpanAttributes(m)...),
	)
	defer span.End()

	// Baggage Members.
	members := oteltag.BaggageMembers(m)
	bag, _ := baggage.New(members...)
	ctx := baggage.ContextWithBaggage(context.Background(), bag)
}

License

Apache License Version 2.0