### Local Gemfile Installation (Shell) Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/gems/README.md This shell command demonstrates how to install gems using a specific gemfile for local testing. It sets the BUNDLE_GEMFILE environment variable before running `bundle install` to ensure the correct gem versions are installed. ```shell BUNDLE_GEMFILE=gems/rails5.gemfile bundle install ``` -------------------------------- ### Scout APM Ruby Background Job Integration Examples Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt Demonstrates how Scout APM automatically instruments various Ruby background job frameworks. Examples include Sidekiq, Resque, Delayed Job, and ActiveJob, showing how jobs are automatically tracked and how custom context can be added for debugging. ```ruby class HardWorker include Sidekiq::Worker def perform(user_id, action) user = User.find(user_id) user.send(action) end end ``` ```ruby class ProcessDataJob @queue = :default def self.perform(data_id) Data.find(data_id).process! end end ``` ```ruby class Newsletter < ApplicationRecord def send_to_subscribers subscribers.each { |s| NewsletterMailer.weekly(s).deliver_later } end handle_asynchronously :send_to_subscribers end ``` ```ruby class ProcessOrderJob < ApplicationJob queue_as :default def perform(order) ScoutApm::Context.add( order_id: order.id, customer_id: order.customer_id ) order.process! end end ``` -------------------------------- ### Enable DevTrace for Local Development Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/README.markdown This snippet illustrates how to enable DevTrace, Scout's free in-browser development profiler. It involves adding the gem to the Gemfile and starting the Rails server with a specific environment variable. ```ruby # Gemfile gem 'scout_apm' # Start server with: SCOUT_DEV_TRACE=true rails server ``` -------------------------------- ### Scout APM Ruby Configuration Options (YAML) Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This YAML snippet provides a comprehensive example of configuring Scout APM in Ruby applications. It covers general settings like application name and API key, error monitoring specifics, sampling rates, endpoint and job ignoring, per-endpoint sampling, background job settings, and advanced options. It also shows environment-specific configurations. ```yaml # config/scout_apm.yml - Full configuration example common: &defaults name: "MyApp" key: <%= ENV['SCOUT_KEY'] %> monitor: true # Logging log_level: info # debug, info, warn log_file_path: log/ # or "STDOUT" # Error Monitoring errors_enabled: true errors_ignored_exceptions: - ActiveRecord::RecordNotFound - ActionController::RoutingError errors_filtered_params: - password - credit_card - ssn # Sampling Configuration (rates are 0.0 to 1.0) sample_rate: 1.0 # Global sample rate (1.0 = 100%) endpoint_sample_rate: 0.5 # Sample 50% of web requests job_sample_rate: 0.8 # Sample 80% of background jobs # Ignore specific endpoints/jobs ignore_endpoints: - "^/health" - "^/metrics" ignore_jobs: - HeartbeatJob - CleanupJob # Per-endpoint sampling (format: "prefix:rate") sample_endpoints: - "/api/v1/webhooks:0.1" # Sample 10% of webhooks - "/admin:1.0" # Sample 100% of admin requests # Background job configuration enable_background_jobs: true job_params_capture: true # Capture job arguments job_filtered_params: - password - api_key # Advanced options uri_reporting: full_path # or 'path' to exclude query params collect_remote_ip: true detailed_middleware: false auto_instruments: false timeline_traces: true hostname: <%= ENV['HOSTNAME'] %> # Instrumentation method use_prepend: false # Use Module#prepend instead of alias_method disabled_instruments: - net_http # Disable specific instruments development: <<: *defaults dev_trace: true # Enable DevTrace in development monitor: false test: monitor: false staging: <<: *defaults production: <<: *defaults sample_rate: 0.1 # Sample 10% in production for high-traffic apps ``` -------------------------------- ### Install ScoutApm Ruby Gem and Configure Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt Instructions for adding the ScoutApm gem to your Rails application's Gemfile and configuring it with an API key in `config/scout_apm.yml`. Ensure the 'parser' gem version matches your Ruby version. ```ruby # Gemfile gem 'scout_apm' gem 'parser', '~> 3.3.0.0' # Match your Ruby version # config/scout_apm.yml common: &defaults name: YOUR_APPLICATION_NAME key: YOUR_APPLICATION_KEY monitor: true test: monitor: false production: <<: *defaults ``` -------------------------------- ### Local Test Execution with Specific Gemfile (Shell) Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/gems/README.md This shell command shows how to execute rake tasks using gems specified by a particular gemfile. Similar to installation, it uses the BUNDLE_GEMFILE environment variable to direct Bundler to the correct gemfile. ```shell BUNDLE_GEMFILE=gems/rails5.gemfile bundle exec rake ``` -------------------------------- ### Enable DevTrace for Development Profiling in Ruby Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This shows how to enable DevTrace for development profiling in Ruby applications. DevTrace provides in-browser profiling without needing a Scout account. It can be activated by setting the `SCOUT_DEV_TRACE` environment variable when starting the Rails server or by configuring `dev_trace: true` in the `development` section of `scout_apm.yml`. ```bash # Start Rails with DevTrace enabled SCOUT_DEV_TRACE=true rails server # Or configure in scout_apm.yml # development: # dev_trace: true ``` -------------------------------- ### Scout APM Ruby Configuration Options (Environment Variables) Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This snippet illustrates how to configure Scout APM in Ruby applications using environment variables. These settings override YAML configurations. Examples include API key, application name, logging level, error monitoring enablement, sampling rates, and ignored endpoints. ```ruby # Environment variable configuration (overrides YAML) # SCOUT_KEY=your_api_key # SCOUT_NAME=MyApp # SCOUT_MONITOR=true # SCOUT_LOG_LEVEL=debug # SCOUT_ERRORS_ENABLED=true # SCOUT_SAMPLE_RATE=0.5 # SCOUT_IGNORE_ENDPOINTS=["^/health","^/ping"] # SCOUT_DEV_TRACE=true ``` -------------------------------- ### Configure Detailed Middleware in Scout APM Ruby Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/CHANGELOG.markdown Introduces a `detailed_middleware` boolean configuration option. When set to true, it captures per-middleware data instead of aggregating all middleware. This provides more granular insights but incurs a small overhead of approximately 10-15ms per request. ```ruby # Example configuration in scout_apm.yml or initializer: ScoutApm.configure do |config| config.ruby.detailed_middleware = true end ``` -------------------------------- ### Access and Utilize DevTrace in Ruby Applications Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This snippet explains how to access and use DevTrace for profiling in Ruby applications. By appending `?pp=1` to any URL, developers can view request timing, SQL query performance, view rendering times, memory allocation, and N+1 query detection directly in their browser. ```ruby # Access DevTrace in your browser # Visit any page in your app, then append ?pp=1 to the URL # Example: http://localhost:3000/users?pp=1 # DevTrace shows: # - Request timing breakdown # - SQL queries with timing # - View rendering time # - Memory allocation # - N+1 query detection ``` -------------------------------- ### Custom Instrumentation with ScoutApm::Tracer in Ruby Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt Demonstrates three methods for custom instrumentation using ScoutApm::Tracer: block-based (explicit), including the module and using `instrument_method` (automatic), and class method instrumentation. ```ruby # Method 1: Block-based instrumentation (explicit) class PaymentProcessor def process_payment(order) ScoutApm::Tracer.instrument("Payment", "process_payment", desc: "Stripe API call") do # Your payment processing code Stripe::Charge.create( amount: order.total_cents, currency: 'usd', source: order.payment_token ) end end end # Method 2: Include module and use instrument_method (automatic) class ReportGenerator include ScoutApm::Tracer def generate_monthly_report(user_id) # Report generation logic data = fetch_user_data(user_id) compile_statistics(data) end def fetch_user_data(user_id) User.find(user_id).transactions.where(created_at: 1.month.ago..Time.current) end # Instrument the method - will appear as "Custom/ReportGenerator/generate_monthly_report" instrument_method :generate_monthly_report, type: "Custom", name: "ReportGenerator/generate_monthly_report" # Custom type for better categorization instrument_method :fetch_user_data, type: "Database", name: "ReportGenerator/fetch_user_data", scope: true end # Method 3: Class method with options class DataExporter extend ScoutApm::Tracer::ClassMethods def self.export_to_csv(records) instrument("Export", "csv_generation", ignore_children: true) do CSV.generate do |csv| records.each { |r| csv << r.to_a } end end end end ``` -------------------------------- ### Configure Scout APM with scout_apm.yml Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/README.markdown This snippet demonstrates the basic structure of the `scout_apm.yml` configuration file. It includes common settings like application name, key, and monitoring status, with environment-specific overrides. ```yaml common: &defaults name: YOUR_APPLICATION_NAME key: YOUR_APPLICATION_KEY monitor: true test: monitor: false production: <<: *defaults ``` -------------------------------- ### Test Scout APM Gem Locally Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/README.markdown This snippet provides instructions for testing the Scout APM gem locally by pointing your Gemfile to a local checkout and compiling the native code. ```bash # Point Gemfile to local checkout: gem 'scout_apm', path: '/path/to/scout_apm_ruby' # Compile native code: cd /path/to/scout_apm_ruby && bundle exec rake compile ``` -------------------------------- ### Travis CI Matrix Configuration (YAML) Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/gems/README.md This YAML snippet defines a Travis CI build matrix, specifying Ruby versions and associated gemfiles for testing. It allows for testing against different Rails versions by selecting specific gemfiles. ```yaml matrix: include: - rvm: "1.8.7" gemfile: gems/rails3.gemfile ``` -------------------------------- ### Scout APM Ruby Extensions API for Custom Callbacks Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This placeholder indicates where to find information about the Scout APM Ruby Extensions API. This API allows developers to hook into Scout APM's data collection process for custom integrations and callbacks, typically configured within an initializer file. ```ruby # config/initializers/scout_apm_extensions.rb ``` -------------------------------- ### Control Transactions Dynamically in Ruby with ScoutApm Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt Illustrates how to use the ScoutApm Transaction module to dynamically rename or ignore transactions. This is useful for consolidating similar API endpoints or excluding specific requests from monitoring. ```ruby class ApiController < ApplicationController def multi_action_endpoint action = params[:action_type] # Rename the transaction based on the actual action being performed ScoutApm::Transaction.rename("Api/#{action}") case action when 'create_user' create_user_logic when 'update_settings' update_settings_logic end end def health_check # Completely ignore this endpoint from monitoring ScoutApm::Transaction.ignore! render json: { status: 'ok', timestamp: Time.current } end def internal_metrics # Ignore internal endpoints that would skew metrics ScoutApm::Transaction.ignore! if request.headers['X-Internal-Request'] # ... metrics logic end end ``` -------------------------------- ### Add Context Metadata to Requests in Ruby with ScoutApm Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt Shows how to use the ScoutApm Context API to attach custom metadata to requests in Rails controllers and background jobs. This metadata aids in debugging and filtering within the Scout dashboard. ```ruby # In a Rails controller - add user context class ApplicationController < ActionController::Base before_action :set_scout_context private def set_scout_context if current_user # Add user-specific context ScoutApm::Context.add_user( id: current_user.id, email: current_user.email, plan: current_user.subscription_plan, ip: request.remote_ip ) # Add general request context ScoutApm::Context.add( account_id: current_user.account_id, monthly_spend: current_user.account.monthly_spend, locale: I18n.locale, feature_flags: current_user.enabled_features.join(",") ) end end end # In a background job class ProcessOrderJob < ApplicationJob def perform(order_id) order = Order.find(order_id) # Add job-specific context ScoutApm::Context.add( order_id: order.id, order_total: order.total, customer_tier: order.customer.tier ) # Process the order... order.fulfill! end end ``` -------------------------------- ### Access Temporary Data Directory in Ruby Tests Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/test/tmp/README.md Demonstrates how to use the `DATA_FILE_DIR` constant within a Ruby Minitest class to construct paths for temporary test files, such as SQLite databases. ```ruby class MyTest < Minitest::Test def database_path File.expand_path('test.sqlite3', DATA_FILE_DIR) end # ... tests end ``` -------------------------------- ### Enable Scout APM Error Monitoring Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/README.markdown This snippet shows how to enable error monitoring within the `scout_apm.yml` configuration file. Ensure `monitor: true` is also set for your environment to guarantee your app is registered in Scout. ```yaml # Common/dev/production/etc. whereever you would like to start trying it # monitor: true should also be required to ensure your App exists in Scout errors_enabled: true ``` -------------------------------- ### Capture Errors Manually with Scout APM Ruby Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This section shows how to manually capture exceptions and add custom context using Scout APM's Error module in Ruby. It covers capturing validation errors during record saving and payment processing errors from Stripe. It also demonstrates capturing errors within background jobs without halting execution. ```ruby # Enable error monitoring in config/scout_apm.yml # errors_enabled: true class OrdersController < ApplicationController def create @order = Order.new(order_params) if @order.save redirect_to @order else # Capture validation errors with context ScoutApm::Error.capture( "Order validation failed: #{@order.errors.full_messages.join(', ')}", { order_params: order_params.to_h, user_id: current_user.id }, name: "OrderValidationError" ) render :new end rescue Stripe::CardError => e # Capture payment errors with full context ScoutApm::Error.capture( e, { order_id: @order&.id, amount: order_params[:total], stripe_error_code: e.code }, env: request.env ) flash[:error] = "Payment failed: #{e.message}" render :new end end # Capture errors in background jobs class ImportJob < ApplicationJob def perform(file_path) CSV.foreach(file_path).with_index do |row, index| begin process_row(row) rescue StandardError => e # Capture row-level errors without stopping the import ScoutApm::Error.capture( e, { file: file_path, row_number: index, row_data: row.to_s } ) end end end end ``` -------------------------------- ### Add Scout APM Gem to Gemfile Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/README.markdown This snippet shows how to add the `scout_apm` gem to your Rails application's Gemfile. Ensure you also add a compatible version of the `parser` gem based on your Ruby version. ```ruby gem 'scout_apm' # Example for Ruby 3.3.0: gem 'parser', '~> 3.3.0.0' ``` -------------------------------- ### Ignore Endpoint Configuration in Scout APM Ruby Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/CHANGELOG.markdown Provides an `ignore` key in the configuration to entirely ignore specific endpoints. When an endpoint is ignored, no traces or metrics are collected for it. This is particularly useful for health-check endpoints or other endpoints that do not require monitoring. ```ruby # Example configuration in scout_apm.yml: ignore: - "/healthcheck" - "/status" ``` -------------------------------- ### Instrument XMLHttpRequest for Scout APM (JavaScript) Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/lib/scout_apm/instant/assets/xmlhttp_instrumentation.html This snippet modifies the browser's XMLHttpRequest object to capture network request details. It intercepts the 'open' and 'send' methods to record the URL and data. Upon receiving a response, it checks for the 'X-scoutapminstant' header and reports the trace information to Scout APM. This is useful for client-side performance monitoring. ```javascript (function(){var open=window.XMLHttpRequest.prototype.open;var send=window.XMLHttpRequest.prototype.send;function openReplacement(method,url,async,user,password){this._url=url;return open.apply(this,arguments);} function sendReplacement(data){if(this.onload){this._onload=this.onload;} this.onload=onLoadReplacement;return send.apply(this,arguments);} function onLoadReplacement(){if(this._url.startsWith(window.location.protocol+"//"+window.location.host)||!this._url.startsWith("http")){try{var traceText=this.getResponseHeader("X-scoutapminstant");if(traceText){setTimeout(function(){window.scoutInstant("addTrace",traceText)},0);}}catch(e){console.debug("Problem getting X-scoutapminstant header");}} if(this._onload){return this._onload.apply(this,arguments);}} window.XMLHttpRequest.prototype.open=openReplacement;window.XMLHttpRequest.prototype.send=sendReplacement;})(); ``` -------------------------------- ### Scout APM Ruby Transaction and Periodic Callbacks Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt Defines callbacks for Scout APM to execute after each transaction and periodically. The transaction callback processes payload data like duration and endpoint, sending metrics to StatsD and logging slow requests. The periodic callback aggregates metrics over a reporting period and can send summary data to an external service. ```ruby ScoutApm::Extensions::Config.add_transaction_callback( Proc.new do |payload| duration_ms = payload.duration_ms endpoint = payload.controller_name || payload.job_name StatsD.timing("app.request.duration", duration_ms, tags: ["endpoint:#{endpoint}"]) if duration_ms > 1000 Rails.logger.warn("Slow request: #{endpoint} took #{duration_ms}ms") end end ) ScoutApm::Extensions::Config.add_periodic_callback( Proc.new do |reporting_period, metadata| ExternalMetricsService.report( timestamp: reporting_period.timestamp, request_count: reporting_period.request_count, error_count: reporting_period.error_count ) end ) ``` -------------------------------- ### Register Periodic Hook in Scout APM Ruby Source: https://github.com/scoutapp/scout_apm_ruby/wiki/Debug-Hooks This Ruby code snippet demonstrates how to register a periodic hook using `ScoutApm::Debug.instance.register_periodic_hook`. It checks for the presence of `ScoutApm::Agent` and `ScoutApm::Debug` before registering a hook that logs a debug message when a background worker runs. This is typically used within application server configurations like `unicorn.rb`. ```ruby after_fork do |server, worker| if defined?(ScoutApm::Agent) && defined?(ScoutApm::Debug) ScoutApm::Debug.instance.register_periodic_hook do ScoutApm::Agent.instance.logger.debug("Background worker ran") end end end ``` -------------------------------- ### Ignore Requests Programmatically with Scout APM Ruby Source: https://context7.com/scoutapp/scout_apm_ruby/llms.txt This snippet demonstrates how to programmatically ignore specific requests in a Ruby application using Scout APM's RequestManager. It checks for a 'heartbeat' event type and calls `ignore_request!` if matched, returning an OK response. This is useful for high-volume webhook endpoints. ```ruby class WebhooksController < ApplicationController def receive # Ignore high-volume webhook endpoints if params[:event_type] == 'heartbeat' ScoutApm::RequestManager.lookup.ignore_request! return head :ok end # Process other webhooks normally process_webhook(params) end end ``` -------------------------------- ### Ignore Request in Scout APM Ruby Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/CHANGELOG.markdown Allows for ignoring specific requests to prevent tracing and metric collection. This is useful for health-check endpoints or other endpoints that do not require monitoring. The `ignore_request!` method is called on the `ScoutApm::RequestManager` lookup. ```ruby ScoutApm::RequestManager.lookup.ignore_request! ``` -------------------------------- ### Filter Parameters for Transaction URIs in Scout APM Ruby Source: https://github.com/scoutapp/scout_apm_ruby/blob/master/CHANGELOG.markdown Applies `Rails.application.config.filter_parameters` settings to reported transaction trace URIs. This ensures sensitive parameters are masked in the trace data, enhancing security and privacy. This feature helps maintain consistency with Rails' built-in parameter filtering. ```ruby # This functionality is automatically applied by the agent when Rails is detected. # Ensure your Rails application has `config.filter_parameters` set correctly. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.