trace

package module
v0.0.0-...-76fb5b7 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2024 License: MIT Imports: 14 Imported by: 0

README

Trace Module

ci go report codecov PkgGoDev

Tracing module based on OpenTelemetry.

Installation

go get github.com/ankorstore/yokai/modules/trace

Documentation

Configuration

Since The TracerProviderFactory use the resource.Default() by default, you can use:

  • OTEL_SERVICE_NAME env variable to configure your tracing service name
  • OTEL_RESOURCE_ATTRIBUTES env variable to configure your resource attributes
Usage

This module provides a TracerProviderFactory, allowing to set up a TracerProvider easily.

package main

import (
  "github.com/ankorstore/yokai/modules/trace"
  "go.opentelemetry.io/otel/sdk/resource"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create()

  // equivalent to
  tp, _ = trace.NewDefaultTracerProviderFactory().Create(
    trace.Global(true),                                        // set the tracer provider as global
    trace.WithResource(resource.Default()),                    // use the default resource
    trace.WithSampler(trace.NewParentBasedAlwaysOnSampler()),  // use parent based always on sampling
    trace.WithSpanProcessor(trace.NewNoopSpanProcessor()),     // use noop processor (void trace spans)
  )
}

See available factory options.

Context

This module provides the trace.CtxTracerProvider() function that allow to extract the tracer provider from a context.Context.

If no tracer provider is found in context, the global tracer will be used.

Span processors

This modules comes with 4 SpanProcessor ready to use:

  • Noop: to async void traces (default)
  • Stdout: to async print traces to the standard output
  • OtlpGrpc: to async send traces to OTLP/gRPC collectors (ex: Jaeger, Grafana, etc.)
  • Test: to sync store traces in memory (for testing assertions)
Noop span processor
package main

import (
  "context"

  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSpanProcessor(trace.NewNoopSpanProcessor()),
  )

  // voids trace span 
  _, span := tp.Tracer("default").Start(context.Background(), "my span")
  defer span.End()
}
Stdout span processor
package main

import (
  "context"

  "github.com/ankorstore/yokai/modules/trace"
  "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSpanProcessor(trace.NewStdoutSpanProcessor(stdouttrace.WithPrettyPrint())),
  )

  // pretty prints trace span to stdout
  _, span := tp.Tracer("default").Start(context.Background(), "my span")
  defer span.End()
}
OTLP gRPC span processor
package main

import (
  "context"

  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  ctx := context.Background()

  conn, _ := trace.NewOtlpGrpcClientConnection(ctx, "jaeger:4317")
  proc, _ := trace.NewOtlpGrpcSpanProcessor(ctx, conn)

  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSpanProcessor(proc),
  )

  // sends trace span to jaeger:4317
  _, span := tp.Tracer("default").Start(ctx, "my span")
  defer span.End()
}
Test span processor
package main

import (
  "context"
  "fmt"

  "github.com/ankorstore/yokai/modules/trace"
  "github.com/ankorstore/yokai/modules/trace/tracetest"
)

func main() {
  ex := tracetest.NewDefaultTestTraceExporter()

  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSpanProcessor(trace.NewTestSpanProcessor(ex)),
  )

  // sends trace span to test exporter
  _, span := tp.Tracer("default").Start(context.Background(), "my span")
  defer span.End()

  // check
  fmt.Printf("has span: %v", ex.HasSpan("my span")) // has span: true
}

You can use the provided test assertion helpers in your tests:

  • AssertHasTraceSpan: to assert on exact name and exact attributes match
  • AssertHasNotTraceSpan: to assert on exact name and exact attributes non match
  • AssertContainTraceSpan: to assert on exact name and partial attributes match
  • AssertContainNotTraceSpan: to assert on exact name and partial attributes non match
package main_test

import (
  "context"
  "testing"

  "github.com/ankorstore/yokai/modules/trace"
  "github.com/ankorstore/yokai/modules/trace/tracetest"
  "go.opentelemetry.io/otel/attribute"
)

func TestTracer(t *testing.T) {
  ex := tracetest.NewDefaultTestTraceExporter()

  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSpanProcessor(trace.NewTestSpanProcessor(ex)),
  )

  // sends trace span to test exporter
  _, span := tp.Tracer("default").Start(
    context.Background(),
    "my span",
    attribute.String("string attr name", "string attr value"),
    attribute.Int("int attr name", 42),
  )
  span.End()

  // assertion success
  tracetest.AssertHasTraceSpan(
    t,
    ex,
    "my span",
    attribute.String("string attr name", "string attr value"),
    attribute.Int("int attr name", 42),
  )

  // assertion success
  tracetest.AssertHasNotTraceSpan(
    t,
    ex,
    "my span",
    attribute.String("string attr name", "string attr value"),
    attribute.Int("int attr name", 24),
  )

  // assertion success
  tracetest.AssertContainTraceSpan(
    t,
    ex,
    "my span",
    attribute.String("string attr name", "attr value"),
    attribute.Int("int attr name", 42),
  )

  // assertion success
  tracetest.AssertContainNotTraceSpan(
    t,
    ex,
    "my span",
    attribute.String("string attr name", "attr value"),
    attribute.Int("int attr name", 24),
  )
}
Samplers

