sentry

package module
v0.0.0-...-93f8639 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2025 License: MIT Imports: 12 Imported by: 0

README

Sentry Adapter for mtlog

Production-ready error tracking and monitoring integration for mtlog with Sentry.

Features

  • 🚀 Automatic Error Tracking - Captures errors with stack traces
  • 📝 Message Template Interpolation - Shows actual values in Sentry UI
  • 🍞 Breadcrumb Collection - Tracks events leading to errors
  • 📦 Efficient Batching - Reduces network overhead
  • 🔄 Retry Logic - Handles transient network failures with exponential backoff
  • 📊 Metrics Collection - Monitor integration health in real-time
  • 🎯 Custom Fingerprinting - Control error grouping strategies
  • Performance Optimized - String builder pooling and stack trace caching
  • 🔧 Environment Variables - Flexible configuration options
  • 🎭 Transaction Tracking - Performance monitoring with spans
  • 💾 Stack Trace Caching - LRU cache for repeated errors
  • 🎲 Advanced Sampling - Multiple strategies to control event volume
  • 🔍 Comprehensive Observability - Track every aspect of the integration

Installation

go get github.com/willibrandon/mtlog/adapters/sentry

Quick Start

package main

import (
    "github.com/willibrandon/mtlog"
    "github.com/willibrandon/mtlog/adapters/sentry"
    "github.com/willibrandon/mtlog/core"
)

func main() {
    // Create Sentry sink
    sentrySink, err := sentry.NewSentrySink(
        "https://your-key@sentry.io/project-id",
        sentry.WithEnvironment("production"),
        sentry.WithRelease("v1.0.0"),
    )
    if err != nil {
        panic(err)
    }
    defer sentrySink.Close()

    // Create logger with Sentry
    logger := mtlog.New(
        mtlog.WithConsole(),
        mtlog.WithSink(sentrySink),
    )

    // Log errors to Sentry
    logger.Error("Database connection failed: {Error}", err)
}

Configuration Options

Basic Configuration
sentrySink, _ := sentry.NewSentrySink(dsn,
    // Environment and release tracking
    sentry.WithEnvironment("production"),
    sentry.WithRelease("v1.2.3"),
    sentry.WithServerName("api-server-1"),
    
    // Level configuration
    sentry.WithMinLevel(core.ErrorLevel),      // Only send errors and above
    sentry.WithBreadcrumbLevel(core.DebugLevel), // Collect debug+ as breadcrumbs
    
    // Sampling
    sentry.WithSampleRate(0.25), // Sample 25% of events
    
    // Batching
    sentry.WithBatchSize(100),
    sentry.WithBatchTimeout(5 * time.Second),
    
    // Breadcrumbs
    sentry.WithMaxBreadcrumbs(50),
)
Retry Configuration

Configure automatic retry for resilient error tracking:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithRetry(3, 1*time.Second),  // 3 retries with exponential backoff
    sentry.WithRetryJitter(0.2),         // 20% jitter to prevent thundering herd
)

The retry mechanism uses exponential backoff:

  • 1st retry: ~1 second
  • 2nd retry: ~2 seconds
  • 3rd retry: ~4 seconds
Metrics Collection

Monitor your Sentry integration health:

// Enable metrics with periodic callback
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithMetricsCallback(30*time.Second, func(m sentry.Metrics) {
        fmt.Printf("Events sent: %d, Failed: %d, Retry rate: %.2f%%\n",
            m.EventsSent, m.EventsFailed,
            float64(m.RetryCount)/float64(m.EventsSent)*100)
    }),
)

// Or retrieve metrics on demand
metrics := sentrySink.Metrics()
fmt.Printf("Average batch size: %.2f\n", metrics.AverageBatchSize)
fmt.Printf("Last flush duration: %v\n", metrics.LastFlushDuration)

Available metrics:

  • Event Statistics: EventsSent, EventsDropped, EventsFailed, EventsRetried
  • Breadcrumb Statistics: BreadcrumbsAdded, BreadcrumbsEvicted
  • Batch Statistics: BatchesSent, AverageBatchSize
  • Performance Metrics: LastFlushDuration, TotalFlushTime
  • Network Statistics: RetryCount, NetworkErrors
Custom Fingerprinting

Control how errors are grouped in Sentry:

// Group by message template only
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithFingerprinter(sentry.ByTemplate()),
)

// Group by template and error type
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithFingerprinter(sentry.ByErrorType()),
)

// Group by template and user ID
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithFingerprinter(sentry.ByProperty("UserId")),
)

// Group by multiple properties
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithFingerprinter(sentry.ByMultipleProperties("TenantId", "Service")),
)

// Custom fingerprinting logic
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithFingerprinter(sentry.Custom(func(event *core.LogEvent) string {
        // Your custom logic here
        return fmt.Sprintf("%s:%v", event.MessageTemplate, event.Properties["RequestId"])
    })),
)
Environment Variables

The adapter supports configuration via environment variables:

export SENTRY_DSN="https://xxx@sentry.io/project"

Then in your code:

// Will use SENTRY_DSN if dsn is empty
sentrySink, _ := sentry.NewSentrySink("",
    sentry.WithEnvironment("production"),
)
Performance Monitoring / Transaction Tracking

Track application performance with distributed tracing:

import (
    "context"
    "github.com/willibrandon/mtlog/adapters/sentry"
)

// Start a transaction
ctx := sentry.StartTransaction(context.Background(), 
    "checkout-flow", "http.request")
defer sentry.GetTransaction(ctx).Finish()

// Track database operations
dbCtx, finishDB := sentry.TraceDatabaseQuery(ctx, 
    "SELECT * FROM orders WHERE id = ?", "orders_db")
err := db.Query(dbCtx, orderID)
finishDB(err)

// Track HTTP requests
httpCtx, finishHTTP := sentry.TraceHTTPRequest(ctx, 
    "POST", "https://payment-api.com/charge")
statusCode, err := client.Post(httpCtx, paymentData)
finishHTTP(statusCode)

// Track cache operations
cacheCtx, finishCache := sentry.TraceCache(ctx, "get", "order:123")
value, hit := cache.Get(cacheCtx, "order:123")
finishCache(hit)

// Measure custom operations
err = sentry.MeasureSpan(ctx, "validate.inventory", func() error {
    return inventory.Validate(items)
})

// Batch operations with metrics
err = sentry.BatchSpan(ctx, "process.items", len(items), func() error {
    return processItems(items)
})

Available tracing functions:

  • StartTransaction - Begin a new transaction
  • StartSpan - Create a child span
  • TraceHTTPRequest - Track HTTP calls
  • TraceDatabaseQuery - Track database operations
  • TraceCache - Track cache hits/misses
  • MeasureSpan - Time any operation
  • BatchSpan - Track batch processing with throughput metrics
  • TransactionMiddleware - Wrap handlers with automatic tracing
Stack Trace Caching

Optimize performance by caching stack traces for repeated errors:

sentrySink, _ := sentry.NewSentrySink(dsn,
    // Configure stack trace cache size (default: 1000)
    sentry.WithStackTraceCacheSize(2000),
    
    // Disable caching if needed
    // sentry.WithStackTraceCacheSize(0),
)

Benefits:

  • Reduced CPU usage - Avoid repeated stack trace extraction
  • Lower memory allocations - Reuse cached stack traces
  • LRU eviction - Automatically manages cache size
  • Thread-safe - Concurrent access supported

Sampling

Control which events are sent to Sentry to manage costs and reduce noise while maintaining visibility into critical issues.

Sampling Strategies
1. Fixed Rate Sampling

Simple percentage-based sampling:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithSampling(0.1), // Sample 10% of events
)
2. Adaptive Sampling

Automatically adjusts sampling rate based on traffic volume:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithAdaptiveSampling(100), // Target 100 events per second
)
  • Reduces sampling during traffic spikes
  • Increases sampling during low traffic
  • Maintains target event rate automatically
3. Priority-Based Sampling

Sample based on event importance:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithPrioritySampling(0.05), // 5% base rate
)
  • Fatal events: Always sampled (100%)
  • Events with errors: Higher priority
  • Events with user context: Medium priority
  • Regular events: Base rate
4. Burst Detection Sampling

Handles traffic bursts with automatic backoff:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithBurstSampling(1000), // Burst threshold: 1000 events/sec
)
  • Normal traffic: Full sampling
  • During burst: Reduced sampling (5-10%)
  • Automatic backoff period
  • Prevents overwhelming Sentry during incidents
5. Group-Based Sampling

