observability

package
v1.13.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: May 29, 2025 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package observability provides monitoring, tracing, and metrics functionality. It includes OpenTelemetry integration, custom metrics, and distributed tracing support.

Index

Constants

View Source
const (
	// Service attributes
	KeyServiceName    = "service.name"
	KeyServiceVersion = "service.version"
	KeyEnvironment    = "environment"

	// Operation attributes
	KeyOperationName = "operation.name"
	KeyOperationType = "operation.type"

	// Resource attributes
	KeyResourceType = "resource.type"
	KeyResourceID   = "resource.id"

	// Organization attributes
	KeyOrganizationID = "organization.id"
	KeyLedgerID       = "ledger.id"
	KeyAccountID      = "account.id"

	// HTTP attributes
	KeyHTTPMethod   = "http.method"
	KeyHTTPPath     = "http.path"
	KeyHTTPStatus   = "http.status_code"
	KeyHTTPHost     = "http.host"
	KeyErrorCode    = "error.code"
	KeyErrorMessage = "error.message"

	// Metric names
	MetricRequestTotal        = "request.total"
	MetricRequestDuration     = "request.duration"
	MetricRequestErrorTotal   = "request.error.total"
	MetricRequestSuccess      = "request.success"
	MetricRequestRetryTotal   = "request.retry.total"
	MetricRequestBatchSize    = "request.batch.size"
	MetricRequestBatchLatency = "request.batch.latency"
)

Constants for attribute keys

Variables

This section is empty.

Functions

func AddSpanAttributes

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

AddSpanAttributes adds attributes to the current span

func AddSpanEvent

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

AddSpanEvent adds an event to the current span

func ExtractSpanContext

func ExtractSpanContext(ctx context.Context) trace.SpanContext

ExtractSpanContext returns the span context from the context

func GetBaggageItem

func GetBaggageItem(ctx context.Context, key string) string

GetBaggageItem returns a baggage item from the context

func GetCurrentSpan

func GetCurrentSpan(ctx context.Context) trace.Span

GetCurrentSpan returns the current span from context

func IsRecording

func IsRecording(ctx context.Context) bool

IsRecording returns true if there's an active recording span in the context

func Link(_ context.Context, linkedSpanContext trace.SpanContext, attributes ...attribute.KeyValue) trace.Link

Link creates a link between spans

func NewFiberMiddleware

func NewFiberMiddleware(provider Provider, opts ...FiberMiddlewareOption) (fiber.Handler, error)

NewFiberMiddleware creates a new Fiber middleware for tracing and metrics

func NewHTTPClientMiddleware

func NewHTTPClientMiddleware(provider Provider, opts ...HTTPClientOption) func(http.RoundTripper) http.RoundTripper

NewHTTPClientMiddleware creates a new HTTP client middleware for tracing and metrics

func RecordDuration

func RecordDuration(ctx context.Context, provider Provider, name string, start time.Time, attrs ...attribute.KeyValue)

RecordDuration records a duration metric using the provided meter

func RecordMetric

func RecordMetric(ctx context.Context, provider Provider, name string, value float64, attrs ...attribute.KeyValue)

RecordMetric records a metric using the provided meter

func SetSpanError

func SetSpanError(ctx context.Context, err error)

SetSpanError sets error on the current span

func SetSpanSuccess

func SetSpanSuccess(ctx context.Context)

SetSpanSuccess sets success status on the current span

func SpanID

func SpanID(ctx context.Context) string

SpanID returns the span ID from the context, if available

func Start

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

Start starts a new span from a context

func TraceID

func TraceID(ctx context.Context) string

TraceID returns the trace ID from the context, if available

func WithBaggageItem

func WithBaggageItem(ctx context.Context, key, value string) (context.Context, error)

WithBaggageItem returns a new context with a baggage item added

func WithProvider

func WithProvider(ctx context.Context, provider Provider) context.Context

WithProvider returns a new context with the provider added

func WithSpan

func WithSpan(ctx context.Context, provider Provider, name string, fn func(context.Context) error, opts ...trace.SpanStartOption) error

WithSpan creates a new span and executes the function within that span

func WithSpanAttributes

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

WithSpanAttributes returns a new context with attributes added to the current span

Types

type AsyncSpanProcessor

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

AsyncSpanProcessor helps with processing asynchronous operations with spans

func NewAsyncSpanProcessor

func NewAsyncSpanProcessor(provider Provider) *AsyncSpanProcessor

NewAsyncSpanProcessor creates a new async span processor

func (*AsyncSpanProcessor) ProcessAsync

func (p *AsyncSpanProcessor) ProcessAsync(
	ctx context.Context,
	spanName string,
	fn func(context.Context) error,
	opts ...trace.SpanStartOption,
) <-chan error

ProcessAsync processes an async operation with a span

type BatchTimer

type BatchTimer struct {
	Timer
	// contains filtered or unexported fields
}

BatchTimer provides a convenient way to record batch operations

func (*BatchTimer) AddItem

func (bt *BatchTimer) AddItem(item any)

AddItem adds an item to the batch

func (*BatchTimer) AddItems

func (bt *BatchTimer) AddItems(items ...any)

AddItems adds multiple items to the batch

func (*BatchTimer) Stop

func (bt *BatchTimer) Stop(additionalAttrs ...attribute.KeyValue)

Stop records the batch operation

type BusinessMetrics

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

BusinessMetrics provides business-specific metrics

func NewBusinessMetrics

func NewBusinessMetrics(meter metric.Meter) (*BusinessMetrics, error)

NewBusinessMetrics creates a new business metrics instance

func (*BusinessMetrics) RecordAccount

func (bm *BusinessMetrics) RecordAccount(
	ctx context.Context,
	organizationID string,
	ledgerID string,
	accountType string,
)

RecordAccount records an account creation

func (*BusinessMetrics) RecordAsset

func (bm *BusinessMetrics) RecordAsset(
	ctx context.Context,
	organizationID string,
	ledgerID string,
	assetType string,
)

RecordAsset records an asset creation

func (*BusinessMetrics) RecordLedger

func (bm *BusinessMetrics) RecordLedger(
	ctx context.Context,
	organizationID string,
)

RecordLedger records a ledger creation

func (*BusinessMetrics) RecordTransaction

func (bm *BusinessMetrics) RecordTransaction(
	ctx context.Context,
	organizationID string,
	ledgerID string,
	status string,
	transactionType string,
	amount float64,
	currency string,
)

RecordTransaction records a transaction metric

func (*BusinessMetrics) RecordTransactionDuration

func (bm *BusinessMetrics) RecordTransactionDuration(
	ctx context.Context,
	organizationID string,
	ledgerID string,
	duration float64,
)

RecordTransactionDuration records transaction processing duration

func (*BusinessMetrics) RecordTransactionError

func (bm *BusinessMetrics) RecordTransactionError(
	ctx context.Context,
	organizationID string,
	ledgerID string,
	errorType string,
)

RecordTransactionError records a transaction error

type Config

type Config struct {
	// ServiceName is the name of the service
	ServiceName string

	// ServiceVersion is the version of the service
	ServiceVersion string

	// Environment is the environment (development, staging, production)
	Environment string

	// CollectorEndpoint is the endpoint for the OpenTelemetry collector
	CollectorEndpoint string

	// LogLevel is the minimum log level
	LogLevel LogLevel

	// LogOutput is where to write logs (defaults to os.Stderr)
	LogOutput io.Writer

	// TraceSampleRate is the sampling rate for traces (0.0 to 1.0)
	TraceSampleRate float64

	// EnabledComponents controls which components are enabled
	EnabledComponents EnabledComponents

	// Attributes are additional attributes to add to all telemetry
	Attributes []attribute.KeyValue

	// Propagators for context propagation
	Propagators []propagation.TextMapPropagator

	// PropagationHeaders to extract for trace context
	PropagationHeaders []string

	// Insecure disables TLS for gRPC connections
	Insecure bool
}

Config holds the configuration for the observability provider

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration

type ContextKey

type ContextKey string

ContextKey is the type for context keys

const (
	// ProviderKey is the context key for the observability provider
	ProviderKey ContextKey = "observability-provider"
)

type Counter

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

Counter provides a simple counter abstraction

func (*Counter) Add

func (c *Counter) Add(ctx context.Context, value float64, additionalAttrs ...attribute.KeyValue)

Add adds a value to the counter

func (*Counter) Inc

func (c *Counter) Inc(ctx context.Context, additionalAttrs ...attribute.KeyValue)

Inc increments the counter by 1

type DistributedTracingHelper

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

DistributedTracingHelper helps with distributed tracing across services

func NewDistributedTracingHelper

func NewDistributedTracingHelper() *DistributedTracingHelper

NewDistributedTracingHelper creates a new distributed tracing helper

func (*DistributedTracingHelper) CreateChildSpan

func (h *DistributedTracingHelper) CreateChildSpan(
	ctx context.Context,
	tracer trace.Tracer,
	spanName string,
	opts ...trace.SpanStartOption,
) (context.Context, trace.Span)

CreateChildSpan creates a child span from the current context

func (*DistributedTracingHelper) ExtractContext

ExtractContext extracts trace context from a carrier

func (*DistributedTracingHelper) InjectContext

func (h *DistributedTracingHelper) InjectContext(ctx context.Context, carrier propagation.TextMapCarrier)

InjectContext injects trace context into a carrier for propagation

func (*DistributedTracingHelper) PropagateServiceCall

func (h *DistributedTracingHelper) PropagateServiceCall(
	ctx context.Context,
	tracer trace.Tracer,
	serviceName string,
	operationName string,
	call func(context.Context) error,
) error

PropagateServiceCall wraps a service call with distributed tracing

type EnabledComponents

type EnabledComponents struct {
	Tracing bool
	Metrics bool
	Logging bool
}

EnabledComponents controls which observability components are enabled

type FiberMiddlewareOption

type FiberMiddlewareOption func(*fiberMiddleware) error

FiberMiddlewareOption is a function type for configuring the Fiber middleware

func WithIgnoreHeadersFiber

func WithIgnoreHeadersFiber(headers ...string) FiberMiddlewareOption

WithIgnoreHeadersFiber specifies headers that should not be logged

func WithIgnorePathsFiber

func WithIgnorePathsFiber(paths ...string) FiberMiddlewareOption

WithIgnorePathsFiber specifies URL paths that should not be traced

func WithMaskedParamsFiber

func WithMaskedParamsFiber(params ...string) FiberMiddlewareOption

WithMaskedParamsFiber specifies query parameters that should have their values masked

func WithRequestIDExtractor

func WithRequestIDExtractor(fn func(*fiber.Ctx) string) FiberMiddlewareOption

WithRequestIDExtractor sets a function to extract request ID from the request

func WithSecurityDefaultsFiber

func WithSecurityDefaultsFiber() FiberMiddlewareOption

WithSecurityDefaultsFiber sets all default security options

func WithUserIDExtractor

func WithUserIDExtractor(fn func(*fiber.Ctx) string) FiberMiddlewareOption

WithUserIDExtractor sets a function to extract user ID from the request

type HTTPClientOption

type HTTPClientOption func(*httpClientMiddleware) error

HTTPClientOption is a function type for configuring the HTTP client middleware

func WithDefaultSensitiveHeaders

func WithDefaultSensitiveHeaders() HTTPClientOption

WithDefaultSensitiveHeaders sets the default list of headers to ignore for security

func WithDefaultSensitiveParams

func WithDefaultSensitiveParams() HTTPClientOption

WithDefaultSensitiveParams sets the default list of parameters to mask for security

func WithHideRequestBody

func WithHideRequestBody(hide bool) HTTPClientOption

WithHideRequestBody specifies whether to hide request bodies from logs

func WithIgnoreHeaders

func WithIgnoreHeaders(headers ...string) HTTPClientOption

WithIgnoreHeaders specifies HTTP header names that should not be logged

func WithIgnorePaths

func WithIgnorePaths(paths ...string) HTTPClientOption

WithIgnorePaths specifies URL paths that should not be traced

func WithMaskedParams

func WithMaskedParams(params ...string) HTTPClientOption

WithMaskedParams specifies query parameters that should have their values masked

func WithSecurityDefaults

func WithSecurityDefaults() HTTPClientOption

WithSecurityDefaults sets all default security options

type LogLevel

type LogLevel int

LogLevel represents the logging level

const (
	// DebugLevel is the most verbose logging level
	DebugLevel LogLevel = iota
	// InfoLevel is for general information
	InfoLevel
	// WarnLevel is for warnings
	WarnLevel
	// ErrorLevel is for errors
	ErrorLevel
	// FatalLevel is for fatal errors
	FatalLevel
)

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of the log level

type Logger

type Logger interface {
	// Debug logs a message at debug level
	Debug(args ...any)
	// Debugf logs a formatted message at debug level
	Debugf(format string, args ...any)
	// Info logs a message at info level
	Info(args ...any)
	// Infof logs a formatted message at info level
	Infof(format string, args ...any)
	// Warn logs a message at warn level
	Warn(args ...any)
	// Warnf logs a formatted message at warn level
	Warnf(format string, args ...any)
	// Error logs a message at error level
	Error(args ...any)
	// Errorf logs a formatted message at error level
	Errorf(format string, args ...any)
	// Fatal logs a message at fatal level
	Fatal(args ...any)
	// Fatalf logs a formatted message at fatal level
	Fatalf(format string, args ...any)
	// With returns a logger with added structured fields
	With(fields map[string]any) Logger
	// WithContext returns a logger with context information (trace ID, etc.)
	WithContext(ctx trace.SpanContext) Logger
	// WithSpan returns a logger with span information
	WithSpan(span trace.Span) Logger
}

Logger is the interface for all logging operations

func Log

func Log(ctx context.Context) Logger

Log returns a logger from the context

func NewLogger

func NewLogger(level LogLevel, output io.Writer, resource *sdkresource.Resource) Logger

NewLogger creates a new logger with the specified level and output

func NewNoopLogger

func NewNoopLogger() Logger

NewNoopLogger creates a new no-op logger

type LoggerImpl

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

LoggerImpl is the standard implementation of the Logger interface

func (*LoggerImpl) Debug

func (l *LoggerImpl) Debug(args ...any)

Debug logs a message at debug level

func (*LoggerImpl) Debugf

func (l *LoggerImpl) Debugf(format string, args ...any)

Debugf logs a formatted message at debug level

func (*LoggerImpl) Error

func (l *LoggerImpl) Error(args ...any)

Error logs a message at error level

func (*LoggerImpl) Errorf

func (l *LoggerImpl) Errorf(format string, args ...any)

Errorf logs a formatted message at error level

func (*LoggerImpl) Fatal

func (l *LoggerImpl) Fatal(args ...any)

Fatal logs a message at fatal level

func (*LoggerImpl) Fatalf

func (l *LoggerImpl) Fatalf(format string, args ...any)

Fatalf logs a formatted message at fatal level

func (*LoggerImpl) Info

func (l *LoggerImpl) Info(args ...any)

Info logs a message at info level

func (*LoggerImpl) Infof

func (l *LoggerImpl) Infof(format string, args ...any)

Infof logs a formatted message at info level

func (*LoggerImpl) Warn

func (l *LoggerImpl) Warn(args ...any)

Warn logs a message at warn level

func (*LoggerImpl) Warnf

func (l *LoggerImpl) Warnf(format string, args ...any)

Warnf logs a formatted message at warn level

func (*LoggerImpl) With

func (l *LoggerImpl) With(fields map[string]any) Logger

With returns a logger with added structured fields

func (*LoggerImpl) WithContext

func (l *LoggerImpl) WithContext(ctx trace.SpanContext) Logger

WithContext returns a logger with context information (trace ID, etc.)

func (*LoggerImpl) WithSpan

func (l *LoggerImpl) WithSpan(span trace.Span) Logger

WithSpan returns a logger with span information

type MapCarrier

type MapCarrier map[string]string

MapCarrier is a simple implementation of TextMapCarrier for headers

func (MapCarrier) Get

func (c MapCarrier) Get(key string) string

Get returns the value associated with the passed key

func (MapCarrier) Keys

func (c MapCarrier) Keys() []string

Keys lists the keys stored in this carrier

func (MapCarrier) Set

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

Set stores the key-value pair

type MetricsCollector

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

MetricsCollector provides convenient methods for recording common metrics

func NewMetricsCollector

func NewMetricsCollector(provider Provider) (*MetricsCollector, error)

NewMetricsCollector creates a new MetricsCollector for recording metrics

func (*MetricsCollector) NewBatchTimer

func (m *MetricsCollector) NewBatchTimer(ctx context.Context, operation, resourceType string, attrs ...attribute.KeyValue) *BatchTimer

NewBatchTimer creates a new timer for batch operations

func (*MetricsCollector) NewCounter

func (m *MetricsCollector) NewCounter(name, resourceType string, attrs ...attribute.KeyValue) *Counter

NewCounter creates a new counter

func (*MetricsCollector) NewTimer

func (m *MetricsCollector) NewTimer(ctx context.Context, operation, resourceType string, attrs ...attribute.KeyValue) *Timer

NewTimer creates a new timer for recording the duration of an operation

func (*MetricsCollector) RecordBatchRequest

func (m *MetricsCollector) RecordBatchRequest(ctx context.Context, operation, resourceType string, batchSize int, duration time.Duration, attrs ...attribute.KeyValue)

RecordBatchRequest records a batch request with its size and latency

func (*MetricsCollector) RecordError

func (m *MetricsCollector) RecordError(ctx context.Context, operation, resourceType, errorType string, attrs ...attribute.KeyValue)

RecordError records an error occurrence

func (*MetricsCollector) RecordRequest

func (m *MetricsCollector) RecordRequest(ctx context.Context, operation, resourceType string, statusCode int, duration time.Duration, attrs ...attribute.KeyValue)

RecordRequest records a request with its result and duration

func (*MetricsCollector) RecordRetry

func (m *MetricsCollector) RecordRetry(ctx context.Context, operation, resourceType string, attempt int, attrs ...attribute.KeyValue)

RecordRetry records a retry attempt

type NoopLogger

type NoopLogger struct{}

NoopLogger is a no-op implementation of the Logger interface

func (*NoopLogger) Debug

func (l *NoopLogger) Debug(_ ...any)

Debug is a no-op

func (*NoopLogger) Debugf

func (l *NoopLogger) Debugf(_ string, _ ...any)

Debugf is a no-op

func (*NoopLogger) Error

func (l *NoopLogger) Error(_ ...any)

Error is a no-op

func (*NoopLogger) Errorf

func (l *NoopLogger) Errorf(_ string, _ ...any)

Errorf is a no-op

func (*NoopLogger) Fatal

func (l *NoopLogger) Fatal(_ ...any)

Fatal is a no-op (but still exits)

func (*NoopLogger) Fatalf

func (l *NoopLogger) Fatalf(_ string, _ ...any)

Fatalf is a no-op (but still exits)

func (*NoopLogger) Info

func (l *NoopLogger) Info(_ ...any)

Info is a no-op

func (*NoopLogger) Infof

func (l *NoopLogger) Infof(_ string, _ ...any)

Infof is a no-op

func (*NoopLogger) Warn

func (l *NoopLogger) Warn(_ ...any)

Warn is a no-op

func (*NoopLogger) Warnf

func (l *NoopLogger) Warnf(_ string, _ ...any)

Warnf is a no-op

func (*NoopLogger) With

func (l *NoopLogger) With(_ map[string]any) Logger

With returns the same no-op logger

func (*NoopLogger) WithContext

func (l *NoopLogger) WithContext(_ trace.SpanContext) Logger

WithContext returns the same no-op logger

func (*NoopLogger) WithSpan

func (l *NoopLogger) WithSpan(_ trace.Span) Logger

WithSpan returns the same no-op logger

type ObservabilityMiddleware

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

ObservabilityMiddleware provides comprehensive observability for HTTP requests. The type name intentionally matches the package name for clarity in external usage.

func NewObservabilityMiddleware

func NewObservabilityMiddleware(
	serviceName string,
	tracerProvider trace.TracerProvider,
	metricProvider metric.MeterProvider,
	logger *log.StructuredLogger,
) (*ObservabilityMiddleware, error)

NewObservabilityMiddleware creates a new observability middleware

func (*ObservabilityMiddleware) Middleware

func (om *ObservabilityMiddleware) Middleware() fiber.Handler

Middleware returns the fiber middleware handler

type ObservabilityProvider

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

ObservabilityProvider is the main implementation of the Provider interface. The type name intentionally matches the package name for clarity in external usage.

func (*ObservabilityProvider) IsEnabled

func (p *ObservabilityProvider) IsEnabled() bool

IsEnabled returns true if observability is enabled

func (*ObservabilityProvider) Logger

func (p *ObservabilityProvider) Logger() Logger

Logger returns a logger

func (*ObservabilityProvider) Meter

func (p *ObservabilityProvider) Meter() metric.Meter

Meter returns a meter for creating metrics

func (*ObservabilityProvider) MeterProvider

func (p *ObservabilityProvider) MeterProvider() metric.MeterProvider

MeterProvider returns the underlying meter provider

func (*ObservabilityProvider) Shutdown

func (p *ObservabilityProvider) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the provider and all its components

func (*ObservabilityProvider) Tracer

func (p *ObservabilityProvider) Tracer() trace.Tracer

Tracer returns a tracer for creating spans

func (*ObservabilityProvider) TracerProvider

func (p *ObservabilityProvider) TracerProvider() trace.TracerProvider

TracerProvider returns the underlying tracer provider

type Option

type Option func(*Config) error

Option defines a function that configures the observability Config

func WithAttributes

func WithAttributes(attrs ...attribute.KeyValue) Option