This modules comes with 6 Samplers ready to use:

  • ParentBasedAlwaysOn: always on depending on parent (default)
  • ParentBasedAlwaysOff: always off depending on parent
  • ParentBasedTraceIdRatio: trace id ratio based depending on parent
  • AlwaysOn: always on
  • AlwaysOff: always off
  • TraceIdRatio: trace id ratio based

Note: parent based samplers returns a composite sampler which behaves differently, based on the parent of the span:

  • if the span has no parent, the embedded sampler is used to make sampling decision
  • if the span has a parent, it depends on whether the parent is remote and whether it is sampled
Parent based always on
package main

import (
  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSampler(trace.NewParentBasedAlwaysOnSampler()),
  )
}
Parent based always off
package main

import (
  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSampler(trace.NewParentBasedAlwaysOffSampler()),
  )
}
Parent based trace id ratio
package main

import (
  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSampler(trace.NewParentBasedTraceIdRatioSampler(0.5)),
  )
}
Always on
package main

import (
  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSampler(trace.NewAlwaysOnSampler()),
  )
}
Always off
package main

import (
  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSampler(trace.NewAlwaysOffSampler()),
  )
}
Trace id ratio
package main

import (
  "github.com/ankorstore/yokai/modules/trace"
)

func main() {
  tp, _ := trace.NewDefaultTracerProviderFactory().Create(
    trace.WithSampler(trace.NewTraceIdRatioSampler(0.5)),
  )
}

Documentation

Index

Constants

View Source
const (
	Stdout   = "stdout"    // processor to send trace spans to the standard output
	OtlpGrpc = "otlp-grpc" // processor to send the trace spans via OTLP/gRPC
	Test     = "test"      // processor to send the trace spans to a test buffer
	Noop     = "noop"      // processor to void the trace spans
)
View Source
const (
	ParentBasedAlwaysOn     = "parent-based-always-on"      // parent based always on sampling
	ParentBasedAlwaysOff    = "parent-based-always-off"     // parent based always off sampling
	ParentBasedTraceIdRatio = "parent-based-trace-id-ratio" // parent based trace id ratio sampling
	AlwaysOn                = "always-on"                   // always on sampling
	AlwaysOff               = "always-off"                  // always off sampling
	TraceIdRatio            = "trace-id-ratio"              // trace id ratio sampling
)
View Source
const DefaultOtlpGrpcTimeout = 5

DefaultOtlpGrpcTimeout is the default timeout in seconds for the OTLP gRPC connection.

Variables

This section is empty.

Functions

func CtxTracerProvider

func CtxTracerProvider(ctx context.Context) trace.TracerProvider

CtxTracerProvider retrieves an OTEL TracerProvider from a provided context (or returns the default one if missing).

func NewAlwaysOffSampler

func NewAlwaysOffSampler() otelsdktrace.Sampler

NewAlwaysOffSampler returns a otelsdktrace.Sampler with always off sampling.

func NewAlwaysOnSampler

func NewAlwaysOnSampler() otelsdktrace.Sampler

NewAlwaysOnSampler returns a otelsdktrace.Sampler with always on sampling.

func NewNoopSpanProcessor

func NewNoopSpanProcessor() trace.SpanProcessor

NewNoopSpanProcessor returns a OTEL SpanProcessor that voids trace spans via an async otelsdktracetest.NoopExporter.

func NewOtlpGrpcClientConnection

func NewOtlpGrpcClientConnection(ctx context.Context, host string, dialOptions ...grpc.DialOption) (*grpc.ClientConn, error)

NewOtlpGrpcClientConnection returns a gRPC connection, and accept a host and a list of DialOption

func NewOtlpGrpcSpanProcessor

func NewOtlpGrpcSpanProcessor(ctx context.Context, conn *grpc.ClientConn) (trace.SpanProcessor, error)

NewOtlpGrpcSpanProcessor returns a OTEL SpanProcessor using an async otlptracegrpc.Exporter.

func NewParentBasedAlwaysOffSampler

func NewParentBasedAlwaysOffSampler() otelsdktrace.Sampler

NewParentBasedAlwaysOffSampler returns a otelsdktrace.Sampler with parent based always off sampling.

func NewParentBasedAlwaysOnSampler

func NewParentBasedAlwaysOnSampler() otelsdktrace.Sampler