Limits events per error group:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithGroupSampling(10, time.Minute), // Max 10 per error type per minute
)
  • Prevents repetitive errors from flooding
  • Maintains visibility into all error types
  • Time-windowed limits
6. Sampling Profiles

Pre-configured profiles for common scenarios:

// Development - No sampling
sentry.WithSamplingProfile(sentry.SamplingProfileDevelopment)

// Production - Balanced sampling with adaptive rates
sentry.WithSamplingProfile(sentry.SamplingProfileProduction)

// High Volume - Aggressive sampling for high-traffic apps
sentry.WithSamplingProfile(sentry.SamplingProfileHighVolume)

// Critical - Minimal sampling, only critical events
sentry.WithSamplingProfile(sentry.SamplingProfileCritical)
7. Custom Sampling Logic

Implement your own sampling decisions:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithCustomSampling(func(event *core.LogEvent) bool {
        // Sample premium users at higher rate
        if userId, ok := event.Properties["UserId"].(int); ok {
            if userId < 1000 { // Premium users
                return rand.Float32() < 0.5 // 50% sampling
            }
            return rand.Float32() < 0.01 // 1% for regular users
        }
        return rand.Float32() < 0.1 // 10% default
    }),
)
Integration with mtlog Sampling

Leverage mtlog's powerful per-message sampling APIs for fine-grained control:

logger := mtlog.New(
    mtlog.WithSink(sentrySink),
)

// Sample every 10th message
logger.Sample(10).Error("Database connection failed", err)

// Sample once per minute
logger.SampleDuration(time.Minute).Warning("Cache miss for key {Key}", key)

// Sample 20% of messages
logger.SampleRate(0.2).Information("User action {Action}", action)

// Sample first 5 occurrences only
logger.SampleFirst(5).Error("Initialization error", err)

// Sample with exponential backoff
logger.SampleBackoff("api-error", 2.0).Error("API rate limit exceeded")

// Conditional sampling
logger.SampleWhen(func() bool { 
    return time.Now().Hour() >= 9 && time.Now().Hour() <= 17 
}, 1).Information("Business hours event")

// Group sampling
logger.SampleGroup("user-errors", 10).Error("User {UserId} validation failed", userId)
Advanced Sampling Configuration

Complete sampling configuration with all options:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithSamplingConfig(&sentry.SamplingConfig{
        Strategy:          sentry.SamplingAdaptive,
        Rate:              0.1,                    // Base rate: 10%
        ErrorRate:         0.5,                    // Error sampling: 50%
        FatalRate:         1.0,                    // Fatal sampling: 100%
        AdaptiveTargetEPS: 100,                    // Target 100 events/sec
        BurstThreshold:    1000,                   // Burst mode above 1000/sec
        GroupSampling:     true,                   // Enable group sampling
        GroupSampleRate:   10,                     // 10 events per group
        GroupWindow:       time.Minute,            // Per minute window
        CustomSampler: func(e *core.LogEvent) bool {
            // Additional custom logic
            return true
        },
    }),
)
Sampling Metrics

Monitor sampling effectiveness:

// Get sampling statistics
metrics := sentrySink.Metrics()
effectiveRate := float64(metrics.EventsSent) / 
    float64(metrics.EventsSent + metrics.EventsDropped) * 100
fmt.Printf("Effective sampling rate: %.1f%%\n", effectiveRate)

Advanced Usage

Filtering Events

Use BeforeSend to filter or modify events:

sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithBeforeSend(func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
        // Don't send events from development
        if event.Environment == "development" {
            return nil
        }
        
        // Redact sensitive data
        if event.Extra["password"] != nil {
            event.Extra["password"] = "[REDACTED]"
        }
        
        return event
    }),
)
Ignoring Specific Errors
sentrySink, _ := sentry.NewSentrySink(dsn,
    sentry.WithIgnoreErrors(
        context.Canceled,
        io.EOF,
    ),
)
Context Enrichment

Enrich events with contextual information:

import sentryctx "github.com/willibrandon/mtlog/adapters/sentry"

// Set user context
ctx := sentryctx.WithUser(ctx, sentry.User{
    ID:       "user-123",
    Username: "john.doe",
    Email:    "john@example.com",
})

// Add tags
ctx = sentryctx.WithTags(ctx, map[string]string{
    "tenant_id": "tenant-456",
    "region":    "us-west-2",
})

// Log with context
logger.WithContext(ctx).Error("Operation failed")

Performance Considerations

The Sentry adapter is optimized for production use:

  1. String Builder Pooling: Reuses string builders to minimize allocations
  2. Batching: Reduces network calls by batching events
  3. Async Processing: Non-blocking event submission
  4. Breadcrumb Buffering: Efficient circular buffer for breadcrumbs
  5. Minimal Overhead: ~170ns for message interpolation

Benchmarks

go test -bench=. -benchmem
Benchmark Results (AMD Ryzen 9 9950X)
BenchmarkRetryCalculation-32               100000000        11.07 ns/op       0 B/op       0 allocs/op
BenchmarkStackTraceCaching-32               20087894        60.74 ns/op      48 B/op       2 allocs/op
BenchmarkMetricsCollection-32              167154866         7.113 ns/op      0 B/op       0 allocs/op
BenchmarkTransactionCreation-32              1992597       652.3 ns/op    1208 B/op       9 allocs/op
BenchmarkMessageInterpolation-32             6992760       178.1 ns/op     136 B/op       4 allocs/op
BenchmarkEventConversion-32                   894856      1322 ns/op      1597 B/op      12 allocs/op
BenchmarkComplexMessageInterpolation-32      3232375       415.1 ns/op     320 B/op       6 allocs/op
BenchmarkBreadcrumbAddition-32               4703395       237.2 ns/op     401 B/op       4 allocs/op
BenchmarkBatchProcessing-32                137846361         8.668 ns/op      8 B/op       0 allocs/op
Performance Highlights
Ultra-Fast Core Operations
  • Retry Calculation: 11.07 ns/op - Zero-allocation exponential backoff
  • Metrics Collection: 7.11 ns/op - Atomic counter updates with no allocations
  • Batch Processing: 8.67 ns/op - Highly optimized batch operations
Efficient Caching & Pooling
  • Stack Trace Caching: 60.74 ns/op - LRU cache with ~95% hit rate in production
  • Message Interpolation: 178.1 ns/op - String builder pooling reduces GC pressure
  • Complex Templates: 415.1 ns/op - Handles multiple properties efficiently
Transaction & Performance Monitoring
  • Transaction Creation: 652.3 ns/op - Lightweight span creation for tracing
  • Breadcrumb Addition: 237.2 ns/op - Fast circular buffer operations
  • Event Conversion: 1.32 μs - Complete Sentry event with all metadata

Testing

Unit Tests
cd adapters/sentry
go test -v ./...
go test -race -v ./...
Integration Tests (Local Sentry)
# Start Sentry infrastructure
./scripts/setup-integration-test.sh

# Run integration tests
go test -tags=integration -v ./...

# Verify pipeline
./scripts/verify-sentry-pipeline.sh

Examples

See the examples directory for complete, runnable examples:

Each example includes:

  • Complete, runnable code
  • Detailed comments explaining each feature
  • Simulated scenarios demonstrating real-world usage
  • Performance considerations and best practices

Troubleshooting

Enable Debug Logging
import "github.com/willibrandon/mtlog/selflog"

// Enable self-diagnostics
selflog.Enable(os.Stderr)
defer selflog.Disable()

// Your Sentry configuration
sentrySink, _ := sentry.NewSentrySink(dsn)
Common Issues
  1. Events not appearing in Sentry

    • Check DSN is correct
    • Verify network connectivity
    • Enable selflog for diagnostics
    • Check sample rate isn't too low
  2. High memory usage

    • Reduce batch size
    • Lower max breadcrumbs
    • Check for event flooding
  3. Slow performance

    • Enable batching
    • Adjust batch timeout
    • Use sampling for high-volume events

License

MIT License - see LICENSE file for details.

Documentation

Overview

Package sentry provides a Sentry integration sink for mtlog. It automatically tracks errors, captures stack traces, and provides breadcrumb support for production error monitoring.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BatchSpan

func BatchSpan(ctx context.Context, operation string, itemCount int, fn func() error) error

BatchSpan creates a span for batch operations with item count tracking.

func ContextsFromContext

func ContextsFromContext(ctx context.Context) map[string]interface{}

ContextsFromContext extracts Sentry contexts from the context.

func GetSpan

func GetSpan(ctx context.Context) *sentry.Span

GetSpan retrieves the current span from context.

