Track Rails errors with Sentry
Create Sentry project
Login to Sentry and go to Projects > Create project
and choose the Rails project type.
Install gems
gem 'sentry-ruby'
gem 'sentry-rails'
Run:
./bin/bundle install
Configure Sentry
Create a file config/initializers/sentry.rb
:
# frozen_string_literal: true
# https://docs.sentry.io/platforms/ruby/guides/rails/configuration/
Sentry.init do |config|
config.breadcrumbs_logger = [:active_support_logger, :http_logger]
config.traces_sample_rate = 0.25
end
Restart Rails server.
Verify setup
Each Sentry project is identified by a client key / DSN. We’ve omitted this from config/initializers/sentry.rb
because we’ll provide it with the SENTRY_DSN
environment variable instead.
To get the client key / DSN, navigate to Projects > [Project]
, click the cog icon on the top right and then Client Keys (DSN)
.
Normally, you’d set this in production or staging environment only but let’s test the Sentry integration locally.
Open up the Rails console:
SENTRY_DSN=<your-dsn> ./bin/rails console
Run:
Sentry.capture_message('test message')
You should see something like:
=> #<Sentry::Event @event_id="3e9672cb7cbd4abf8f3648cf80668700", @timestamp="2022-02-06T05:48:49Z", @platform=:ruby, @sdk={"name"=>"sentry.ruby", "version"=>"5.0.2"}, @user={}, @extra={}, @contexts={:os=>{:name=>"-ruby.rb:293", "sentry-ruby-core (5.0.2) lib/sentry/hub.rb:116"]>, @breadcrumbs=#<Sentry::BreadcrumbBuffer:0x00007fb2bbc590c0 @buffer=[nil, nil]>>
Sending envelope [event] 3e9672cb7cbd4abf8f3648cf80668700 to Sentry
This means Sentry was able to send the event to its servers. If you try this without setting the SENTRY_DSN
env variable, you’ll get nil
when you call Sentry.capture_message
. Go to your Sentry project’s issues page and you should see the error reported.
Other notes
Sentry automatically sets the current environment to RAILS_ENV
, or if it is not present, RACK_ENV
.
Sources
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment