Documentation
¶
Overview ¶
Example ¶
Example demonstrates basic usage of autolemetry.
ctx := context.Background()
// Initialize autolemetry
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("example-service"),
autolemetry.WithEndpoint("localhost:4318"),
)
if err != nil {
log.Fatal(err)
}
defer cleanup()
// Create a traced operation
_, span := autolemetry.Start(ctx, "example-operation")
defer span.End()
span.SetAttribute("example.key", "example-value")
fmt.Println("Tracing initialized")
Output: Tracing initialized
Example (ErrorHandling) ¶
Example_errorHandling demonstrates automatic error recording.
ctx := context.Background()
_, span := autolemetry.Start(ctx, "risky-operation")
defer span.End()
// Simulate an error
err := fmt.Errorf("something went wrong")
if err != nil {
span.RecordError(err) // Automatically sets span status to ERROR
}
fmt.Println("Error recorded in span")
Output: Error recorded in span
Example (Init) ¶
Example_init demonstrates initialization with various options.
ctx := context.Background()
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("my-service"),
autolemetry.WithServiceVersion("1.0.0"),
autolemetry.WithEnvironment("production"),
autolemetry.WithEndpoint("localhost:4318"),
autolemetry.WithProtocol(autolemetry.ProtocolHTTP),
)
if err != nil {
log.Fatal(err)
}
defer cleanup()
fmt.Println("Initialized with custom options")
Output: Initialized with custom options
Example (InitWithConfig) ¶
Example_initWithConfig demonstrates advanced configuration using Config directly. This is for advanced users who need full control over configuration.
ctx := context.Background()
// Get default config and customize it
cfg := autolemetry.DefaultConfig()
cfg.ServiceName = "advanced-service"
cfg.ServiceVersion = "2.0.0"
cfg.Environment = "production"
cfg.Endpoint = "otel-collector:4318"
cfg.Protocol = autolemetry.ProtocolHTTP
cfg.Insecure = false
// Initialize with custom config
cleanup, err := autolemetry.InitWithConfig(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer cleanup()
fmt.Println("Initialized with custom Config")
Output: Initialized with custom Config
Example (NestedSpans) ¶
Example_nestedSpans demonstrates creating nested spans.
ctx := context.Background()
// Parent span
ctx, parentSpan := autolemetry.Start(ctx, "parent-operation")
defer parentSpan.End()
parentSpan.SetAttribute("level", "parent")
// Child span
_, childSpan := autolemetry.Start(ctx, "child-operation")
childSpan.SetAttribute("level", "child")
childSpan.End()
fmt.Println("Nested spans created")
Output: Nested spans created
Example (Start) ¶
Example_start demonstrates creating spans with Start.
ctx := context.Background()
// Start a new span
_, span := autolemetry.Start(ctx, "database-query")
defer span.End()
// Set attributes
span.SetAttribute("db.system", "postgresql")
span.SetAttribute("db.operation", "SELECT")
span.SetAttribute("db.table", "users")
fmt.Println("Span created with attributes")
Output: Span created with attributes
Example (Trace) ¶
Example_trace demonstrates using the Trace helper for automatic error handling.
ctx := context.Background()
// Use Trace helper with automatic error handling
result, err := autolemetry.Trace(ctx, "process-data",
func(ctx context.Context, span autolemetry.Span) (string, error) {
span.SetAttribute("operation", "processing")
// Your business logic here
return "processed-data", nil
},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("Result:", result)
Output: Result: processed-data
Example (TraceNoError) ¶
Example_traceNoError demonstrates Trace helper for operations without errors.
ctx := context.Background()
result := autolemetry.TraceNoError(ctx, "calculation",
func(ctx context.Context, span autolemetry.Span) int {
span.SetAttribute("operation", "add")
return 42 + 8
},
)
fmt.Println("Result:", result)
Output: Result: 50
Example (TraceVoid) ¶
Example_traceVoid demonstrates Trace helper for operations that return only errors.
ctx := context.Background()
err := autolemetry.TraceVoid(ctx, "write-operation",
func(ctx context.Context, span autolemetry.Span) error {
span.SetAttribute("operation", "write")
// Your operation here
return nil
},
)
if err == nil {
fmt.Println("Operation completed successfully")
}
Output: Operation completed successfully
Example (WithCircuitBreaker) ¶
Example_withCircuitBreaker demonstrates circuit breaker configuration.
ctx := context.Background()
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("resilient-service"),
autolemetry.WithCircuitBreaker(
5, // failure threshold
3, // success threshold
30, // timeout in seconds
),
)
if err != nil {
log.Fatal(err)
}
defer cleanup()
fmt.Println("Circuit breaker enabled")
Output: Circuit breaker enabled
Example (WithDebug) ¶
Example_withDebug demonstrates debug mode for development.
ctx := context.Background()
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("debug-service"),
autolemetry.WithDebug(true),
)
if err != nil {
log.Fatal(err)
}
defer cleanup()
fmt.Println("Debug mode enabled")
Output: Debug mode enabled
Example (WithRateLimit) ¶
Example_withRateLimit demonstrates rate limiting configuration.
ctx := context.Background()
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("rate-limited-service"),
autolemetry.WithRateLimit(100, 200), // 100 spans/sec, burst of 200
)
if err != nil {
log.Fatal(err)
}
defer cleanup()
fmt.Println("Rate limiting enabled")
Output: Rate limiting enabled
Index ¶
- Constants
- func AddEvent(ctx context.Context, name string, attrs map[string]any)
- func AddEventWithAttributes(span Span, name string, attrs ...any)
- func DebugPrintf(format string, args ...any)
- func DisableDebug()
- func EnableDebug()
- func GetOperationName(ctx context.Context) string
- func GetSpanID(ctx context.Context) string
- func GetTraceID(ctx context.Context) string
- func GetVersion() string
- func Init(ctx context.Context, opts ...Option) (func(), error)
- func InitWithConfig(ctx context.Context, cfg *Config) (func(), error)
- func IsDebugEnabled() bool
- func IsProduction() bool
- func IsTracingEnabled(ctx context.Context) bool
- func RecordError(ctx context.Context, err error, attrs map[string]any)
- func RegisterQueueFactory(factory func(cfg *Config, subscribers []Subscriber) EventTracker)
- func SetAttribute(ctx context.Context, key string, value any)
- func SetAttributes(ctx context.Context, attrs map[string]any)
- func SetDuration(span Span, start time.Time)
- func SetHTTPRequestAttributes(span Span, method, path, userAgent string)
- func ShouldEnableDebug(debug *bool) bool
- func Trace[T any](ctx context.Context, name string, fn func(context.Context, Span) (T, error)) (T, error)
- func TraceNoError[T any](ctx context.Context, name string, fn func(context.Context, Span) T) T
- func TraceVoid(ctx context.Context, name string, fn func(context.Context, Span) error) error
- func Track(ctx context.Context, event string, properties map[string]any)
- type Config
- type DebugPrinter
- type EventTracker
- type Metric
- type Option
- func WithAdaptiveSampler(opts ...sampling.AdaptiveSamplerOption) Option
- func WithBackend(name string) Option
- func WithBatchTimeout(timeout time.Duration) Option
- func WithCircuitBreaker(failureThreshold, successThreshold int, timeout time.Duration) Option
- func WithDebug(enabled bool) Option
- func WithEndpoint(endpoint string) Option
- func WithEnvironment(env string) Option
- func WithEventBackoff(min, max, reset time.Duration) Option
- func WithEventQueue(size int, flushInterval time.Duration, circuitBreakerThreshold int) Option
- func WithEventRetry(maxRetries int, jitter time.Duration) Option
- func WithInsecure(insecure bool) Option
- func WithMaxExportBatchSize(size int) Option
- func WithMaxQueueSize(size int) Option
- func WithMetricExporters(exporters ...metricSdk.Exporter) Option
- func WithMetricInterval(d time.Duration) Option
- func WithMetrics(enabled bool) Option
- func WithOTLPHeaders(headers map[string]string) Option
- func WithPIIRedaction(opts ...redaction.PIIRedactorOption) Option
- func WithProtocol(protocol Protocol) Option
- func WithRateLimit(rate float64, burst int) Option
- func WithSampler(sampler trace.Sampler) Option
- func WithService(name string) Option
- func WithServiceVersion(version string) Option
- func WithSpanExporters(exporters ...trace.SpanExporter) Option
- func WithSpanProcessors(processors ...trace.SpanProcessor) Option
- func WithSubscribers(subscribers ...Subscriber) Option
- type Protocol
- type Span
- type Subscriber
Examples ¶
Constants ¶
const Version = "0.1.0"
Version is the current version of autolemetry-go.
Variables ¶
This section is empty.
Functions ¶
func AddEvent ¶
AddEvent adds an event to the current span from context. This is a convenience function that doesn't require getting the span first.
func AddEventWithAttributes ¶
AddEventWithAttributes is a convenience function for adding events with attributes.
Example:
autolemetry.AddEventWithAttributes(span, "cache_hit",
"cache.key", "user:123",
"cache.ttl", 3600,
)
func DebugPrintf ¶
DebugPrintf is exported for internal helpers (avoid cycles).
func EnableDebug ¶
func EnableDebug()
EnableDebug enables debug mode, which logs all span operations.
func GetOperationName ¶
GetOperationName returns the operation/span name stored on context by Start/Trace helpers.
func GetSpanID ¶
GetSpanID returns the current span ID as a hex string. Returns empty string if no active span exists.
func GetTraceID ¶
GetTraceID returns the current trace ID as a hex string. Returns empty string if no active span exists.
func GetVersion ¶
func GetVersion() string
GetVersion returns the current version of autolemetry-go.
func Init ¶
Init initializes autolemetry with OpenTelemetry SDK using functional options. Returns a cleanup function that should be called on shutdown.
This is the recommended way to initialize autolemetry for most users.
Example:
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("my-service"),
autolemetry.WithEndpoint("http://localhost:4318"),
)
if err != nil {
log.Fatal(err)
}
defer cleanup()
func InitWithConfig ¶
InitWithConfig initializes autolemetry with a custom Config. This provides advanced users with full control over configuration.
Most users should use Init() with functional options instead.
Example:
cfg := autolemetry.DefaultConfig()
cfg.ServiceName = "my-service"
cfg.Endpoint = "custom:4318"
cfg.Sampler = trace.AlwaysSample() // Custom sampler
cleanup, err := autolemetry.InitWithConfig(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer cleanup()
func IsDebugEnabled ¶
func IsDebugEnabled() bool
IsDebugEnabled returns whether debug mode is enabled.
func IsProduction ¶
func IsProduction() bool
func IsTracingEnabled ¶
IsTracingEnabled checks if tracing is currently enabled. Returns true if a TracerProvider is set and not a no-op provider.
func RecordError ¶
RecordError records an error on the current span from context. This sets the span status to ERROR automatically. This is a convenience function that doesn't require getting the span first.
func RegisterQueueFactory ¶
func RegisterQueueFactory(factory func(cfg *Config, subscribers []Subscriber) EventTracker)
RegisterQueueFactory registers a function to create analytics queues. This is called by the analytics package to avoid import cycles. Users should not call this directly.
func SetAttribute ¶
SetAttribute sets a single attribute on the current span from context. This is a convenience function that doesn't require getting the span first.
func SetAttributes ¶
SetAttributes sets multiple attributes on the current span from context. This is a convenience function that doesn't require getting the span first.
func SetDuration ¶
SetDuration sets the duration of an operation as a span attribute. This is useful for tracking operation performance.
Example:
start := time.Now() // ... do work ... autolemetry.SetDuration(span, start)
func SetHTTPRequestAttributes ¶
SetHTTPRequestAttributes sets common HTTP request attributes on a span. This is a convenience function for HTTP handlers.
Example:
func handler(w http.ResponseWriter, r *http.Request) {
ctx, span := autolemetry.Start(r.Context(), "handleRequest")
defer span.End()
autolemetry.SetHTTPRequestAttributes(span, r)
// ... handle request ...
}
func ShouldEnableDebug ¶
ShouldEnableDebug decides whether debug should be enabled when not explicitly set. If debug is nil, enable in non-production by default.
func Trace ¶
func Trace[T any](ctx context.Context, name string, fn func(context.Context, Span) (T, error)) (T, error)
Trace wraps a function with automatic span lifecycle management. The function receives the updated context and span. If the function returns an error, it's automatically recorded.
Example:
func GetUser(ctx context.Context, id string) (*User, error) {
return autolemetry.Trace(ctx, "GetUser", func(ctx context.Context, span autolemetry.Span) (*User, error) {
span.SetAttribute("user.id", id)
return db.Users.FindByID(ctx, id)
})
}
func TraceNoError ¶
TraceNoError is like Trace but for functions that don't return errors.
func Track ¶
Track sends an analytics event to the global queue (if configured). This is a convenience function that uses the queue created during Init(). If no subscribers were provided during Init(), this function does nothing.
Example:
autolemetry.Track(ctx, "user_signed_up", map[string]any{
"user_id": "123",
"plan": "premium",
})
Types ¶
type Config ¶
type Config struct {
// ServiceName is the name of your service (required)
ServiceName string
// ServiceVersion is the version of your service (optional)
ServiceVersion string
// Environment is the deployment environment (e.g., "production", "staging")
Environment string
// Endpoint is the OTLP endpoint URL (default: "localhost:4318")
Endpoint string
// Protocol is the OTLP protocol to use (http or grpc)
Protocol Protocol
// Insecure controls whether to use insecure connections (default: true for development)
Insecure bool
// Sampler is the trace sampler to use (default: AdaptiveSampler)
Sampler trace.Sampler
// RateLimiter limits span creation rate (optional)
RateLimiter *ratelimit.TokenBucket
// CircuitBreaker protects exporter from overload (optional)
CircuitBreaker *circuitbreaker.CircuitBreaker
// PIIRedactor redacts PII from span attributes (optional)
PIIRedactor *redaction.PIIRedactor
// UseAdaptiveSampler indicates whether adaptive sampling is enabled
UseAdaptiveSampler bool
// Subscribers are event subscribers (PostHog, Mixpanel, etc.)
// If provided, a global event queue will be created automatically.
Subscribers []Subscriber
// BackendPreset enables vendor presets (datadog, honeycomb, grafana, default otlp).
BackendPreset string
// OTLPHeaders are additional headers sent to the exporter (API keys, datasets, etc.).
OTLPHeaders map[string]string
// Additional span exporters beyond the default OTLP exporter.
SpanExporters []trace.SpanExporter
// Additional span processors to attach.
SpanProcessors []trace.SpanProcessor
// Event queue tuning.
EventQueueSize int
EventFlushInterval time.Duration
EventCBThreshold int
EventBackoffMin time.Duration
EventBackoffMax time.Duration
EventCBReset time.Duration
EventMaxRetries int
EventJitter time.Duration
// Batch processor tuning knobs (match TS README).
BatchTimeout time.Duration
MaxQueueSize int
MaxExportBatchSize int
// Debug allows auto detection when nil.
Debug *bool
// Metrics control.
MetricsEnabled bool
MetricExporters []metric.Exporter
MetricInterval time.Duration
}
Config holds autolemetry configuration.
Most users should use the functional options pattern with Init():
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("my-service"),
autolemetry.WithEndpoint("localhost:4318"),
)
Advanced users can create and modify Config directly for more control:
cfg := autolemetry.DefaultConfig() cfg.ServiceName = "my-service" cfg.Endpoint = "custom:4318" // ... customize further cleanup, err := autolemetry.InitWithConfig(ctx, cfg)
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible defaults. You can modify the returned Config and pass it to InitWithConfig.
Example:
cfg := autolemetry.DefaultConfig() cfg.ServiceName = "my-service" cfg.Environment = "production" cleanup, err := autolemetry.InitWithConfig(ctx, cfg)
type DebugPrinter ¶
type DebugPrinter struct {
// contains filtered or unexported fields
}
DebugPrinter provides a structured way to print debug information.
func NewDebugPrinter ¶
func NewDebugPrinter() *DebugPrinter
NewDebugPrinter creates a new debug printer.
func (*DebugPrinter) PrintSpan ¶
func (d *DebugPrinter) PrintSpan(name string, ctx trace.SpanContext, attrs []attribute.KeyValue)
PrintSpan prints span information.
func (*DebugPrinter) PrintTrace ¶
func (d *DebugPrinter) PrintTrace(traceID trace.TraceID, spans []string)
PrintTrace prints trace information.
type EventTracker ¶
type EventTracker interface {
Track(ctx context.Context, event string, properties map[string]any)
Shutdown(ctx context.Context) error
}
EventTracker is an interface for tracking analytics events. This avoids import cycles by not importing the analytics package directly.
type Metric ¶
type Metric struct {
// contains filtered or unexported fields
}
Metric wraps an OTEL meter to provide lightweight counters/histograms with trace correlation.
type Option ¶
type Option func(*Config)
Option is a functional option for configuring autolemetry
func WithAdaptiveSampler ¶
func WithAdaptiveSampler(opts ...sampling.AdaptiveSamplerOption) Option
WithAdaptiveSampler configures the adaptive sampler with custom options.
func WithBackend ¶
WithBackend enables a vendor preset ("datadog", "honeycomb", "grafana", "otlp"). Presets remain OTLP-first and only adjust endpoints/headers.
func WithBatchTimeout ¶
WithBatchTimeout overrides the batch processor timeout.
func WithCircuitBreaker ¶
WithCircuitBreaker enables circuit breaker protection. failureThreshold is the number of failures before opening the circuit. successThreshold is the number of successes needed to close from half-open. timeout is how long to wait before attempting recovery.
func WithEnvironment ¶
WithEnvironment sets the deployment environment
func WithEventBackoff ¶
WithEventBackoff configures per-subscriber backoff and circuit reset.
func WithEventQueue ¶
WithEventQueue configures event queue buffer, flush interval (for retries), and breaker threshold.
func WithEventRetry ¶
WithEventRetry configures max retries (0 = unlimited) and jitter.
func WithInsecure ¶
WithInsecure controls whether to use insecure connections
func WithMaxExportBatchSize ¶
WithMaxExportBatchSize overrides exporter batch size.
func WithMaxQueueSize ¶
WithMaxQueueSize overrides exporter queue size.
func WithMetricExporters ¶
WithMetricExporters appends custom metric exporters.
func WithMetricInterval ¶
WithMetricInterval sets periodic reader interval.
func WithOTLPHeaders ¶
WithOTLPHeaders adds custom OTLP headers (API keys, datasets, etc.).
func WithPIIRedaction ¶
func WithPIIRedaction(opts ...redaction.PIIRedactorOption) Option
WithPIIRedaction enables PII redaction with optional configuration.
func WithProtocol ¶
WithProtocol sets the OTLP protocol (http or grpc)
func WithRateLimit ¶
WithRateLimit enables rate limiting for span creation. rate is the number of spans per second, burst is the maximum burst size.
func WithServiceVersion ¶
WithServiceVersion sets the service version
func WithSpanExporters ¶
func WithSpanExporters(exporters ...trace.SpanExporter) Option
WithSpanExporters appends custom span exporters.
func WithSpanProcessors ¶
func WithSpanProcessors(processors ...trace.SpanProcessor) Option
WithSpanProcessors appends custom span processors.
func WithSubscribers ¶
func WithSubscribers(subscribers ...Subscriber) Option
WithSubscribers sets event subscribers. If provided, a global event queue will be created automatically. The queue will be shut down when the cleanup function from Init() is called.
Example:
cleanup, err := autolemetry.Init(ctx,
autolemetry.WithService("my-service"),
autolemetry.WithSubscribers(
subscribers.NewPostHogSubscriber("phc_..."),
),
)
defer cleanup()
// Use the global Track function
autolemetry.Track(ctx, "user_signed_up", map[string]any{
"user_id": "123",
})
type Span ¶
type Span interface {
// SetAttribute sets an attribute (supports string, int, int64, float64, bool)
SetAttribute(key string, value any)
// AddEvent adds an event to the span
AddEvent(name string, attrs ...attribute.KeyValue)
// SetStatus sets the span status
SetStatus(code codes.Code, description string)
// RecordError records an error and sets span status to ERROR
RecordError(err error)
// End ends the span
End()
// SpanContext returns the span context
SpanContext() trace.SpanContext
// IsRecording returns whether the span is recording
IsRecording() bool
}
Span wraps an OpenTelemetry span with ergonomic helpers
func Start ¶
Start creates a new span and returns the updated context and span. The span should be ended with span.End() or defer span.End().
Example:
func CreateUser(ctx context.Context, data UserData) error {
ctx, span := autolemetry.Start(ctx, "CreateUser")
defer span.End()
span.SetAttribute("user.email", data.Email)
return db.Users.Create(ctx, data)
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
analytics
command
|
|
|
analytics-posthog
command
|
|
|
basic
command
|
|
|
gin-server
command
|
|
|
http-server
command
|
|
|
logging
command
|
|
|
production-example
command
|
|
|
internal
|
|