func GetTransaction

func GetTransaction(ctx context.Context) *sentry.Span

GetTransaction retrieves the current transaction from context.

func MeasureSpan

func MeasureSpan(ctx context.Context, operation string, fn func() error) error

MeasureSpan measures the duration of an operation and records it as a span.

func RecordBreadcrumbInTransaction

func RecordBreadcrumbInTransaction(ctx context.Context, breadcrumb sentry.Breadcrumb)

RecordBreadcrumbInTransaction adds a breadcrumb to the current transaction.

func SetSpanData

func SetSpanData(ctx context.Context, key string, value interface{})

SetSpanData sets data on the current span.

func SetSpanStatus

func SetSpanStatus(ctx context.Context, status string)

SetSpanStatus sets the status of the current span.

func SetSpanTag

func SetSpanTag(ctx context.Context, key, value string)

SetSpanTag sets a tag on the current span.

func StartSpan

func StartSpan(ctx context.Context, operation string) (context.Context, func())

StartSpan starts a new span within the current transaction.

func StartTransaction

func StartTransaction(ctx context.Context, name string, operation string) context.Context

StartTransaction starts a new Sentry transaction and returns a context with it.

func TagsFromContext

func TagsFromContext(ctx context.Context) map[string]string

TagsFromContext extracts Sentry tags from the context.

func TraceCache

func TraceCache(ctx context.Context, operation, key string) (context.Context, func(hit bool))

TraceCache creates a span for cache operations.

func TraceDatabaseQuery

func TraceDatabaseQuery(ctx context.Context, query string, dbName string) (context.Context, func(error))

TraceDatabaseQuery creates a span for a database query.

func TraceHTTPRequest

func TraceHTTPRequest(ctx context.Context, method, url string) (context.Context, func(statusCode int))

TraceHTTPRequest creates a span for an HTTP request.

func TransactionMiddleware

func TransactionMiddleware(name string) func(context.Context, func(context.Context) error) error

TransactionMiddleware wraps a handler with transaction tracking.

func UserFromContext

func UserFromContext(ctx context.Context) (sentry.User, bool)

UserFromContext extracts Sentry user information from the context.

func WithContext

func WithContext(ctx context.Context, key string, data interface{}) context.Context

WithContext adds Sentry context data to the context.

func WithSentry

func WithSentry(dsn string, opts ...Option) (core.LogEventSink, error)

WithSentry creates a new Sentry sink with the given DSN and options. This is a convenience function that returns a core.LogEventSink.

func WithTags

func WithTags(ctx context.Context, tags map[string]string) context.Context

WithTags adds Sentry tags to the context.

func WithTransaction

func WithTransaction(ctx context.Context, name string, operation string) context.Context

WithTransaction creates a transaction-aware logger context.

func WithUser

func WithUser(ctx context.Context, user sentry.User) context.Context

WithUser adds Sentry user information to the context.

Types

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

BreadcrumbBuffer is a thread-safe ring buffer for storing breadcrumbs. It automatically evicts old breadcrumbs based on age and capacity.

func NewBreadcrumbBuffer

func NewBreadcrumbBuffer(maxSize int) *BreadcrumbBuffer

NewBreadcrumbBuffer creates a new breadcrumb buffer with the specified capacity.

func (b *BreadcrumbBuffer) Add(breadcrumb sentry.Breadcrumb)

Add adds a breadcrumb to the buffer.

func (b *BreadcrumbBuffer) Clear()

Clear removes all breadcrumbs from the buffer.

func (b *BreadcrumbBuffer) GetAll() []*sentry.Breadcrumb

GetAll returns all valid breadcrumbs in chronological order.

func (b *BreadcrumbBuffer) SetMaxAge(maxAge time.Duration)

SetMaxAge sets the maximum age for breadcrumbs.

func (b *BreadcrumbBuffer) Size() int

Size returns the current number of breadcrumbs in the buffer.

type Fingerprinter

type Fingerprinter func(*core.LogEvent) []string

Fingerprinter is a function that generates fingerprints for error grouping.

func ByErrorType

func ByErrorType() Fingerprinter

ByErrorType groups by template and error type. This creates separate groups for different error types even if they have the same message template.

func ByMultipleProperties

func ByMultipleProperties(propertyNames ...string) Fingerprinter

ByMultipleProperties groups by template and multiple property values. This allows for fine-grained grouping based on multiple dimensions.

