### Lapsoss Backtrace Code Context Example (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/backtrace_processing.md Illustrates the structure of extracted code context around an error line. It shows `pre_context`, `context_line`, and `post_context` arrays, providing source code snippets for debugging. ```ruby # Given an error at line 42: { pre_context: [ "39: def process_payment(amount)", "40: validate_amount(amount)", "41: " ], context_line: "42: charge_card(amount)", post_context: [ "43: send_receipt", "44: end", "45:" ] } ``` -------------------------------- ### Direct Lapsoss Backtrace Processing Usage (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/backtrace_processing.md Provides an example of using `Lapsoss::BacktraceProcessor` directly to process an exception, including options like `follow_cause` and `skip_context`. It also shows how to access details of each processed frame. ```ruby # Create a processor instance processor = Lapsoss::BacktraceProcessor.new # Process an exception frames = processor.process_exception(exception) # Process with options frames = processor.process_exception(exception, follow_cause: true, # Follow exception cause chain skip_context: false # Include code context ) # Access frame details frames.each do |frame| puts "#{frame.filename}:#{frame.lineno} in #{frame.method}" puts " Application code: #{frame.in_app}" if frame.has_context? puts " Context: #{frame.context_line}" end end ``` -------------------------------- ### Ruby Lapsoss Configuration Helper for New Adapters Source: https://github.com/seuros/lapsoss/blob/master/TODO.md Illustrates how to add a configuration helper method to Lapsoss for integrating a new service adapter. This method, `use_your_service`, allows users to easily instantiate and register a new adapter with custom settings. ```ruby # lib/lapsoss/configuration.rb (add method) def use_your_service(name: :your_service, **settings) adapter = Adapters::YourServiceAdapter.new(name, settings) Registry.instance.register_adapter(adapter) end ``` -------------------------------- ### Configure Asynchronous Mode and Thread Pool in Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Demonstrates how to configure Lapsoss for asynchronous processing. The example shows setting `config.async = true` and notes that the thread pool size is automatically managed. ```ruby Lapsoss.configure do |config| config.async = true # Thread pool size is automatically managed end ``` -------------------------------- ### Automatic Rails.error Integration with Lapsoss and AppSignal Source: https://github.com/seuros/lapsoss/blob/master/README.md This example demonstrates the recommended way to integrate Lapsoss with Rails, specifically using the `Rails.error` API. It shows how to configure Lapsoss in an initializer to automatically capture all errors handled by `Rails.error` when using AppSignal as the backend. ```ruby # config/initializers/lapsoss.rb Lapsoss.configure do |config| config.use_appsignal(push_api_key: ENV['APPSIGNAL_KEY']) end # That's it! All Rails errors are automatically captured # Works with Rails.error.handle, Rails.error.record, Rails.error.report # No code changes needed - just configure and go ``` -------------------------------- ### Vendor Lock-in vs. Lapsoss Gem Inclusion Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This example contrasts the traditional approach of individually requiring vendor-specific SDKs (like Sentry and AppSignal) with the Lapsoss approach. Lapsoss aims to reduce bundle size by providing a single gem that supports multiple vendors through adapters. ```ruby # Instead of this vendor lock-in nightmare: gem 'sentry-ruby' # 556KB for one vendor gem 'appsignal' # 1.2MB for another vendor # You get this: gem 'lapsoss' # 256KB with adapters for ALL vendors! ``` -------------------------------- ### Multi-Adapter Lapsoss Setup (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Configure Lapsoss with multiple named adapters for different purposes: Sentry for general errors, Rollbar for business events, and a local logger for backup. This allows for flexible routing and handling of different types of events. ```ruby Lapsoss.configure do |config| # Named adapters for different purposes config.use_sentry(name: :errors, dsn: ENV['SENTRY_DSN']) config.use_rollbar(name: :business_events, access_token: ENV['ROLLBAR_TOKEN']) config.use_logger(name: :local_backup) # Local file backup end ``` -------------------------------- ### Test Lapsoss Error Handling in Rails Console Source: https://github.com/seuros/lapsoss/blob/master/README.md Provides a comprehensive example of how to test Lapsoss integration within the Rails console. It demonstrates configuring Lapsoss with the logger adapter for immediate output, testing error capture (`Rails.error.handle`), error recording (`Rails.error.record`), and manual error reporting with context. ```ruby # Configure Lapsoss with the logger adapter for immediate visibility Lapsoss.configure do |config| config.use_logger(name: :console_test) config.async = false # Synchronous for immediate output config.debug = true # Verbose logging end # Create a class that demonstrates error handling class Liberation def self.liberate! Rails.error.handle do raise StandardError, "Freedom requires breaking chains!" end puts "āœ… Continued execution after error" end def self.revolt! Rails.error.record do raise RuntimeError, "Revolution cannot be stopped!" end puts "This won't print - error was re-raised" end end # Test error capture (error is swallowed) Liberation.liberate! # You'll see the error logged but execution continues # Test error recording (error is re-raised) begin Liberation.revolt! rescue => e puts "Caught re-raised error: #{e.message}" end # Manual error reporting with context begin 1 / 0 rescue => e Rails.error.report(e, context: { user_id: 42, action: "console_test" }) end # Check what was captured puts "\nšŸŽ‰ Lapsoss captured all errors through Rails.error!" ``` -------------------------------- ### Install Lapsoss Gem Source: https://github.com/seuros/lapsoss/blob/master/README.md This code snippet shows the standard method for adding the Lapsoss gem to a Rails application's Gemfile, ensuring it's included in the project's dependencies. ```ruby gem 'lapsoss' ``` -------------------------------- ### Ruby: Creating a Custom Lapsoss Adapter Source: https://github.com/seuros/lapsoss/blob/master/README.md Shows how to create a custom error reporting adapter for Lapsoss by extending the base adapter class. This involves implementing the 'capture' method to send event data to a custom service. The example uses an HttpClient to POST error data. ```ruby class MyAdapter < Lapsoss::Adapters::Base def capture(event) # Send to your service HttpClient.post("/errors", event.to_h) end end Lapsoss::Registry.register(:my_service, MyAdapter) ``` -------------------------------- ### Faraday Middleware Chain with Multiple SDKs in Ruby Source: https://github.com/seuros/lapsoss/blob/master/STORY.md Demonstrates how installing multiple error tracking SDKs can lead to a deeply nested chain of Faraday middleware for simple HTTP requests. Each SDK's middleware acts as a 'passport control' point, adding overhead and telemetry data, significantly increasing the latency of API calls. ```ruby # Making a simple API call with multiple SDKs installed: HTTP.get("https://api.example.com/users") Ć¢ā€ ā€œ Airbrake Faraday Middleware (Passport Control #1) Ć¢ā€ ā€œ AppSignal Faraday Middleware (Passport Control #2) Ć¢ā€ ā€œ Bugsnag Faraday Middleware (Passport Control #3) Ć¢ā€ ā€œ Ć¢ā€ā€Ć¢ā€ā‚¬Ć¢ā€ā‚¬ Sentry Faraday Middleware (Final Passport Control) Ć¢ā€ ā€œ Your actual HTTP request finally happens Ć¢ā€ ā€œ Response comes back through ALL 5 checkpoints again! ``` -------------------------------- ### Setting User Context in Web Application Controllers (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Provides an example of integrating Lapsoss into a Rails controller using a `before_action` filter. This pattern ensures that user-specific context is correctly set for each request thread, leveraging Lapsoss's thread-local scope management for isolated request data. ```ruby # Each request thread has isolated scope class ApplicationController < ActionController::Base before_action :set_user_context private def set_user_context Lapsoss.current_scope.user = { id: current_user.id, email: current_user.email } end end ``` -------------------------------- ### Configure Lapsoss with a Single Adapter Source: https://context7.com/seuros/lapsoss/llms.txt Configure Lapsoss to use a single error tracking adapter in a Rails initializer. This setup includes options for asynchronous processing, sample rate, environment/release tracking, and transport configurations like timeout and retries. ```ruby # config/initializers/lapsoss.rb Lapsoss.configure do |config| # Single adapter setup config.use_sentry(dsn: ENV['SENTRY_DSN']) # Async processing for better performance config.async = true # Sample rate (1.0 = 100%, 0.25 = 25%) config.sample_rate = 1.0 # Environment and release tracking config.environment = Rails.env config.release = "v1.2.3" # Transport configuration config.transport_timeout = 10 config.transport_max_retries = 3 end ``` -------------------------------- ### Ruby Adapter Structure for Error Tracking Services Source: https://github.com/seuros/lapsoss/blob/master/TODO.md Defines the basic structure for a new adapter class within the Lapsoss system. It includes initialization, event capturing, payload building, and sending data to the respective error tracking service, along with error handling. This serves as a template for developers creating new adapters. ```ruby module Lapsoss module Adapters class YourServiceAdapter < Base def initialize(name = :your_service, settings = {}) super(name, settings) @api_key = settings[:api_key] @endpoint = settings[:endpoint] || "https://api.yourservice.com" # ... other initialization end def capture(event) # Transform Lapsoss event to your service's format payload = build_payload(event) # Send to your service send_to_service(payload) rescue => e handle_delivery_error(e) false end private def build_payload(event) # Transform the event to your service's expected format # See event.rb for available fields end def send_to_service(payload) # HTTP request or SDK call to your service end end end end ``` -------------------------------- ### Scoping Background Jobs with `with_scope` (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Shows a practical example of using `Lapsoss.with_scope` within a background job to add job-specific context. This ensures that any exceptions captured during job processing include relevant information like the job name and ID, aiding in debugging distributed systems. ```ruby class ProcessPaymentJob def perform(payment_id) Lapsoss.with_scope(tags: { job: "process_payment", payment_id: payment_id }) do # Job processing logic # Any exceptions will include the job context end end end ``` -------------------------------- ### Rails.error Usage with Lapsoss Context Source: https://github.com/seuros/lapsoss/blob/master/README.md This example shows how Lapsoss integrates seamlessly with Rails' native error handling. When `Rails.error.handle` is used, Lapsoss automatically captures the exception and includes the provided context, such as `user_id`. ```ruby # It just works with Rails.error: Rails.error.handle(context: {user_id: current_user.id}) do risky_operation end # Automatically captured by whatever service you configured ``` -------------------------------- ### Gemfile Dependency Conflict in Ruby Error Tracking Source: https://github.com/seuros/lapsoss/blob/master/STORY.md Illustrates a common issue in Ruby applications where installing multiple error tracking SDKs can lead to conflicts. Each SDK may monkey-patch the same methods or instrument existing instrumentation, creating a recursive monitoring loop and unpredictable behavior based on gem loading order. ```ruby # Gemfile disaster waiting to happen gem 'sentry-ruby' gem 'appsignal' gem 'airbrake' ``` ```ruby # What you think happens: Rails → Instrumentation → Error Tracker # What actually happens (gems load alphabetically!): Rails → Rails Instrumentation Ć¢ā€ ā€œ Ć¢ā€ā€Ć¢ā€ā‚¬Ć¢ā€ā‚¬ Airbrake loads first, patches everything Ć¢ā€ā€Ć¢ā€ā‚¬Ć¢ā€ā‚¬ AppSignal loads second, patches Airbrake's patches Ć¢ā€ā€Ć¢ā€ā‚¬Ć¢ā€ā‚¬ Bugsnag loads third, patches both above Ć¢ā€ā€Ć¢ā€ā‚¬Ć¢ā€ā‚¬ Sentry loads last, RULES THEM ALL (patches everyone's patches) # Result: Sentry wins by alphabetical order! # The last to load becomes the outer wrapper # Everyone else is trapped inside Sentry's instrumentation # Sentry is now monitoring all the other monitors... ``` -------------------------------- ### Configure Lapsoss with Multiple Adapters Source: https://context7.com/seuros/lapsoss/llms.txt Configure Lapsoss to use multiple error tracking adapters simultaneously. This is useful for vendor migration, A/B testing, or meeting regional compliance requirements. Examples include setting up primary and secondary services, local logging, and regional-specific adapters. ```ruby Lapsoss.configure do |config| # Primary production service config.use_sentry(name: :production, dsn: ENV['SENTRY_DSN']) # Secondary service for comparison config.use_rollbar(name: :backup, access_token: ENV['ROLLBAR_TOKEN']) # Local file logging for development config.use_logger(name: :local) # Regional compliance example config.use_telebugs(name: :eu_service, dsn: ENV['EU_DSN']) config.use_appsignal(name: :us_service, push_api_key: ENV['US_KEY']) end ``` -------------------------------- ### Zero-Downtime Vendor Migration Strategy with Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/README.md This outlines a step-by-step process for migrating error reporting vendors without downtime. It involves adding Lapsoss alongside the existing setup, configuring dual reporting, gradually replacing old calls with Lapsoss calls, and finally removing the old gem. ```ruby # Step 1: Add Lapsoss alongside your current setup gem 'lapsoss' gem 'bugsnag' # Keep your existing gem for now # Step 2: Configure dual reporting Lapsoss.configure do |config| config.use_bugsnag(api_key: ENV['BUGSNAG_KEY']) config.use_telebugs(dsn: ENV['TELEBUGS_DSN']) end # Step 3: Gradually replace Bugsnag calls # Old: Bugsnag.notify(e) # New: Lapsoss.capture_exception(e) # Step 4: Remove bugsnag gem when ready # Your app keeps running, now on Telebugs ``` -------------------------------- ### Apply Common Lapsoss Error Filtering Patterns in Ruby Source: https://github.com/seuros/lapsoss/blob/master/README.md Provides examples of common Lapsoss error filtering configurations for Rails applications. This includes excluding development/test-specific errors, user input validation errors, and bot traffic, using `add_exclusion` with exception types or custom lambda functions. ```ruby # Development/Test exclusions if Rails.env.development? config.exclusion_filter.add_exclusion(:exception, "RSpec::Expectations::ExpectationNotMetError") config.exclusion_filter.add_exclusion(:exception, "Minitest::Assertion") end # User input errors (if you don't want to track them) config.exclusion_filter.add_exclusion(:exception, "ActiveRecord::RecordInvalid") config.exclusion_filter.add_exclusion(:exception, "ActionController::ParameterMissing") # Bot traffic (if you want to exclude it) config.exclusion_filter.add_exclusion(:custom, lambda do |event| request = event.context[:request] request && request[:user_agent]&.match?(/googlebot|bingbot/i) end) ``` -------------------------------- ### Clear Thread-Local Scope Data in Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Provides an example of how to manually clear accumulated scope data in long-running background threads using Lapsoss. This is important for preventing memory buildup in threads that do not exit. ```ruby # In long-running background threads loop do Lapsoss.current_scope.clear # Clear accumulated data # Process next batch end ``` -------------------------------- ### Lapsoss Backtrace Processing and Formatting (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/backtrace_processing.md Shows how to instantiate `BacktraceProcessor`, process an exception's backtrace, and then format the processed frames for specific error tracking services like Sentry, Rollbar, and Bugsnag. ```ruby processor = Lapsoss::BacktraceProcessor.new # Process the backtrace frames = processor.process(exception.backtrace) # Format for specific adapters sentry_frames = processor.format_frames(frames, :sentry) rollbar_frames = processor.format_frames(frames, :rollbar) bugsnag_frames = processor.format_frames(frames, :bugsnag) ``` -------------------------------- ### Dependency Management for Sentry (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This code lists the direct dependencies required by the Sentry Ruby SDK. It highlights the potential for dependency hell due to the number of required gems and native extensions. ```ruby # Sentry requires: - concurrent-ruby - faraday - sawyer - various patches and integrations - msgpack - debase-ruby_core_source - numerous native extensions ``` -------------------------------- ### Basic Exception Capture in Sentry Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This snippet demonstrates the fundamental way to capture an exception using the Sentry SDK. It's a straightforward call to report an error that has occurred within the application. ```ruby Sentry.capture_exception(error) ``` -------------------------------- ### Basic Lapsoss Configuration (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Perform a basic configuration of Lapsoss by setting up the Telebugs adapter using an environment variable for the DSN. This is typically placed in an initializer file. ```ruby # config/initializers/lapsoss.rb Lapsoss.configure do |config| config.use_telebugs(dsn: ENV["TELEBUGS_DSN"]) end ``` -------------------------------- ### Ruby: Extending Lapsoss Sentry Adapter for Custom Reporting Source: https://github.com/seuros/lapsoss/blob/master/README.md Illustrates extending the existing Lapsoss SentryAdapter to create a custom adapter, like 'TelebugsAdapter'. This is useful for integrating with Sentry-compatible services while adding specific configurations or headers. It shows how to override initialization and private methods. ```ruby class TelebugsAdapter < Lapsoss::Adapters::SentryAdapter def initialize(name = :telebugs, settings = {}) super(name, settings) end private def build_headers(public_key) super(public_key).merge( "X-Telebugs-Client" => "lapsoss/#{Lapsoss::VERSION}" ) end end ``` -------------------------------- ### Configuring Lapsoss with Multiple Vendors Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This Ruby code snippet shows how to configure the Lapsoss gem to use specific vendor adapters. It demonstrates the flexibility of switching or using multiple error tracking services through a unified interface. ```ruby # Same API, switch vendors instantly: Lapsoss.configure do |config| config.use_sentry(dsn: ENV['SENTRY_DSN']) config.use_appsignal(api_key: ENV['APPSIGNAL_KEY']) end ``` -------------------------------- ### Ruby Gem Comparison: Traditional SDKs vs. Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This snippet compares the file sizes of traditional error tracking SDKs (AppSignal, Sentry-Ruby) with the Lapsoss gem and optional integrations. It highlights Lapsoss's smaller footprint for basic error tracking and the ability to add other functionalities like APM or metrics separately. ```ruby # Traditional SDK approach: gem 'appsignal' # 1.2MB of instrumentation layers gem 'sentry-ruby' # 556K of growing complexity # Lapsoss approach: gem 'lapsoss' # 256KB - Just error tracking! # Then pick what you ACTUALLY need: gem 'opentelemetry-ruby' # If you want APM gem 'prometheus-client' # If you want metrics ``` -------------------------------- ### Configure File Cache Source: https://github.com/seuros/lapsoss/blob/master/docs/backtrace_processing.md Initializes a file cache for Lapsoss with specified maximum size and time-to-live (TTL) values. This cache can store file contents to reduce redundant file I/O operations. ```ruby # In initializer or custom code cache = Lapsoss::FileCache.new( max_size: 100, # More files cached ttl: 600 # 10 minute TTL ) ``` -------------------------------- ### Thread-Safe Adapter Registration in Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Demonstrates the mechanism for thread-safe adapter registration and lookup within Lapsoss. It employs a mutex synchronization strategy to protect shared access to the adapter registry, ensuring data integrity when multiple threads attempt to register or access adapters concurrently. ```ruby # Thread-safe adapter management @mutex = Mutex.new def register(name, type, **settings) @mutex.synchronize do # Safe registration logic end end ``` -------------------------------- ### Create and Register Custom Lapsoss Adapters in Ruby Source: https://context7.com/seuros/lapsoss/llms.txt Extend Lapsoss by creating custom adapters for unsupported services. This involves defining a new adapter class inheriting from `Lapsoss::Adapters::Base`, implementing methods like `capture` and `capabilities`, and registering it with `Lapsoss::Registry`. ```ruby # lib/lapsoss/adapters/custom_adapter.rb module Lapsoss module Adapters class CustomAdapter < Base def initialize(name, settings = {}) super @api_key = settings[:api_key] @endpoint = settings[:endpoint] || "https://api.custom-service.com" end def capture(event) return unless enabled? payload = build_payload(event) response = http_client.post("/errors", payload) unless response.success? raise DeliveryError.new( "Failed to deliver to CustomAdapter", response: response ) end end def capabilities super.merge( breadcrumbs: true, code_context: true ) end private def build_payload(event) { timestamp: event.timestamp.iso8601, level: event.level, message: event.message, exception: { type: event.exception_type, message: event.exception_message, stacktrace: event.backtrace }, context: event.context, tags: event.tags, user: event.user_context } end def http_client @http_client ||= create_http_client( @endpoint, headers: { "X-API-Key" => @api_key } ) end end end end # Register the adapter Lapsoss::Registry.register(:custom, CustomAdapter) # Use in configuration Lapsoss.configure do |config| config.register_adapter( :my_custom_service, :custom, api_key: ENV['CUSTOM_API_KEY'], endpoint: "https://errors.example.com" ) end ``` -------------------------------- ### Conceptual OSS Standard for Error Tracking Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This code illustrates a hypothetical future where an open-source standard for error tracking exists. It suggests a minimal universal protocol gem combined with small, vendor-specific adapter gems, significantly reducing the total size compared to current monolithic SDKs. ```ruby # The future with an OSS standard: gem 'error-tracking-standard' # ~100KB universal protocol gem 'sentry-adapter' # ~5KB vendor-specific transport gem 'appsignal-adapter' # ~5KB vendor-specific transport # Total: ~115KB vs current 6.7MB+ for all three vendors! ``` -------------------------------- ### Basic Lapsoss Backtrace Configuration (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/backtrace_processing.md Configures fundamental backtrace processing options like context lines, path stripping, maximum frames, and code context extraction. These settings are essential for controlling the detail and scope of processed error backtraces. ```ruby Lapsoss.configure do |config| # Number of context lines to include (before and after) config.backtrace_context_lines = 3 # Strip Ruby load paths for cleaner filenames config.backtrace_strip_load_path = true # Maximum frames to process (prevents memory issues) config.backtrace_max_frames = 100 # Enable code context extraction config.backtrace_enable_code_context = true end ``` -------------------------------- ### Lapsoss Backtrace Frame Limiting Configuration (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/backtrace_processing.md Demonstrates how to set a maximum number of frames to process in a backtrace, preventing potential memory issues with very deep stacks. It highlights the intelligent prioritization of application frames. ```ruby config.backtrace_max_frames = 50 # Limit to 50 frames ``` -------------------------------- ### Basic Lapsoss Usage for Capturing and Context Source: https://github.com/seuros/lapsoss/blob/master/README.md This illustrates fundamental Lapsoss functionalities including capturing exceptions, logging messages with severity levels, and adding contextual information to error reports using `with_scope`. ```ruby # Capture exceptions Lapsoss.capture_exception(e) # Capture messages Lapsoss.capture_message("Payment processed", level: :info) # Add context Lapsoss.with_scope(user_id: current_user.id) do process_payment end # Add breadcrumbs Lapsoss.add_breadcrumb("User clicked checkout", type: :navigation) ``` -------------------------------- ### RateLimiter Sampler Configuration in Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Sets up Lapsoss to limit the maximum number of events processed per second using RateLimiter. This prevents overwhelming error tracking services during high-traffic periods. ```ruby Lapsoss.configure do |config| # Maximum 10 errors per second config.sampling_strategy = Lapsoss::Sampling::RateLimiter.new(max_events_per_second: 10) end ``` -------------------------------- ### OTLP (OpenTelemetry Protocol) Configuration (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Configure Lapsoss to send data using the OpenTelemetry Protocol (OTLP). This is compatible with various observability backends like SigNoz, Jaeger, Tempo, and Honeycomb. It requires an endpoint and service name, with optional custom headers. ```ruby # Works with SigNoz, Jaeger, Tempo, Honeycomb, Datadog, etc. Lapsoss.configure do |config| config.use_otlp( endpoint: ENV['OTLP_ENDPOINT'], # e.g., "http://localhost:4318" service_name: "my-rails-app", headers: { "X-Custom-Header" => "value" } # optional custom headers ) # Or use convenience helpers for specific services config.use_signoz(signoz_api_key: ENV['SIGNOZ_API_KEY']) config.use_jaeger(endpoint: "http://jaeger:4318") config.use_tempo(endpoint: "http://tempo:4318") end ``` -------------------------------- ### Custom Composite Sampling Strategy in Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Combines multiple Lapsoss sampling strategies into a single, composite strategy. This allows for complex sampling logic by defining whether all, any, or the first sampler's decision should apply. ```ruby class CompositeSampler < Lapsoss::Sampling::Base def initialize(samplers, strategy: :all) @samplers = samplers @strategy = strategy end def sample?(event, hint = {}) case @strategy when :all @samplers.all? { |s| s.sample?(event, hint) } when :any @samplers.any? { |s| s.sample?(event, hint) } when :first @samplers.first&.sample?(event, hint) || true end end end Lapsoss.configure do |config| config.sampling_strategy = CompositeSampler.new( [ Lapsoss::Sampling::RateLimiter.new(max_events_per_second: 50), ExceptionTypeSampler.new('ActiveRecord::RecordNotFound' => 0.01), TimeBasedSampler.new ], strategy: :all # All samplers must agree to send the event ) end ``` -------------------------------- ### Pipeline and Sampling Configuration (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Configure a middleware pipeline for Lapsoss events, including sampling to reduce the volume of sent events and enhancing user context within events. This allows for fine-grained control over event processing. ```ruby Lapsoss.configure do |config| # Build a middleware pipeline for every event config.configure_pipeline do |pipeline| pipeline.sample(rate: 0.1) # Drop 90% of events pipeline.enhance_user_context( provider: ->(event, _) { current_user&.slice(:id, :email) }, privacy_mode: true # keep only ids ) end end ``` -------------------------------- ### Proper Exception Handling with Lapsoss Scope Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Shows how to properly capture exceptions within the context of a Lapsoss scope, ensuring that the exception data includes relevant operational tags. This uses a `begin...rescue` block combined with `Lapsoss.capture_exception`. ```ruby # Good: Exception captured with proper scope context Lapsoss.with_scope(tags: { operation: "user_creation" }) do begin create_user(params) rescue => e Lapsoss.capture_exception(e) # Includes operation context end end ``` -------------------------------- ### Adaptive Sampling with Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Dynamically adjusts the sampling rate based on the volume of events. It increases the rate during low volume and decreases it during high volume to maintain a target sampling rate. This strategy requires a 'target_rate' and 'adjustment_period'. ```ruby class AdaptiveSampler < Lapsoss::Sampling::Base def initialize(target_rate: 1.0, adjustment_period: 60) @target_rate = target_rate @adjustment_period = adjustment_period @current_rate = target_rate @events_count = 0 @last_adjustment = Time.now @mutex = Mutex.new end def sample?(_event, _hint = {}) @mutex.synchronize do @events_count += 1 now = Time.now if now - @last_adjustment > @adjustment_period adjust_rate @last_adjustment = now @events_count = 0 end end @current_rate > rand end private def adjust_rate if @events_count > 100 # High volume @current_rate = [@current_rate * 0.9, @target_rate * 0.1].max elsif @events_count < 10 # Low volume @current_rate = [@current_rate * 1.1, @target_rate].min end end end Lapsoss.configure do |config| config.sampling_strategy = AdaptiveSampler.new(target_rate: 0.5) end ``` -------------------------------- ### Route Data by Region (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Configure Sentry and Telebugs to route data to specific regional servers based on environment variables. This is useful for compliance with data residency regulations. ```ruby config.use_sentry(name: :us, dsn: ENV['US_SENTRY_DSN']) config.use_telebugs(name: :eu, dsn: ENV['EU_TELEBUGS_DSN']) ``` -------------------------------- ### Debugging Sampling Decisions with Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Wraps an existing sampler to log sampling decisions for debugging purposes. It takes a 'wrapped_sampler' and an optional 'logger'. The 'sample?' method logs whether an event is sampled or not before returning the original sampler's decision. This requires a logger object, typically Rails.logger in a Rails environment. ```ruby class DebugSampler < Lapsoss::Sampling::Base def initialize(wrapped_sampler, logger: Rails.logger) @sampler = wrapped_sampler @logger = logger end def sample?(event, hint = {}) result = @sampler.sample?(event, hint) @logger.debug "Sampling decision: #{result} for #{event.exception&.class}" result end end Lapsoss.configure do |config| config.sampling_strategy = DebugSampler.new( Lapsoss::Sampling::UniformSampler.new(0.5) ) end ``` -------------------------------- ### High Availability with Multiple Providers (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Configure multiple error tracking services, Telebugs and AppSignal, to ensure redundancy. If one service fails, the other can continue to log errors, improving system reliability. ```ruby # Multiple providers for redundancy config.use_telebugs(name: :primary, dsn: ENV['PRIMARY_DSN']) config.use_appsignal(name: :backup, push_api_key: ENV['APPSIGNAL_KEY']) ``` -------------------------------- ### Configure Lapsoss Error Filtering in Ruby Source: https://github.com/seuros/lapsoss/blob/master/README.md Demonstrates how to configure Lapsoss to filter which errors are sent. It shows the use of `before_send` callbacks for simple filtering and `exclusion_filter` for more complex rules based on exception types, patterns, and messages. Custom exclusion logic can also be added. ```ruby Lapsoss.configure do |config| # Use the before_send callback for simple filtering config.before_send = lambda do |event| # Return nil to prevent sending return nil if event.exception.is_a?(ActiveRecord::RecordNotFound) event end # Or use the exclusion filter for more complex rules config.exclusion_filter = Lapsoss::ExclusionFilter.new( # Exclude specific exception types excluded_exceptions: [ "ActionController::RoutingError", # Your choice "ActiveRecord::RecordNotFound" # Your decision ], # Exclude by pattern matching excluded_patterns: [ /timeout/i, # If timeouts are expected in your app /user not found/i # If these are normal in your workflow ], # Exclude specific error messages excluded_messages: [ "No route matches", "Invalid authenticity token" ] ) # Add custom exclusion logic config.exclusion_filter.add_exclusion(:custom, lambda do |event| # Your business logic here event.context[:request]&.dig(:user_agent)&.match?(/bot/i) end) end ``` -------------------------------- ### Ruby: Lapsoss Error Handling in Non-Rails Environments Source: https://github.com/seuros/lapsoss/blob/master/README.md Demonstrates using Lapsoss for error handling in Ruby code outside of Rails, such as Sidekiq jobs or rake tasks. It covers configuration with Sentry, handling errors with and without fallbacks, recording errors, and manual reporting. Dependencies include the 'lapsoss' gem. ```ruby require 'lapsoss' Lapsoss.configure do |config| config.use_sentry(dsn: ENV['SENTRY_DSN']) end # Handle errors (swallow them) result = Lapsoss.handle do risky_operation end # Returns nil if error occurred, or the block's result # Handle with fallback user = Lapsoss.handle(fallback: User.anonymous) do User.find(id) end # Record errors (re-raise them) Lapsoss.record do critical_operation # Error is captured then re-raised end # Report errors manually begin something_dangerous rescue => e Lapsoss.report(e, user_id: user.id, context: 'background_job') # Continue processing... end ``` -------------------------------- ### Uniform Sampler Configuration in Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Configures Lapsoss to randomly sample a specified percentage of errors using UniformSampler. This is useful for general-purpose sampling to reduce the volume of tracked errors. ```ruby Lapsoss.configure do |config| # Sample 50% of errors randomly config.sample_rate = 0.5 # Or explicitly use UniformSampler config.sampling_strategy = Lapsoss::Sampling::UniformSampler.new(0.5) end ``` -------------------------------- ### Manage Scope Isolation Between Threads in Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Illustrates the correct way to handle scope objects in multi-threaded scenarios using Lapsoss. It contrasts a bad practice (sharing scope) with a good practice (using `Lapsoss.with_scope` for thread-local context). ```ruby # Bad: Sharing scope between threads scope = Lapsoss.current_scope threads = items.map do |item| Thread.new do scope.tags["item"] = item.id # Race condition! end end ``` ```ruby # Good: Each thread has its own scope threads = items.map do |item| Thread.new do Lapsoss.with_scope(tags: { item_id: item.id }) do # Thread-safe processing end end end ``` -------------------------------- ### Custom Sampling Logic with Proc in Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Uses a Proc for simple, inline custom sampling logic in Lapsoss. This is suitable for straightforward filtering or random sampling without defining a full class. ```ruby Lapsoss.configure do |config| config.sampling_strategy = ->(event, hint) { # Skip all ActiveRecord::RecordNotFound errors return false if event.exception&.class&.name == 'ActiveRecord::RecordNotFound' # Sample 10% of everything else 0.1 > rand } end ``` -------------------------------- ### Configure OTLP (OpenTelemetry) Integrations in Ruby Source: https://context7.com/seuros/lapsoss/llms.txt Set up Lapsoss to send errors to any OpenTelemetry-compatible backend, including generic OTLP endpoints, SigNoz, Jaeger, and Grafana Tempo. This enables unified error tracking across different observability tools. ```ruby Lapsoss.configure do |config| # Generic OTLP endpoint config.use_otlp( endpoint: "http://localhost:4318", service_name: "my-rails-app", headers: { "Authorization" => "Bearer #{ENV['OTLP_TOKEN']}", "X-Custom-Header" => "value" } ) # SigNoz (self-hosted observability) config.use_signoz( endpoint: "https://ingest.signoz.io", signoz_api_key: ENV['SIGNOZ_API_KEY'] ) # Jaeger (distributed tracing) config.use_jaeger(endpoint: "http://jaeger:4318") # Grafana Tempo config.use_tempo( endpoint: "https://tempo.grafana.net", headers: { "Authorization" => "Basic #{encoded_credentials}" } ) end ``` -------------------------------- ### Implement Lapsoss Error Handler Hook in Ruby Source: https://github.com/seuros/lapsoss/blob/master/README.md Shows how to set up a custom error handler in Lapsoss to receive a callback when an adapter fails to deliver an error report. The provided lambda function logs the failure details, including the adapter name, error message, and optionally the event payload in development environments. ```ruby Lapsoss.configure do |config| config.error_handler = lambda do |adapter, event, error| Rails.logger.error("Delivery failed for #{adapter.name}: #{error.message}") Rails.logger.error(event.to_h) if Rails.env.development? end end ``` -------------------------------- ### Configure Lapsoss with Multiple Error Reporting Services Source: https://github.com/seuros/lapsoss/blob/master/README.md This snippet demonstrates how to configure Lapsoss to use multiple error reporting services simultaneously. It shows how to switch between Bugsnag and Telebugs by changing configuration lines, highlighting the zero-code change benefit. ```ruby # Your code never changes: Lapsoss.capture_exception(e) # Switch vendors in config, not code: Lapsoss.configure do |config| # Monday: Using Bugsnag config.use_bugsnag(api_key: ENV['BUGSNAG_KEY']) # Tuesday: Add Telebugs for comparison config.use_telebugs(dsn: ENV['TELEBUGS_DSN']) # Wednesday: Drop Bugsnag, keep Telebugs # Just remove the line. Zero code changes. end ``` -------------------------------- ### Essential Features Provided by Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/STORY.md This list outlines the core functionalities that Lapsoss focuses on for error tracking. It contrasts these essential features with the often unnecessary or unwanted features included in larger SDKs. ```text # What you actually need: - Exception capture āœ“ - Context/user data āœ“ - Breadcrumbs āœ“ - Clean HTTP transport āœ“ # What you DON'T get: - SQL injection detection you didn't enable - Profilers running by default - Security monitoring you're not paying for - 47 different integrations ``` -------------------------------- ### Manual Error Reporting with Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/README.md This snippet illustrates explicit error capture using Lapsoss within a `begin...rescue` block in controllers or jobs. It also shows how to use `Rails.error.report` with custom context, providing fine-grained control over error reporting. ```ruby # In controllers, jobs, or anywhere you want explicit control begin process_payment rescue => e Lapsoss.capture_exception(e, user_id: current_user.id) # Handle gracefully... end # Or use Rails.error directly with your configured services Rails.error.report(e, context: { user_id: current_user.id }) ``` -------------------------------- ### Best Practice: Using Scoped Context for Request Data (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Highlights the best practice of using `Lapsoss.with_scope` to manage context data that is specific to a request or operation. This ensures that contextual information, like a request ID, is correctly associated with events and exceptions originating from that specific scope. ```ruby # Good: Scoped context Lapsoss.with_scope(tags: { request_id: request.id }) do # Request processing end ``` -------------------------------- ### A/B Test Error Services (Ruby) Source: https://github.com/seuros/lapsoss/blob/master/README.md Set up two different error tracking services, Rollbar and Sentry, to run in parallel. This allows for comparing their effectiveness or for a staged rollout of a new service. ```ruby # Run both services, compare effectiveness config.use_rollbar(name: :current, access_token: ENV['ROLLBAR_TOKEN']) config.use_sentry(name: :candidate, dsn: ENV['SENTRY_DSN']) ``` -------------------------------- ### Configure Backtrace Processing in Ruby Source: https://context7.com/seuros/lapsoss/llms.txt Customize how Lapsoss processes and displays backtraces. Options include setting the number of context lines, defining patterns for 'in_app' frames, excluding specific frames, stripping the Rails root path, and setting the maximum number of frames. ```ruby Lapsoss.configure do |config| # Number of lines of code context around each frame config.backtrace_context_lines = 3 # Mark frames as "in_app" if they match these patterns config.backtrace_in_app_patterns = [ %r{^/app/}, %r{^/lib/my_app/} ] # Exclude frames matching these patterns config.backtrace_exclude_patterns = [ %r{/gems/}, %r{/ruby/} ] # Strip Rails root from paths config.backtrace_strip_load_path = true # Maximum number of frames to include config.backtrace_max_frames = 100 # Include source code context in frames config.backtrace_enable_code_context = true end ``` -------------------------------- ### Consistent Hash Sampling with Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/sampling_strategies.md Samples events consistently based on a hash of specific event attributes, such as its fingerprint. This is useful for debugging as the same event will always be sampled or dropped. It requires a 'rate' and a 'key' for hashing. Dependencies include the 'digest' library. ```ruby require 'digest' class ConsistentHashSampler < Lapsoss::Sampling::Base def initialize(rate: 0.1, key: :fingerprint) @rate = rate @key = key @threshold = (rate * 0xFFFFFFFF).to_i end def sample?(event, _hint = {}) value = event.send(@key) || event.message return @rate > rand unless value hash_value = Digest::MD5.hexdigest(value.to_s)[0, 8].to_i(16) hash_value <= @threshold end end Lapsoss.configure do |config| # Consistently sample 10% of errors based on their fingerprint config.sampling_strategy = ConsistentHashSampler.new(rate: 0.1) end ``` -------------------------------- ### Build Event Processing Pipeline in Ruby Source: https://context7.com/seuros/lapsoss/llms.txt Construct a custom event processing pipeline using `Lapsoss.configure` and `pipeline.configure_pipeline`. This allows for advanced event transformation and filtering, including sampling, enhancing context, excluding specific errors, rate limiting, conditional filtering, and event transformation such as custom fingerprinting. ```ruby Lapsoss.configure do |config| config.configure_pipeline do |pipeline| # Sample 25% of events pipeline.sample(rate: 0.25) # Enhance with user context pipeline.enhance_user_context( provider: ->(event, _hint) { { id: Current.user&.id, email: Current.user&.email } }, privacy_mode: true # Only keep user IDs ) # Exclude specific exceptions pipeline.exclude_exceptions( ActiveRecord::RecordNotFound, ActionController::RoutingError, patterns: [/timeout/i] ) # Rate limiting (max 100 events per 60 seconds) pipeline.rate_limit(max_events: 100, time_window: 60) # Conditional filtering pipeline.filter_if do |event| event.level == :debug && Rails.env.production? end # Transform events pipeline.transform_events do |event| # Add custom fingerprinting event.with(fingerprint: custom_fingerprint(event)) end end end ``` -------------------------------- ### Adding Controller Context with Lapsoss Source: https://github.com/seuros/lapsoss/blob/master/README.md This shows how to include Lapsoss's controller context module in `ApplicationController`. This automatically enriches error reports with details about the current controller and action, aiding in debugging. ```ruby # app/controllers/application_controller.rb class ApplicationController < ActionController::Base include Lapsoss::RailsControllerContext end # Now all errors include controller/action context: # { controller: "users", action: "show", controller_class: "UsersController" } ``` -------------------------------- ### Thread-Safe HTTP Client with Faraday in Ruby Source: https://github.com/seuros/lapsoss/blob/master/docs/thread_safety.md Shows how Lapsoss utilizes Faraday for its HTTP client, which includes built-in retry middleware. Faraday's connection pooling and adapter system are inherently thread-safe, eliminating the need for explicit mutex synchronization for HTTP requests. This ensures reliable communication in concurrent environments. ```ruby # Thread-safe Faraday connection def build_connection Faraday.new(@base_url) do |conn| conn.request :retry, retry_options conn.options.timeout = @config[:timeout] || 5 # Faraday handles connection pooling and thread safety internally end end ```