WithAttributes adds additional attributes to all telemetry

func WithCollectorEndpoint

func WithCollectorEndpoint(endpoint string) Option

WithCollectorEndpoint sets the OpenTelemetry collector endpoint

func WithComponentEnabled

func WithComponentEnabled(tracing, metrics, logging bool) Option

WithComponentEnabled enables or disables specific components

func WithDevelopmentDefaults

func WithDevelopmentDefaults() Option

WithDevelopmentDefaults sets reasonable defaults for development

func WithEnvironment

func WithEnvironment(env string) Option

WithEnvironment sets the environment

func WithInsecure

func WithInsecure(insecure bool) Option

WithInsecure disables TLS for gRPC connections

func WithLogLevel

func WithLogLevel(level LogLevel) Option

WithLogLevel sets the minimum log level

func WithLogOutput

func WithLogOutput(output io.Writer) Option

WithLogOutput sets the writer for logs

func WithProductionDefaults

func WithProductionDefaults() Option

WithProductionDefaults sets reasonable defaults for production

func WithPropagators

func WithPropagators(propagators ...propagation.TextMapPropagator) Option

WithPropagators sets the propagators for context propagation

func WithServiceName

func WithServiceName(name string) Option

WithServiceName sets the service name

func WithServiceVersion

func WithServiceVersion(version string) Option

WithServiceVersion sets the service version

func WithTraceSampleRate

func WithTraceSampleRate(rate float64) Option

WithTraceSampleRate sets the sampling rate for traces

type Provider

type Provider interface {
	// Tracer returns a tracer for creating spans
	Tracer() trace.Tracer

	// Meter returns a meter for creating metrics
	Meter() metric.Meter

	// TracerProvider returns the underlying tracer provider
	TracerProvider() trace.TracerProvider

	// MeterProvider returns the underlying meter provider
	MeterProvider() metric.MeterProvider

	// Logger returns a logger
	Logger() Logger

	// Shutdown gracefully shuts down the provider
	Shutdown(ctx context.Context) error

	// IsEnabled returns true if observability is enabled
	IsEnabled() bool
}

Provider is the interface for observability providers

func GetProvider

func GetProvider(ctx context.Context) Provider

GetProvider returns the provider from the context, if any

func New

func New(ctx context.Context, opts ...Option) (Provider, error)

New creates a new observability provider with the given options

type SpanProcessor

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

SpanProcessor is a helper for processing spans with common operations

func NewSpanProcessor

func NewSpanProcessor(provider Provider) *SpanProcessor

NewSpanProcessor creates a new span processor

func (*SpanProcessor) ProcessWithSpan

func (p *SpanProcessor) ProcessWithSpan(
	ctx context.Context,
	spanName string,
	fn func(context.Context) error,
	opts ...trace.SpanStartOption,
) error

ProcessWithSpan processes a function within a span with automatic error handling

func (*SpanProcessor) ProcessWithSpanAndResult

func (p *SpanProcessor) ProcessWithSpanAndResult(
	ctx context.Context,
	spanName string,
	fn func(context.Context) (any, error),
	opts ...trace.SpanStartOption,
) (any, error)

ProcessWithSpanAndResult processes a function that returns a result and error

type Timer

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

Timer provides a convenient way to record the duration of an operation

func (*Timer) Stop

func (t *Timer) Stop(statusCode int, additionalAttrs ...attribute.KeyValue)

Stop records the duration of the operation with the result

func (*Timer) StopBatch

func (t *Timer) StopBatch(batchSize int, additionalAttrs ...attribute.KeyValue)

StopBatch records the duration of a batch operation

func (*Timer) StopWithError

func (t *Timer) StopWithError(errorType string, additionalAttrs ...attribute.KeyValue)

StopWithError records the duration and marks it as an error

type TraceContextCarrier

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

TraceContextCarrier wraps any type that has Get/Set methods for headers

func NewTraceContextCarrier

func NewTraceContextCarrier() *TraceContextCarrier

NewTraceContextCarrier creates a new trace context carrier

func (*TraceContextCarrier) Get

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

Get returns the value for a key

func (*TraceContextCarrier) GetHeaders

func (c *TraceContextCarrier) GetHeaders() map[string]string

GetHeaders returns all headers as a map

func (*TraceContextCarrier) Keys

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

Keys returns all keys

func (*TraceContextCarrier) Set

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

Set sets a key-value pair

Jump to

Keyboard shortcuts

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