func ByProperty

func ByProperty(propertyName string) Fingerprinter

ByProperty groups by template and a specific property value. This is useful for grouping by user ID, tenant ID, or other identifiers.

func ByTemplate

func ByTemplate() Fingerprinter

ByTemplate groups errors by message template only. This is useful when you want all instances of the same log message to be grouped together regardless of the actual values.

func Custom

func Custom(fn func(*core.LogEvent) string) Fingerprinter

Custom creates a fingerprinter that uses a custom function to generate fingerprints. The function receives the event and should return a unique identifier string.

type Metrics

type Metrics struct {
	// Event statistics
	EventsSent    int64
	EventsDropped int64
	EventsFailed  int64
	EventsRetried int64

	// Breadcrumb statistics
	BreadcrumbsAdded   int64
	BreadcrumbsEvicted int64

	// Batch statistics
	BatchesSent      int64
	AverageBatchSize float64

	// Performance metrics
	LastFlushDuration time.Duration
	TotalFlushTime    time.Duration

	// Network statistics
	RetryCount    int64
	NetworkErrors int64
}

Metrics provides runtime statistics for the Sentry sink.

type Option

type Option func(*SentrySink)

Option configures the Sentry sink.

func WithAdaptiveSampling

func WithAdaptiveSampling(targetEPS uint64) Option

WithAdaptiveSampling creates an adaptive sampling configuration

func WithAttachStacktrace

func WithAttachStacktrace(attach bool) Option

WithAttachStacktrace enables stack trace attachment for all levels.

func WithBatchSize

func WithBatchSize(size int) Option

WithBatchSize sets the batch size for event sending.

func WithBatchTimeout

func WithBatchTimeout(timeout time.Duration) Option

WithBatchTimeout sets the timeout for batch sending.

func WithBeforeSend

func WithBeforeSend(processor sentry.EventProcessor) Option

WithBeforeSend sets a function to modify or filter events before sending. Return nil to drop the event.

func WithBreadcrumbLevel

func WithBreadcrumbLevel(level core.LogEventLevel) Option

WithBreadcrumbLevel sets the minimum level for breadcrumb collection. Events at or above this level but below MinLevel become breadcrumbs.

func WithBurstSampling

func WithBurstSampling(threshold uint64) Option

WithBurstSampling creates a burst-aware sampling configuration

func WithCustomSampling

func WithCustomSampling(sampler func(event *core.LogEvent) bool) Option

WithCustomSampling uses a custom sampling function

func WithEnvironment

func WithEnvironment(env string) Option

WithEnvironment sets the environment (e.g., "production", "staging").

func WithFingerprinter

func WithFingerprinter(f Fingerprinter) Option

WithFingerprinter sets a custom fingerprinting function for error grouping.

func WithGroupSampling

func WithGroupSampling(eventsPerGroup uint64, window time.Duration) Option

WithGroupSampling enables per-error-group sampling

func WithIgnoreErrors

func WithIgnoreErrors(errors ...error) Option

WithIgnoreErrors configures errors to ignore.

func WithMaxBreadcrumbs

func WithMaxBreadcrumbs(max int) Option

WithMaxBreadcrumbs sets the maximum number of breadcrumbs to keep.

func WithMetrics

func WithMetrics(enabled bool) Option

WithMetrics enables or disables metrics collection.

func WithMetricsCallback

func WithMetricsCallback(interval time.Duration, callback func(Metrics)) Option

WithMetricsCallback sets a callback that's called periodically with metrics.

func WithMinLevel

func WithMinLevel(level core.LogEventLevel) Option

WithMinLevel sets the minimum level for events to be sent to Sentry. Events below this level may still be captured as breadcrumbs.

func WithPrioritySampling

func WithPrioritySampling(baseRate float32) Option

WithPrioritySampling creates a priority-based sampling configuration

func WithRelease

func WithRelease(release string) Option

WithRelease sets the release version.

func WithRetry

func WithRetry(maxRetries int, backoff time.Duration) Option

WithRetry configures retry behavior for failed event submissions. maxRetries: maximum number of retry attempts (0 = no retries) backoff: base delay between retries (will be exponentially increased)

func WithRetryJitter

func WithRetryJitter(jitter float64) Option

WithRetryJitter sets the jitter factor for retry delays (0.0 to 1.0). Jitter helps prevent thundering herd problems.

