trace

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2025 License: MIT Imports: 15 Imported by: 0

README

Contributions Welcome Release

Trace Package

The trace package provides an easy-to-use utility for adding distributed tracing to Go applications using OpenTelemetry. With support for multiple trace exporters, function-level tracing, and integration with web frameworks like Gin, this package simplifies instrumentation and performance monitoring across services.

Key Features:

  • Tracer Provider Initialization: Easily initialize and configure OpenTelemetry's Tracer Provider with support for multiple exporters, including: gRPC Exporter: Export traces to remote tracing backends. Stdout Exporter: Print traces to the console for local development and debugging.
  • Function-Level Tracing (TraceFunc): Automatically trace the execution of any Go function, including capturing function start/end times, execution status, and errors.

Installation

go get github.com/kittipat1413/go-common/framework/trace

Documentation

Go Reference

For detailed API documentation, examples, and usage patterns, visit the Go Package Documentation.

Usage

1. Initialize Tracer Provider

To initialize the Tracer Provider, call InitTracerProvider with the service name and desired exporter:

ctx := context.Background()
tracerProvider, err := trace.InitTracerProvider(ctx, "my-service", nil, trace.ExporterStdout)
if err != nil {
    log.Fatalf("Failed to initialize tracer provider: %v", err)
}
defer tracerProvider.Shutdown(ctx)

You can also set the OTEL_SERVICE_NAME environment variable to override the service name dynamically. Additionally, you can set the OTEL_RESOURCE_ATTRIBUTES environment variable to specify additional resource attributes.

2. Function-Level Tracing (TraceFunc)

Wrap any function in TraceFunc to automatically trace its execution:

result, err := trace.TraceFunc(ctx, otel.Tracer("my-tracer"), func(ctx context.Context) (string, error) {
    // Simulate some processing
    time.Sleep(100 * time.Millisecond)
    return "Hello, World!", nil
})

if err != nil {
    log.Fatalf("Error executing traced function: %v", err)
}
fmt.Println("Result:", result)

Example

You can find a complete working example in the repository under framework/trace/example.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultTracer

func DefaultTracer() trace.Tracer

DefaultTracer returns a tracer instance with this package's instrumentation scope. Uses a consistent naming convention for spans created by this common library.

Returns:

  • trace.Tracer: Tracer with package-specific instrumentation scope

Example:

tracer := trace.DefaultTracer()
ctx, span := tracer.Start(ctx, "operation-name")
defer span.End()

func GetTracer added in v0.11.1

func GetTracer(name string) trace.Tracer

GetTracer returns a named tracer or the default tracer if name is empty. Enables custom instrumentation scopes for different components or services.

Parameters:

  • name: Custom instrumentation scope name (empty returns default tracer)

Returns:

  • trace.Tracer: Named tracer instance

Example:

// Custom tracer for specific component
dbTracer := trace.GetTracer("database-operations")

// Default tracer when name is empty
defaultTracer := trace.GetTracer("")

func InitTracerProvider

func InitTracerProvider(ctx context.Context, serviceName string, endpoint *string, exporterType ExporterType) (*sdktrace.TracerProvider, error)

InitTracerProvider initializes OpenTelemetry tracing with configurable exporters and resource detection. Sets up global tracer provider and propagators for distributed tracing across services.

Initialization Process:

  1. Override serviceName with OTEL_SERVICE_NAME environment variable if present
  2. Create exporter based on exporterType
  3. Auto-detect system resources (OS, runtime, process information)
  4. Merge with default OpenTelemetry resource detection
  5. Configure tracer provider with batcher and resource attribution
  6. Set global tracer provider and W3C trace context propagation

Resource Detection:

  • OS information (name, version, architecture)
  • Runtime details (Go version, process info)
  • Environment variables (OTEL_* configuration)
  • Service name and version identification

Propagation:

  • W3C Trace Context for cross-service trace correlation
  • W3C Baggage for additional metadata propagation

Parameters:

  • ctx: Context for exporter initialization and resource detection
  • serviceName: Service identifier for traces (overridden by OTEL_SERVICE_NAME)
  • endpoint: gRPC endpoint for OTLP exporter in "host:port" format (nil for stdout)
  • exporterType: Exporter backend type (stdout for dev, grpc for production)

Returns:

  • *sdktrace.TracerProvider: Configured tracer provider for cleanup
  • error: Configuration or initialization error

func TraceFunc

func TraceFunc[T any](ctx context.Context, tracer trace.Tracer, f func(ctx context.Context) (T, error)) (T, error)

TraceFunc wraps function execution with OpenTelemetry tracing for automatic observability. Creates spans with function names, records execution status, and captures errors with stack traces. Uses Go generics to support any return type while maintaining type safety.

Span Configuration:

  • Span Name: Extracted function name with common suffixes trimmed
  • Span Kind: Internal (function execution within service)
  • Error Recording: Stack traces included for failed operations
  • Status Codes: OK for success, Error for failures with descriptive messages

Function Requirements:

  • Accept context.Context as first parameter
  • Return (T, error) where T is any type

Tracer Fallback:

  • If tracer is nil, uses DefaultTracer() to ensure tracing always works even when not explicitly configured.

Parameters:

  • ctx: Context for span creation and function execution
  • tracer: OpenTelemetry tracer (nil uses default tracer)
  • f: Function to trace following (ctx context.Context) (T, error) pattern

Returns:

  • T: Function result of generic type T
  • error: Function error, nil on success

Example Usage:

user, err := trace.TraceFunc(ctx, tracer, func(ctx context.Context) (*User, error) {
    return userRepo.GetByID(ctx, userID)
})

Types

type ExporterType

type ExporterType string

ExporterType defines supported trace exporter backends. Determines where trace data is sent for collection and analysis.

const (
	ExporterStdout ExporterType = "stdout" // Console output for development and debugging
	ExporterGRPC   ExporterType = "grpc"   // OTLP gRPC for production observability platforms
)

Directories

Path Synopsis
example
gin command
trace_func command

Jump to

Keyboard shortcuts

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