tracing

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package tracing provides OpenTelemetry distributed tracing with W3C trace context propagation. It supports OTLP exporters (gRPC/HTTP), automatic span creation via middleware, and graceful shutdown.

Example usage:

cfg := config.TracingConfig{
    Enabled:    true,
    Endpoint:   "localhost:4317",
    SampleRate: 0.1,
    ExportMode: "grpc",
}
tp, shutdown, err := tracing.NewTracerProvider(ctx, cfg, "my-service")
if err != nil {
    log.Fatal(err)
}
defer shutdown(ctx)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSpanEvent

func AddSpanEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)

AddSpanEvent adds an event to the span with the given name and attributes. Events are timestamped occurrences that happened during the span's lifetime.

func CacheAttributes

func CacheAttributes(system, operation, key string, hit bool) []attribute.KeyValue

CacheAttributes returns common cache attributes for a span.

func ContextWithSpan

func ContextWithSpan(ctx context.Context, span trace.Span) context.Context

ContextWithSpan returns a new context with the given span.

func DatabaseAttributes

func DatabaseAttributes(system, operation, table string) []attribute.KeyValue

DatabaseAttributes returns common database attributes for a span.

func ExtractGRPC

func ExtractGRPC(ctx context.Context, md *metadata.MD) context.Context

ExtractGRPC extracts trace context from gRPC metadata. It returns a new context with the extracted trace information.

Example:

md, ok := metadata.FromIncomingContext(ctx)
if ok {
    ctx = tracing.ExtractGRPC(ctx, &md)
}

func ExtractHTTP

func ExtractHTTP(ctx context.Context, header http.Header) context.Context

ExtractHTTP extracts trace context from HTTP request headers. It returns a new context with the extracted trace information.

Example:

ctx = tracing.ExtractHTTP(ctx, req.Header)
ctx, span := tracing.StartSpan(ctx, "handler")
defer span.End()

func GRPCAttributes

func GRPCAttributes(method, service string, statusCode int) []attribute.KeyValue

GRPCAttributes returns common gRPC attributes for a span.

func GRPCStreamServerInterceptor

func GRPCStreamServerInterceptor(serviceName string) grpc.StreamServerInterceptor

GRPCStreamServerInterceptor returns a gRPC server interceptor that creates a span for each incoming streaming RPC call.

Example:

s := grpc.NewServer(
    grpc.StreamInterceptor(tracing.GRPCStreamServerInterceptor("my-service")),
)

func GRPCUnaryServerInterceptor

func GRPCUnaryServerInterceptor(serviceName string) grpc.UnaryServerInterceptor

GRPCUnaryServerInterceptor returns a gRPC server interceptor that creates a span for each incoming unary RPC call. It automatically extracts trace context from gRPC metadata and propagates it through the call chain.

Example:

s := grpc.NewServer(
    grpc.UnaryInterceptor(tracing.GRPCUnaryServerInterceptor("my-service")),
)

func GetPropagator

func GetPropagator() propagation.TextMapPropagator

GetPropagator returns the global text map propagator. This can be used for custom propagation scenarios.

func GetTracer

func GetTracer(name string) trace.Tracer

GetTracer returns a tracer for the given name from the global tracer provider. This is a convenience function for getting a tracer after initialization.

func HTTPAttributes

func HTTPAttributes(method, path, host string, statusCode int) []attribute.KeyValue

HTTPAttributes returns common HTTP attributes for a span.

func HTTPMiddleware

func HTTPMiddleware(serviceName string) func(http.Handler) http.Handler

HTTPMiddleware is an HTTP middleware that creates a span for each incoming request. It automatically extracts trace context from request headers, creates a root span, and injects span information into the request context for downstream handlers.

Example:

mux := http.NewServeMux()
handler := tracing.HTTPMiddleware("my-service")(mux)
http.ListenAndServe(":8080", handler)

func InjectGRPC

func InjectGRPC(ctx context.Context, md *metadata.MD)

InjectGRPC injects trace context into gRPC metadata. It uses the W3C Trace Context propagation format.

Example:

md := metadata.New(nil)
tracing.InjectGRPC(ctx, &md)
ctx = metadata.NewOutgoingContext(ctx, md)

func InjectHTTP

func InjectHTTP(ctx context.Context, header http.Header)

InjectHTTP injects trace context into HTTP request headers. It uses the W3C Trace Context propagation format (traceparent, tracestate).

Example:

req, _ := http.NewRequest("GET", "http://example.com", nil)
tracing.InjectHTTP(ctx, req.Header)

func MessagingAttributes

func MessagingAttributes(system, destination, operation string, messageSize int) []attribute.KeyValue

MessagingAttributes returns common messaging attributes for a span.

func SetSpanAttributes

func SetSpanAttributes(ctx context.Context, attrs ...attribute.KeyValue)

SetSpanAttributes adds attributes to the span in the context. This is a convenience function that extracts the span and sets attributes.

func SetSpanError

func SetSpanError(ctx context.Context, err error)

SetSpanError marks the span as errored and records the error message. The span status is set to Error and the error is recorded as an event.

func SetSpanStatus

func SetSpanStatus(ctx context.Context, code codes.Code, description string)

SetSpanStatus sets the status code and description of the span.

func SpanFromContext

func SpanFromContext(ctx context.Context) trace.Span

SpanFromContext retrieves the current span from the context. Returns a no-op span if no span is present in the context.

func StartSpan

func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartSpan creates a new span with the given name and options. It automatically links the span to its parent span from the context. The returned context contains the new span and should be passed to downstream operations.

Example:

ctx, span := tracing.StartSpan(ctx, "operation-name",
    trace.WithAttributes(attribute.String("user.id", "123")))
defer span.End()

func StartSpanWithTracer

func StartSpanWithTracer(ctx context.Context, tracerName, spanName string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartSpanWithTracer creates a new span using a specific tracer. This is useful when you want to use a tracer with a specific name or version.

Types

type GRPCCarrier

type GRPCCarrier struct {
	// contains filtered or unexported fields
}

GRPCCarrier adapts gRPC metadata to TextMapCarrier interface.

func (*GRPCCarrier) Get

func (c *GRPCCarrier) Get(key string) string

Get returns the value associated with the passed key.

func (*GRPCCarrier) Keys

func (c *GRPCCarrier) Keys() []string

Keys lists the keys stored in this carrier.

func (*GRPCCarrier) Set

func (c *GRPCCarrier) Set(key, value string)

Set stores the key-value pair.

type HTTPCarrier

type HTTPCarrier http.Header

HTTPCarrier adapts http.Header to TextMapCarrier interface.

func (HTTPCarrier) Get

func (c HTTPCarrier) Get(key string) string

Get returns the value associated with the passed key.

func (HTTPCarrier) Keys

func (c HTTPCarrier) Keys() []string

Keys lists the keys stored in this carrier.

func (HTTPCarrier) Set

func (c HTTPCarrier) Set(key, value string)

Set stores the key-value pair.

type ShutdownFunc

type ShutdownFunc func(context.Context) error

ShutdownFunc is a function to gracefully shutdown the tracer provider. It should be called with a context when the application terminates to flush pending spans.

func NewTracerProvider

func NewTracerProvider(ctx context.Context, cfg config.TracingConfig, serviceName string) (*sdktrace.TracerProvider, ShutdownFunc, error)

NewTracerProvider creates and initializes a TracerProvider with OTLP exporter. It configures the tracer with the provided config and service name, setting up resource attributes, sampling, and the appropriate exporter (gRPC or HTTP).

The context is used for initialization operations and should have a reasonable timeout. The returned ShutdownFunc must be called to flush pending spans before process termination.

If tracing is disabled in config, it returns a no-op tracer provider and shutdown function.

Jump to

Keyboard shortcuts

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