Documentation
¶
Index ¶
- Variables
- func AddSpanAttributes(ctx context.Context, attrs map[string]string)
- func AddSpanEvent(ctx context.Context, name string, attrs map[string]string)
- func CleanSensitiveHeaders(headers map[string]string, sensitiveHeaders []string) map[string]string
- func CleanSensitiveQueryParams(queryParams map[string]string, sensitiveParams []string) map[string]string
- func ExtractTraceContextFromRequest(r *http.Request) map[string]string
- func FormatTraceParent(info *TraceContextInfo) string
- func HTTPClientSpanNameAndAttrs(apiName, domain, method, target string, timeout time.Duration, sslVerify bool) (string, map[string]string)
- func InitGlobalTracing(config *TracingConfig) error
- func InitGlobalTracingConfig(configPath string) error
- func InitHTTPClientMetrics()
- func InitializeTracing(config *TracingConfig) error
- func InitializeTracingFromConfig(configPath string) error
- func InitializeTracingFromEnv() error
- func InjectTraceContextToRequest(r *http.Request, headers map[string]string)
- func InjectTraceContextToResponse(w http.ResponseWriter, headers map[string]string)
- func LogWithTrace(ctx context.Context, logger *slog.Logger, level slog.Level, msg string, ...)
- func MergeSpanAttrs(base, extra map[string]string) map[string]string
- func RecordError(ctx context.Context, err error, attrs map[string]string)
- func RecordHTTPClientCall(apiName, method string, statusCode int, duration time.Duration, err error)
- func RecordHTTPClientCallWithOutcome(apiName, method string, statusCode int, duration time.Duration, err error, ...)
- func ShutdownGlobalTracing(ctx context.Context) error
- func ShutdownTracing(ctx context.Context) error
- func SpanAttrsFromSlogValue(prefix string, v slog.Value) map[string]string
- func StartSpan(ctx context.Context, name string, attrs map[string]string) (context.Context, trace.Span)
- func TraceError[Arg TracableArg](fn func(Arg) error, arg Arg) error
- func TraceErrorWithContext(ctx context.Context, fn func(context.Context) error) (error, context.Context)
- func TraceErrorWithParser[Arg any](parser webFramework.RequestParser, fn func(Arg) error, arg Arg) error
- func TraceFunc[T any, Arg TracableArg](fn func(Arg) (T, error), arg Arg) (T, error)
- func TraceFuncWithContext[T any](ctx context.Context, fn func(context.Context) (T, error)) (T, error, context.Context)
- func TraceFuncWithParser[T any, Arg any](parser webFramework.RequestParser, fn func(Arg) (T, error), arg Arg) (T, error)
- func TraceFuncWithSpanName[T any](ctx context.Context, spanName string, attrs map[string]string, ...) (T, error, context.Context)
- func TraceVoid[Arg TracableArg](fn func(Arg), arg Arg)
- func TraceVoidWithContext(ctx context.Context, fn func(context.Context)) context.Context
- func TraceVoidWithParser[Arg any](parser webFramework.RequestParser, fn func(Arg), arg Arg)
- func TracingMiddleware(tm *TracingManager) func(next http.Handler) http.Handler
- type HTTPClientMetricsRecorder
- type HTTPHeaderCarrier
- type MapCarrier
- type SpanContext
- type SpanEvent
- type SpanInfo
- type SpanStatus
- type TracableArg
- type TraceContextInfo
- type TracingAttributes
- type TracingConfig
- type TracingConfigLoader
- type TracingContext
- func (tc *TracingContext) AddAttribute(key, value string)
- func (tc *TracingContext) AddAttributes(attrs map[string]string)
- func (tc *TracingContext) AddEvent(name string, attrs map[string]string)
- func (tc *TracingContext) End()
- func (tc *TracingContext) GetSpan() trace.Span
- func (tc *TracingContext) GetSpanContext() SpanContext
- func (tc *TracingContext) RecordError(err error, attrs map[string]string)
- func (tc *TracingContext) SetStatus(code codes.Code, description string)
- type TracingInitializer
- type TracingManager
- func (tm *TracingManager) AddSpanAttributes(ctx context.Context, attrs map[string]string)
- func (tm *TracingManager) AddSpanEvent(ctx context.Context, name string, attrs map[string]string)
- func (tm *TracingManager) ExtractTraceContext(ctx context.Context, headers map[string]string) context.Context
- func (tm *TracingManager) GetTracer() trace.Tracer
- func (tm *TracingManager) InjectTraceContext(ctx context.Context, headers map[string]string)
- func (tm *TracingManager) RecordError(ctx context.Context, err error, attrs map[string]string)
- func (tm *TracingManager) Shutdown(ctx context.Context) error
- func (tm *TracingManager) StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func (tm *TracingManager) StartSpanWithAttributes(ctx context.Context, name string, attrs map[string]string, ...) (context.Context, trace.Span)
- type TracingMiddlewareConfig
Constants ¶
This section is empty.
Variables ¶
var TraceContextHeaders = struct { TraceParent string TraceState string Baggage string }{ TraceParent: "traceparent", TraceState: "tracestate", Baggage: "baggage", }
TraceContextHeaders contains the standard trace context header names
Functions ¶
func CleanSensitiveHeaders ¶
CleanSensitiveHeaders removes sensitive headers from tracing
func CleanSensitiveQueryParams ¶
func CleanSensitiveQueryParams(queryParams map[string]string, sensitiveParams []string) map[string]string
CleanSensitiveQueryParams removes sensitive query parameters from tracing
func ExtractTraceContextFromRequest ¶
ExtractTraceContextFromRequest extracts trace context from HTTP request
func FormatTraceParent ¶
func FormatTraceParent(info *TraceContextInfo) string
FormatTraceParent formats trace context info into traceparent header
func HTTPClientSpanNameAndAttrs ¶ added in v0.22.0
func HTTPClientSpanNameAndAttrs(apiName, domain, method, target string, timeout time.Duration, sslVerify bool) (string, map[string]string)
HTTPClientSpanNameAndAttrs builds a span name and attributes for outbound HTTP calls. domain should be the base domain (e.g. https://service/api), and target is the full target path (path + query).
func InitGlobalTracing ¶
func InitGlobalTracing(config *TracingConfig) error
InitGlobalTracing initializes global tracing
func InitGlobalTracingConfig ¶
InitGlobalTracingConfig initializes global tracing configuration
func InitHTTPClientMetrics ¶ added in v0.27.0
func InitHTTPClientMetrics()
InitHTTPClientMetrics registers Prometheus metrics for outbound HTTP client calls. Safe to call multiple times; uses sync.Once to prevent duplicate-registration panics.
func InitializeTracing ¶
func InitializeTracing(config *TracingConfig) error
InitializeTracing initializes tracing with the given configuration
func InitializeTracingFromConfig ¶
InitializeTracingFromConfig initializes tracing from configuration file
func InitializeTracingFromEnv ¶
func InitializeTracingFromEnv() error
InitializeTracingFromEnv initializes tracing from environment variables
func InjectTraceContextToRequest ¶
InjectTraceContextToRequest injects trace context into HTTP request
func InjectTraceContextToResponse ¶
func InjectTraceContextToResponse(w http.ResponseWriter, headers map[string]string)
InjectTraceContextToResponse injects trace context into HTTP response
func LogWithTrace ¶
func LogWithTrace(ctx context.Context, logger *slog.Logger, level slog.Level, msg string, attrs ...slog.Attr)
Logging integration
func MergeSpanAttrs ¶ added in v0.22.0
MergeSpanAttrs merges extra into base, returning base (creating it if nil).
func RecordHTTPClientCall ¶ added in v0.27.0
func RecordHTTPClientCall(apiName, method string, statusCode int, duration time.Duration, err error)
RecordHTTPClientCall records metrics for an outbound HTTP client call. This is a backward-compatible wrapper that derives outcome from err. Use RecordHTTPClientCallWithOutcome for explicit outcome control (e.g. "timeout").
func RecordHTTPClientCallWithOutcome ¶ added in v0.27.0
func RecordHTTPClientCallWithOutcome(apiName, method string, statusCode int, duration time.Duration, err error, outcome string)
RecordHTTPClientCallWithOutcome records metrics with an explicit outcome label (success, failure, timeout) in addition to the HTTP status class.
func ShutdownGlobalTracing ¶
ShutdownGlobalTracing shuts down global tracing
func ShutdownTracing ¶
ShutdownTracing gracefully shuts down tracing
func SpanAttrsFromSlogValue ¶ added in v0.22.0
SpanAttrsFromSlogValue flattens a slog.Value (typically from LogValue()) into span attributes. It flattens groups as prefix.key and stringifies values. Large values are truncated.
func StartSpan ¶
func StartSpan(ctx context.Context, name string, attrs map[string]string) (context.Context, trace.Span)
Helper functions for common tracing operations
func TraceError ¶ added in v0.22.0
func TraceError[Arg TracableArg](fn func(Arg) error, arg Arg) error
TraceError traces a function that returns only error - Normal mode (automatic parser extraction) Usage: err := TraceError(handler.Initializer, trx) Automatically extracts context from arg's RequestParser and updates it
func TraceErrorWithContext ¶ added in v0.22.0
func TraceErrorWithContext(ctx context.Context, fn func(context.Context) error) (error, context.Context)
TraceErrorWithContext traces a function that takes context and returns error Usage: err, newCtx := TraceErrorWithContext(ctx, func(ctx context.Context) error { ... }) Returns: (error, newContext) - newContext contains the span context for propagation
func TraceErrorWithParser ¶ added in v0.22.0
func TraceErrorWithParser[Arg any](parser webFramework.RequestParser, fn func(Arg) error, arg Arg) error
TraceErrorWithParser traces a function that returns only error - Manual mode (explicit parser) Usage: err := TraceErrorWithParser(parser, myFunction, myArg) Uses provided parser to extract and update context
func TraceFunc ¶ added in v0.22.0
func TraceFunc[T any, Arg TracableArg](fn func(Arg) (T, error), arg Arg) (T, error)
TraceFunc traces a function that returns (T, error) - Normal mode (automatic parser extraction) Usage: result, err := TraceFunc(handler.Handler, trx) Automatically extracts context from arg's RequestParser and updates it
func TraceFuncWithContext ¶ added in v0.22.0
func TraceFuncWithContext[T any](ctx context.Context, fn func(context.Context) (T, error)) (T, error, context.Context)
TraceFuncWithContext traces a function that takes context and returns (T, error) Usage: result, err, newCtx := TraceFuncWithContext(ctx, func(ctx context.Context) (ResultType, error) { ... }) Returns: (result, error, newContext) - newContext contains the span context for propagation
func TraceFuncWithParser ¶ added in v0.22.0
func TraceFuncWithParser[T any, Arg any](parser webFramework.RequestParser, fn func(Arg) (T, error), arg Arg) (T, error)
TraceFuncWithParser traces a function that returns (T, error) - Manual mode (explicit parser) Usage: result, err := TraceFuncWithParser(parser, myFunction, myArg) Uses provided parser to extract and update context
func TraceFuncWithSpanName ¶ added in v0.22.0
func TraceFuncWithSpanName[T any](ctx context.Context, spanName string, attrs map[string]string, fn func(context.Context) (T, error)) (T, error, context.Context)
TraceFuncWithSpanName traces a function that takes context and returns (T, error) with custom span name and attributes Usage: result, err, newCtx := TraceFuncWithSpanName(ctx, spanName, attrs, func(ctx context.Context) (ResultType, error) { ... })
func TraceVoid ¶ added in v0.22.0
func TraceVoid[Arg TracableArg](fn func(Arg), arg Arg)
TraceVoid traces a function with no return value - Normal mode (automatic parser extraction) Usage: TraceVoid(handler.Finalizer, trx) Automatically extracts context from arg's RequestParser and updates it
func TraceVoidWithContext ¶ added in v0.22.0
TraceVoidWithContext traces a function that takes context and returns nothing Usage: newCtx := TraceVoidWithContext(ctx, func(ctx context.Context) { ... }) Returns: newContext - contains the span context for propagation
func TraceVoidWithParser ¶ added in v0.22.0
func TraceVoidWithParser[Arg any](parser webFramework.RequestParser, fn func(Arg), arg Arg)
TraceVoidWithParser traces a function with no return value - Manual mode (explicit parser) Usage: TraceVoidWithParser(parser, myFunction, myArg) Uses provided parser to extract and update context
func TracingMiddleware ¶
func TracingMiddleware(tm *TracingManager) func(next http.Handler) http.Handler
TracingMiddleware creates middleware for HTTP tracing
Types ¶
type HTTPClientMetricsRecorder ¶ added in v0.27.0
type HTTPClientMetricsRecorder interface {
Record(api, method string, statusCode int, duration time.Duration, outcome string)
}
HTTPClientMetricsRecorder is the interface for recording outbound HTTP client call metrics. Inject a custom implementation for testing; use the default Prometheus-backed recorder in production.
func DefaultHTTPClientMetricsRecorder ¶ added in v0.27.0
func DefaultHTTPClientMetricsRecorder() HTTPClientMetricsRecorder
DefaultHTTPClientMetricsRecorder returns the default Prometheus-backed recorder.
type HTTPHeaderCarrier ¶
type HTTPHeaderCarrier struct {
// contains filtered or unexported fields
}
HTTPHeaderCarrier implements the TextMapCarrier interface for HTTP headers
func NewHTTPHeaderCarrier ¶
func NewHTTPHeaderCarrier(headers http.Header) *HTTPHeaderCarrier
NewHTTPHeaderCarrier creates a new HTTP header carrier
func (*HTTPHeaderCarrier) Get ¶
func (c *HTTPHeaderCarrier) Get(key string) string
Get returns the value for the given key
func (*HTTPHeaderCarrier) Set ¶
func (c *HTTPHeaderCarrier) Set(key, value string)
Set sets the value for the given key
type MapCarrier ¶
type MapCarrier struct {
// contains filtered or unexported fields
}
MapCarrier implements the TextMapCarrier interface for map[string]string
func NewMapCarrier ¶
func NewMapCarrier(headers map[string]string) *MapCarrier
NewMapCarrier creates a new map carrier
func (*MapCarrier) Get ¶
func (c *MapCarrier) Get(key string) string
Get returns the value for the given key
func (*MapCarrier) Set ¶
func (c *MapCarrier) Set(key, value string)
Set sets the value for the given key
type SpanContext ¶
type SpanContext struct {
TraceID string `json:"trace_id"`
SpanID string `json:"span_id"`
Sampled bool `json:"sampled"`
}
SpanContext holds span context information
type SpanEvent ¶
type SpanEvent struct {
Name string `json:"name"`
Timestamp time.Time `json:"timestamp"`
Attributes map[string]string `json:"attributes"`
}
SpanEvent represents an event within a span
type SpanInfo ¶
type SpanInfo struct {
Name string `json:"name"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Duration time.Duration `json:"duration"`
Attributes map[string]string `json:"attributes"`
Events []SpanEvent `json:"events"`
Status SpanStatus `json:"status"`
}
SpanInfo holds span information for logging and debugging
type SpanStatus ¶
SpanStatus represents the status of a span
type TracableArg ¶ added in v0.22.0
type TracableArg interface {
GetParser() webFramework.RequestParser
}
TracableArg constraint for types that have RequestParser (like HandlerRequest)
type TraceContextInfo ¶
type TraceContextInfo struct {
TraceID string `json:"trace_id"`
SpanID string `json:"span_id"`
Sampled bool `json:"sampled"`
Baggage map[string]string `json:"baggage"`
TraceState string `json:"trace_state"`
}
TraceContextInfo holds trace context information
func ParseTraceParent ¶
func ParseTraceParent(traceParent string) *TraceContextInfo
ParseTraceParent parses a traceparent header value
type TracingAttributes ¶
type TracingAttributes struct {
// HTTP attributes
HTTPMethod string `json:"http.method"`
HTTPURL string `json:"http.url"`
HTTPStatusCode string `json:"http.status_code"`
HTTPUserAgent string `json:"http.user_agent"`
// Request attributes
RequestID string `json:"request.id"`
UserID string `json:"user.id"`
ProgramID string `json:"program.id"`
ModuleID string `json:"module.id"`
MethodID string `json:"method.id"`
// Database attributes
DBOperation string `json:"db.operation"`
DBStatement string `json:"db.statement"`
DBTable string `json:"db.table"`
// Custom attributes
CustomAttributes map[string]string `json:"custom_attributes"`
}
TracingAttributes defines common tracing attributes
func (*TracingAttributes) ToMap ¶
func (ta *TracingAttributes) ToMap() map[string]string
ToMap converts TracingAttributes to map[string]string
type TracingConfig ¶
type TracingConfig struct {
// Service information
ServiceName string `yaml:"service_name" json:"service_name"`
ServiceVersion string `yaml:"service_version" json:"service_version"`
Environment string `yaml:"environment" json:"environment"`
// Exporter configuration
Exporter string `yaml:"exporter" json:"exporter"`
JaegerEndpoint string `yaml:"jaeger_endpoint" json:"jaeger_endpoint"`
ZipkinEndpoint string `yaml:"zipkin_endpoint" json:"zipkin_endpoint"`
// Sampling configuration
SamplingRatio float64 `yaml:"sampling_ratio" json:"sampling_ratio"`
// Additional attributes
Attributes map[string]string `yaml:"attributes" json:"attributes"`
// Enable/disable tracing
Enabled bool `yaml:"enabled" json:"enabled"`
}
TracingConfig represents tracing configuration
func DefaultTracingConfig ¶
func DefaultTracingConfig() *TracingConfig
DefaultTracingConfig returns a default tracing configuration
func GetGlobalTracingConfig ¶
func GetGlobalTracingConfig() *TracingConfig
GetGlobalTracingConfig provides access to the globally loaded tracing configuration
type TracingConfigLoader ¶
type TracingConfigLoader struct {
// contains filtered or unexported fields
}
TracingConfigLoader handles loading and managing tracing configurations
func NewTracingConfigLoader ¶
func NewTracingConfigLoader(path string) *TracingConfigLoader
NewTracingConfigLoader creates a new loader instance
func (*TracingConfigLoader) GetConfig ¶
func (l *TracingConfigLoader) GetConfig() *TracingConfig
GetConfig returns the loaded configuration
func (*TracingConfigLoader) LoadConfig ¶
func (l *TracingConfigLoader) LoadConfig() error
LoadConfig loads the tracing configuration from the specified YAML file
func (*TracingConfigLoader) LoadConfigFromEnv ¶
func (l *TracingConfigLoader) LoadConfigFromEnv() error
LoadConfigFromEnv loads configuration from environment variables
type TracingContext ¶
TracingContext extends context.Context with tracing capabilities
func NewTracingContext ¶
func NewTracingContext(ctx context.Context, span trace.Span) *TracingContext
NewTracingContext creates a new tracing context
func (*TracingContext) AddAttribute ¶
func (tc *TracingContext) AddAttribute(key, value string)
AddAttribute adds an attribute to the span
func (*TracingContext) AddAttributes ¶
func (tc *TracingContext) AddAttributes(attrs map[string]string)
AddAttributes adds multiple attributes to the span
func (*TracingContext) AddEvent ¶
func (tc *TracingContext) AddEvent(name string, attrs map[string]string)
AddEvent adds an event to the span
func (*TracingContext) GetSpan ¶
func (tc *TracingContext) GetSpan() trace.Span
GetSpan returns the current span
func (*TracingContext) GetSpanContext ¶
func (tc *TracingContext) GetSpanContext() SpanContext
GetSpanContext returns span context information
func (*TracingContext) RecordError ¶
func (tc *TracingContext) RecordError(err error, attrs map[string]string)
RecordError records an error in the span
type TracingInitializer ¶
type TracingInitializer struct {
// contains filtered or unexported fields
}
TracingInitializer handles tracing initialization
func NewTracingInitializer ¶
func NewTracingInitializer(config *TracingConfig) (*TracingInitializer, error)
NewTracingInitializer creates a new tracing initializer
type TracingManager ¶
type TracingManager struct {
// contains filtered or unexported fields
}
TracingManager manages OpenTelemetry tracing
func GetGlobalTracingManager ¶
func GetGlobalTracingManager() *TracingManager
GetGlobalTracingManager returns the global tracing manager
func NewTracingManager ¶
func NewTracingManager(config *TracingConfig) (*TracingManager, error)
NewTracingManager creates a new tracing manager
func (*TracingManager) AddSpanAttributes ¶
func (tm *TracingManager) AddSpanAttributes(ctx context.Context, attrs map[string]string)
AddSpanAttributes adds attributes to the current span
func (*TracingManager) AddSpanEvent ¶
AddSpanEvent adds an event to the current span
func (*TracingManager) ExtractTraceContext ¶
func (tm *TracingManager) ExtractTraceContext(ctx context.Context, headers map[string]string) context.Context
ExtractTraceContext extracts trace context from headers
func (*TracingManager) GetTracer ¶
func (tm *TracingManager) GetTracer() trace.Tracer
GetTracer returns the tracer instance
func (*TracingManager) InjectTraceContext ¶
func (tm *TracingManager) InjectTraceContext(ctx context.Context, headers map[string]string)
InjectTraceContext injects trace context into headers
func (*TracingManager) RecordError ¶
RecordError records an error in the current span
func (*TracingManager) Shutdown ¶
func (tm *TracingManager) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the tracing manager
func (*TracingManager) StartSpan ¶
func (tm *TracingManager) StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartSpan starts a new span
func (*TracingManager) StartSpanWithAttributes ¶
func (tm *TracingManager) StartSpanWithAttributes(ctx context.Context, name string, attrs map[string]string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartSpanWithAttributes starts a new span with attributes
type TracingMiddlewareConfig ¶
type TracingMiddlewareConfig struct {
// Whether to trace HTTP requests
TraceHTTP bool `yaml:"trace_http" json:"trace_http"`
// Whether to trace database operations
TraceDB bool `yaml:"trace_db" json:"trace_db"`
// Whether to trace external API calls
TraceAPI bool `yaml:"trace_api" json:"trace_api"`
// Whether to include request/response bodies
IncludeBodies bool `yaml:"include_bodies" json:"include_bodies"`
// Maximum body size to include (in bytes)
MaxBodySize int `yaml:"max_body_size" json:"max_body_size"`
// Sensitive headers to exclude from tracing
SensitiveHeaders []string `yaml:"sensitive_headers" json:"sensitive_headers"`
// Sensitive query parameters to exclude from tracing
SensitiveQueryParams []string `yaml:"sensitive_query_params" json:"sensitive_query_params"`
}
TracingMiddlewareConfig holds configuration for tracing middleware
func DefaultTracingMiddlewareConfig ¶
func DefaultTracingMiddlewareConfig() *TracingMiddlewareConfig
DefaultTracingMiddlewareConfig returns default middleware configuration