func WithSampleRate

func WithSampleRate(rate float64) Option

WithSampleRate sets the sample rate (0.0 to 1.0).

func WithSampling

func WithSampling(rate float32) Option

WithSampling creates a basic fixed-rate sampling configuration

func WithSamplingConfig

func WithSamplingConfig(config *SamplingConfig) Option

WithSamplingConfig applies a complete sampling configuration

func WithSamplingProfile

func WithSamplingProfile(profile SamplingProfile) Option

WithSamplingProfile applies a predefined sampling profile

func WithServerName

func WithServerName(name string) Option

WithServerName sets the server name.

func WithStackTraceCacheSize

func WithStackTraceCacheSize(size int) Option

WithStackTraceCacheSize sets the size of the stack trace cache. A larger cache can improve performance when the same errors occur repeatedly. Set to 0 to disable caching.

type SamplingConfig

type SamplingConfig struct {
	// Strategy defines the sampling approach
	Strategy SamplingStrategy

	// Rate is the base sampling rate (0.0 to 1.0)
	Rate float32

	// ErrorRate is the sampling rate for errors (defaults to 1.0)
	ErrorRate float32

	// FatalRate is the sampling rate for fatal events (defaults to 1.0)
	FatalRate float32

	// AdaptiveTargetEPS is the target events per second for adaptive sampling
	AdaptiveTargetEPS uint64

	// BurstThreshold is the events/sec threshold to trigger burst mode
	BurstThreshold uint64

	// CustomSampler is a function for custom sampling logic
	CustomSampler func(event *core.LogEvent) bool

	// GroupSampling enables sampling by error fingerprint/group
	GroupSampling bool

	// GroupSampleRate is events per group per time window
	GroupSampleRate uint64

	// GroupWindow is the time window for group sampling
	GroupWindow time.Duration
}

SamplingConfig configures sampling behavior for the Sentry sink

func DefaultSamplingConfig

func DefaultSamplingConfig() *SamplingConfig

DefaultSamplingConfig returns a sensible default sampling configuration

type SamplingProfile

type SamplingProfile string

SamplingProfile represents a predefined sampling configuration

const (
	// SamplingProfileDevelopment - verbose sampling for development
	SamplingProfileDevelopment SamplingProfile = "development"

	// SamplingProfileProduction - balanced sampling for production
	SamplingProfileProduction SamplingProfile = "production"

	// SamplingProfileHighVolume - aggressive sampling for high-volume apps
	SamplingProfileHighVolume SamplingProfile = "high-volume"

	// SamplingProfileCritical - minimal sampling, only critical events
	SamplingProfileCritical SamplingProfile = "critical"
)

type SamplingStrategy

type SamplingStrategy string

SamplingStrategy defines different sampling strategies for Sentry events

const (
	// SamplingOff disables sampling - all events are sent
	SamplingOff SamplingStrategy = "off"

	// SamplingFixed uses a fixed rate for all events
	SamplingFixed SamplingStrategy = "fixed"

	// SamplingAdaptive adjusts rate based on volume
	SamplingAdaptive SamplingStrategy = "adaptive"

	// SamplingPriority samples based on event severity
	SamplingPriority SamplingStrategy = "priority"

	// SamplingBurst handles burst scenarios with backoff
	SamplingBurst SamplingStrategy = "burst"

	// SamplingCustom uses a custom sampling function
	SamplingCustom SamplingStrategy = "custom"
)

type SentrySink

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

SentrySink sends log events to Sentry for error tracking and monitoring. It supports batching, breadcrumb collection, and custom fingerprinting.

func NewSentrySink

func NewSentrySink(dsn string, opts ...Option) (*SentrySink, error)

NewSentrySink creates a new Sentry sink with the given DSN and options.

func (*SentrySink) Close

func (s *SentrySink) Close() error

Close flushes any pending events and closes the sink.

func (*SentrySink) Emit

func (s *SentrySink) Emit(event *core.LogEvent)

Emit sends a log event to Sentry.

func (*SentrySink) Metrics

func (s *SentrySink) Metrics() Metrics

Metrics returns a snapshot of the current metrics.

Directories

Path Synopsis
examples
basic command
breadcrumbs command
context command
metrics command
performance command
retry command
sampling command

Jump to

Keyboard shortcuts

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