NewParentBasedAlwaysOnSampler returns a otelsdktrace.Sampler with parent based always on sampling.

func NewParentBasedTraceIdRatioSampler

func NewParentBasedTraceIdRatioSampler(ratio float64) otelsdktrace.Sampler

NewParentBasedTraceIdRatioSampler returns a otelsdktrace.Sampler with parent based trace id ratio sampling.

func NewStdoutSpanProcessor

func NewStdoutSpanProcessor(options ...stdouttrace.Option) trace.SpanProcessor

NewTestSpanProcessor returns a OTEL SpanProcessor using an async stdouttrace.Exporter.

func NewTestSpanProcessor

func NewTestSpanProcessor(testTraceExporter tracetest.TestTraceExporter) trace.SpanProcessor

NewTestSpanProcessor returns a OTEL SpanProcessor using a sync tracetest.TestTraceExporter.

func NewTraceIdRatioSampler

func NewTraceIdRatioSampler(ratio float64) otelsdktrace.Sampler

NewTraceIdRatioSampler returns a otelsdktrace.Sampler with trace id ratio sampling.

func WithContext

func WithContext(ctx context.Context, tp trace.TracerProvider) context.Context

WithContext appends to a given context a OTEL TracerProvider.

Types

type CtxKey

type CtxKey struct{}

CtxKey is a contextual struct key.

type DefaultTracerProviderFactory

type DefaultTracerProviderFactory struct{}

DefaultTracerProviderFactory is the default TracerProviderFactory implementation.

func (*DefaultTracerProviderFactory) Create

Create returns a new OTEL TracerProvider, and accepts a list of TracerProviderOption.

For example:

tp, _ := trace.NewDefaultTracerProviderFactory().Create()

is equivalent to:
tp, _ = trace.NewDefaultTracerProviderFactory().Create(
	trace.Global(true),                                       // set the tracer provider as global
	trace.WithResource(resource.Default()),                   // use the default resource
	trace.WithSampler(trace.NewParentBasedAlwaysOnSampler()), // use parent based always on sampling
	trace.WithSpanProcessor(trace.NewNoopSpanProcessor()),    // use noop processor (void trace spans)
)

type Options

type Options struct {
	Global         bool
	Resource       *resource.Resource
	Sampler        trace.Sampler
	SpanProcessors []trace.SpanProcessor
}

Options are options for the TracerProviderFactory implementations.

func DefaultTracerProviderOptions

func DefaultTracerProviderOptions() Options

DefaultTracerProviderOptions are the default options used in the TracerProviderFactory.

type Sampler

type Sampler int

Sampler is an enum for the supported samplers.

const (
	ParentBasedAlwaysOnSampler Sampler = iota
	ParentBasedAlwaysOffSampler
	ParentBasedTraceIdRatioSampler
	AlwaysOnSampler
	AlwaysOffSampler
	TraceIdRatioSampler
)

func FetchSampler

func FetchSampler(s string) Sampler

FetchSampler returns a Sampler for a given value.

func (Sampler) String

func (s Sampler) String() string

String returns a string representation of the Sampler.

type SpanProcessor

type SpanProcessor int

SpanProcessor is an enum for the supported span processors.

const (
	NoopSpanProcessor SpanProcessor = iota
	StdoutSpanProcessor
	TestSpanProcessor
	OtlpGrpcSpanProcessor
)

func FetchSpanProcessor

func FetchSpanProcessor(p string) SpanProcessor

FetchSpanProcessor returns a SpanProcessor for a given value.

func (SpanProcessor) String

func (p SpanProcessor) String() string

String returns a string representation of the SpanProcessor.

type TracerProviderFactory

type TracerProviderFactory interface {
	Create(options ...TracerProviderOption) (*trace.TracerProvider, error)
}

TracerProviderFactory is the interface for OTEL TracerProvider factories.

func NewDefaultTracerProviderFactory

func NewDefaultTracerProviderFactory() TracerProviderFactory

NewDefaultTracerProviderFactory returns a DefaultTracerProviderFactory, implementing TracerProviderFactory.

type TracerProviderOption

type TracerProviderOption func(o *Options)

TracerProviderOption are functional options for the TracerProviderFactory implementations.

func Global

func Global(b bool) TracerProviderOption

Global is used to set the OTEL TracerProvider as global.

func WithResource

func WithResource(r *resource.Resource) TracerProviderOption

WithResource is used to set the resource to use by the OTEL TracerProvider.

func WithSampler

func WithSampler(s trace.Sampler) TracerProviderOption

WithSampler is used to set the sampler to use by the OTEL TracerProvider.

func WithSpanProcessor

func WithSpanProcessor(spanProcessor trace.SpanProcessor) TracerProviderOption

WithSpanProcessor is used to set the span processor to use by the OTEL TracerProvider.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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