Skip to content

bold-minds/obs

# obs

A powerful Go observability library that combines intelligent sampling, business-aware tracking, and seamless OpenTelemetry integration.

Features

🎯 Intelligent Sampling

  • Context-aware sampling based on operation type, error status, and endpoint volume
  • Configurable sampling rates for different operation types (database, user events, errors)
  • High-volume endpoint detection with reduced sampling rates

📊 Generic Event System

  • Flexible, domain-agnostic event tracking for any business context
  • Pre-built event builders for common scenarios (data ops, queries, errors, etc.)
  • Rich context attributes with type-safe attribute builders
  • Backward-compatible legacy functions for existing codebases

🔧 Multiple Abstraction Levels

  • Low-level span management for fine-grained control
  • High-level TrackedOperation for concise business logic tracing
  • Middleware-friendly API design

🚀 Production Ready

  • Comprehensive configuration with validation
  • Environment variable support
  • Graceful shutdown and error handling
  • Memory and performance metrics

Quick Start

Installation

go get github.com/bold-minds/obs

Basic Usage

package main

import (
    "context"
    "log"
    
    "github.com/bold-minds/obs"
)

func main() {
    ctx := context.Background()
    
    // Initialize from environment variables
    if err := obs.InitFromEnv(ctx); err != nil {
        log.Fatal(err)
    }
    defer obs.Shutdown(ctx)
    
    // Track a business operation
    ctx, op := obs.TrackOperation(ctx, "api", "user_signup")
    defer op.Success(1)
    
    // Your business logic here
    processUserSignup()
}

Configuration

Set environment variables:

export OBS_ENABLED=true
export OBS_API_KEY=your_honeycomb_api_key
export OBS_DATASET=your_dataset
export OBS_SERVICE_NAME=your_service
export OBS_ENVIRONMENT=production

Or configure programmatically:

cfg := obs.Config{
    Enabled:     true,
    APIKey:      "your_api_key",
    Dataset:     "your_dataset",
    ServiceName: "your_service",
    Environment: "production",
    Sampling: obs.SamplingConfig{
        TraceSampleRate:      25,  // 25% of traces
        ErrorSampleRate:      100, // 100% of errors
        DatabaseSampleRate:   10,  // 10% of DB operations
        UserEventSampleRate:  50,  // 50% of user events
        HighVolumeEndpoints:  []string{"Find", "List"},
        HighVolumeSampleRate: 5,   // 5% for high-volume endpoints
    },
}

if err := obs.Init(ctx, cfg); err != nil {
    log.Fatal(err)
}

Usage Examples

Business Tracking

// Track data operations
obs.TrackDataOperationResult(ctx, "save", "tenant_123", 5, 100, true, false)

// Track user activity
obs.TrackUserActivity(ctx, "api_call", "tenant_123", 1024, 150, true)

// Track query performance
obs.TrackQueryPerformance(ctx, "find_users", 45, 25, true, false)

Advanced Tracing

// Manual span management
ctx, span := obs.StartSpan(ctx, "business", "complex_operation")
defer span.End()

obs.AddBusinessContext(span, "tenant_123", 5, "data_migration")
obs.AddMemoryMetrics(span)

// Tracked operations with error handling
ctx, op := obs.TrackOperationWithError(ctx, "critical", "payment_processing")
if err := processPayment(); err != nil {
    op.Error(err, "payment_failed")
    return
}
op.Success(1)

Database Operations

ctx, span := obs.TrackDatabaseOperation(ctx, "query", "find_users", 512)
defer func() {
    obs.FinishSpanWithResult(span, time.Since(start), resultCount, err)
}()

// Execute your database query
results, err := db.Query("MATCH (u:User) RETURN u")

Migration from Original Code

This library maintains 100% API compatibility with the original observe package. Simply update your imports:

// Before
import "your_project/observe"

// After  
import "github.com/bold-minds/obs"

All function signatures and behavior remain identical, ensuring zero migration friction.

Configuration Reference

Environment Variables

Variable Description Default
OBS_ENABLED Enable/disable observability false
OBS_API_KEY Honeycomb API key Required when enabled
OBS_DATASET Honeycomb dataset default
OBS_SERVICE_NAME Service name service
OBS_ENVIRONMENT Environment (dev/staging/prod) development
OBS_TRACE_SAMPLE_RATE Base trace sampling rate (1-100) 100
OBS_ERROR_SAMPLE_RATE Error sampling rate (1-100) 100
OBS_DATABASE_SAMPLE_RATE Database operation sampling (1-100) 100
OBS_USER_EVENT_SAMPLE_RATE User event sampling (1-100) 100
OBS_HIGH_VOLUME_ENDPOINTS Comma-separated list of endpoints Find,Save
OBS_HIGH_VOLUME_SAMPLE_RATE Sampling rate for high-volume endpoints 25

Sampling Strategy

The library uses intelligent sampling to manage event volume:

  1. Error Priority: Errors are sampled at higher rates to ensure visibility
  2. Operation Type: Different rates for database, user events, and general operations
  3. High-Volume Detection: Reduced sampling for read-heavy endpoints
  4. Context Awareness: Sampling decisions consider operation context

Architecture

obs/
├── config/          # Configuration management
├── sampling/        # Intelligent sampling logic
├── tracing/         # Core tracing utilities  
├── business/        # Business domain tracking
├── providers/       # Backend integrations (Honeycomb)
├── obs.go          # Main client API
└── observe.go      # Compatibility layer

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Submit a pull request

License

MIT License - see LICENSE file for details.

About

OpenTelemetry-based observability for Go — tracing, sampling, and business events with Honeycomb export.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages