Ruby on Rails handles a lot for you — routing, database queries, template rendering — but when an exception bubbles up, you need to know about it before your users do. Rails error tracking isn't just about capturing controller exceptions. It's about catching errors in background jobs, request middleware, scheduled tasks, and every corner of your production stack. This guide sets up production-grade error tracking in Rails using the Sentry SDK, pointed at LightTrace.
By the end, you'll capture controller errors, Sidekiq job failures, unhandled exceptions, and async task crashes — all grouped and alerted in real time.
Install and initialize the SDK
Add the Sentry gem and initialize it in a Rails initializer. Because LightTrace speaks the Sentry protocol, you use the standard sentry-ruby gem and change only the dsn.
bundle add sentry-ruby sentry-rails sentry-sidekiq
Create an initializer to set up the SDK:
# config/initializers/sentry.rb
Sentry.init do |config|
config.dsn = ENV.fetch("SENTRY_DSN", "https://<key>@your-lighttrace-host/1")
config.environment = Rails.env
config.release = "#{Rails.application.class.module_parent_name}@#{ENV.fetch('APP_VERSION', '0.0.0')}"
config.traces_sample_rate = 1.0
end
That single init installs global handlers for uncaught exceptions. The sentry-rails gem also integrates Rails' request handling so every error arrives with the HTTP method, URL, user ID, and request headers automatically attached.
Rails initializers run once at startup, so this is the only place you need to configure Sentry for LightTrace. The SDK handles everything else.
Capture controller and route errors
By default, Rails silently logs errors and returns 500 responses. With the SDK initialized, every uncaught exception in your controllers, models, and middleware is captured and sent to LightTrace.
You don't need to wrap code in try/catch. The SDK's exception handlers catch everything:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id]) # If not found, Rails raises 404
render :show
end
def update
@user = User.find(params[:id])
# If save fails and validation errors aren't handled, this will raise
@user.update!(user_params)
redirect_to @user
end
end
Any unrescued exception here is automatically captured with the request context attached: HTTP method, URL, user ID, IP, headers, and params (with sensitive values like passwords filtered by default). The error lands in LightTrace grouped by fingerprint, so one bug is one issue in your list, not thousands of duplicate events. This fingerprinting and grouping is what turns a firehose into a manageable list.
Track background job failures with Sidekiq
Background jobs are where silent errors hide. A job crashes, nobody notices, and your data stays corrupt until a customer reports it three days later. Sidekiq errors are easy to miss in logs.
The sentry-sidekiq gem hooks into Sidekiq's error handling automatically. Any job that raises an uncaught exception is captured and reported to LightTrace:
# app/jobs/send_invoice_email_job.rb
class SendInvoiceEmailJob
include Sidekiq::Job
def perform(invoice_id)
invoice = Invoice.find(invoice_id)
InvoiceMailer.send_invoice(invoice).deliver_now
end
end
If InvoiceMailer or deliver_now raises an exception, the SDK captures it with the job context: the job class, the arguments, which queue, how many retries, and the exact exception. Sidekiq will retry the job (per your configuration), but you'll see the error immediately in LightTrace instead of waiting for dead letter discovery.
For jobs that retry, set a tag to distinguish retries from real failures. Add context before the job runs using a middleware:
Sidekiq.configure_server do |config|
config.server_middleware do |chain|
chain.add SentryMiddleware
end
end
class SentryMiddleware
def call(worker, msg, queue)
Sentry.set_tags(job_class: msg['class'], retry_count: msg['retry_count'] || 0)
yield
end
endAdd context, tags, and release tracking
Raw stack traces are a start. The real speed-up comes from context — who hit the error, what they were doing, and which release introduced it. Set the current user and add breadcrumbs at important moments:
# config/initializers/sentry.rb (add to the Sentry.init block)
Sentry.init do |config|
# ... other config ...
config.before_send = lambda { |event, hint|
# Attach the current Rails user if one is logged in
if defined?(current_user) && current_user
event.user = {
id: current_user.id,
email: current_user.email,
username: current_user.username,
}
end
event
}
end
And add breadcrumbs for key events in your controllers or models:
Sentry.capture_breadcrumb(
category: "payment",
message: "Processing payment for order ##{order.id}",
level: "info",
)
Now every error arrives with the breadcrumb trail that led to it — database queries, HTTP calls, user actions — so you can reproduce the exact sequence instead of guessing what happened.
Tag errors by feature or team. As your app grows, a flat list of errors becomes overwhelming. Tags let you filter and organize issues by feature, team, priority, or anything else. Add tags in your controller or middleware:
Sentry.set_tags(
feature: "checkout",
team: "payments",
customer_plan: @user&.plan_type,
)
When an error lands in LightTrace, you can filter by tag to see only payment-related issues, or route them to the payments team automatically. Tags also help with error alerting best practices — you can set alert rules that trigger only for critical tags.
Wire up release tracking. When an error spikes after a deploy, the first question is always "which release introduced this?" Tag every event with your release by setting the APP_VERSION environment variable:
# In your deploy script
export APP_VERSION=$(git rev-parse --short HEAD)
# or
export APP_VERSION=$(git describe --tags --always)
The initializer picks it up automatically, and every error is tagged with the exact commit or release version. With release health monitoring, you'll spot regressions instantly and make rollback decisions with confidence.
Handle production gotchas and sensitive data
Rails has several production quirks to watch out for, plus the sensitive-data challenge that most web apps face.
Rails-specific gotchas. A few things create noise or hide real errors:
ActiveRecord race conditions. If two requests race to update the same record, you might see ActiveRecord::StaleObjectError. These are usually transient and not worth alerting on:
Sentry.init do |config|
config.excluded_exceptions += ["ActiveRecord::StaleObjectError"]
end
N+1 queries in exception handlers. Don't query the database in your exception handler — you'll just create more errors. Set the exception message and user ID, but leave deep queries to your app logic.
Sidekiq time zones. If your workers run in a different time zone from your app, timestamp comparisons in error context can look weird. Use UTC consistently.
Scrubbing sensitive data. Rails apps often leak sensitive data — API keys in params, credit card info in forms, user passwords in exceptions. The SDK scrubs known patterns by default (passwords, tokens, credit cards), but you can customize it:
Sentry.init do |config|
config.scrubber = Sentry::Scrubber.new(
# Built-in patterns: password, secret, token, credit_card, etc.
)
# Or define custom patterns:
config.before_send = lambda { |event, hint|
if event.request&.data&.is_a?(Hash)
event.request.data.delete("ssn") # Remove SSN from params
end
event
}
end
By default, the SDK also never sends query strings or POST body data with errors — only the method, URL, and headers. This keeps your error tracking useful without leaking PII.
Always test your scrubbing rules in a test environment before deploying. Overly aggressive scrubbing can hide the context you need to debug; too lenient leaves you exposed.
Getting started
Set up takes about five minutes: add the gems, initialize with your DSN, and deploy. The first errors arrive seconds later in LightTrace. If you need a comparison of error tracking tools or want a deeper dive into the universal patterns that work across every framework, check those guides too.
Start tracking errors in minutes
Add the Sentry gems, point to LightTrace, and start tracking every Rails error, Sidekiq failure, and background job crash in minutes.
Rails error tracking transforms production debugging from "I hope the user reports this" to "I saw it the moment it happened." Catch errors in controllers, jobs, and scheduled tasks automatically, add rich context so fixes are fast, and ship with confidence.