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 ¶
- func AddSpanEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)
- func CacheAttributes(system, operation, key string, hit bool) []attribute.KeyValue
- func ContextWithSpan(ctx context.Context, span trace.Span) context.Context
- func DatabaseAttributes(system, operation, table string) []attribute.KeyValue
- func ExtractGRPC(ctx context.Context, md *metadata.MD) context.Context
- func ExtractHTTP(ctx context.Context, header http.Header) context.Context
- func GRPCAttributes(method, service string, statusCode int) []attribute.KeyValue
- func GRPCStreamServerInterceptor(serviceName string) grpc.StreamServerInterceptor
- func GRPCUnaryServerInterceptor(serviceName string) grpc.UnaryServerInterceptor
- func GetPropagator() propagation.TextMapPropagator
- func GetTracer(name string) trace.Tracer
- func HTTPAttributes(method, path, host string, statusCode int) []attribute.KeyValue
- func HTTPMiddleware(serviceName string) func(http.Handler) http.Handler
- func InjectGRPC(ctx context.Context, md *metadata.MD)
- func InjectHTTP(ctx context.Context, header http.Header)
- func MessagingAttributes(system, destination, operation string, messageSize int) []attribute.KeyValue
- func SetSpanAttributes(ctx context.Context, attrs ...attribute.KeyValue)
- func SetSpanError(ctx context.Context, err error)
- func SetSpanStatus(ctx context.Context, code codes.Code, description string)
- func SpanFromContext(ctx context.Context) trace.Span
- func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func StartSpanWithTracer(ctx context.Context, tracerName, spanName string, ...) (context.Context, trace.Span)
- type GRPCCarrier
- type HTTPCarrier
- type ShutdownFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddSpanEvent ¶
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 ¶
CacheAttributes returns common cache attributes for a span.
func ContextWithSpan ¶
ContextWithSpan returns a new context with the given span.
func DatabaseAttributes ¶
DatabaseAttributes returns common database attributes for a span.
func ExtractGRPC ¶
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 ¶
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 ¶
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 ¶
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 ¶
HTTPAttributes returns common HTTP attributes for a span.
func HTTPMiddleware ¶
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 ¶
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 ¶
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 ¶
SetSpanAttributes adds attributes to the span in the context. This is a convenience function that extracts the span and sets attributes.
func SetSpanError ¶
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 ¶
SetSpanStatus sets the status code and description of the span.
func SpanFromContext ¶
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 ¶
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.
type ShutdownFunc ¶
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.