5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails版 bugsnagの飼い方

Last updated at Posted at 2019-08-17

環境

  • Rails 5.2.3

参考サイト

手順

1. bugsnagでユーザ登録。

2. 指示に従い環境を選ぶ(今回は、RubyRails

3. Gemfileにbugsnagを追加する。

Gemfile
gem 'bugsnag'
bundle install

4. 指示に従い、以下のコマンドでconfig/initializers/bugsnag.rbを生成する。

rails generate bugsnag <YOUR_BUGSNAG_API_KEY>

尚、そのままではAPIキーがベタ書きされるので、以下のように環境変数から読み込むようにする。

config/initializers/bugsnag.rb
# frozen_string_literal: true

Bugsnag.configure do |config|
  config.api_key = ENV['BUGSNAG_API_KEY']
end

5. production環境でだけbugsnagのnotificationが飛ぶようにする。

config/initializers/bugsnag.rb
# frozen_string_literal: true

Bugsnag.configure do |config|
  config.api_key = ENV['BUGSNAG_API_KEY']
  config.notify_release_stages = ['production']
end

参考: https://docs.bugsnag.com/platforms/ruby/rails/configuration-options/

6. エラーの報告

ここ(↑)までの設定で、rescue されていない例外は全て報告されるようになります。

Reporting unhandled exceptions

After completing installation and basic configuration, unhandled exceptions in your Rails app will be automatically reported to your Bugsnag dashboard.

https://docs.bugsnag.com/platforms/ruby/rails/#reporting-unhandled-exceptions

以下、rescue している箇所で bugsnag への通知を入れる例です。

begin
  raise 'Something went wrong!'
rescue => exception
  Bugsnag.notify(exception)
  # 必要であれば、ここで何か処理を行う。
end

rescue の中で再度 raise する場合は、以下のように skip_bugsnag を挟む(そうしないと、再度 bugsnag に通知が飛びます)。

参考URL: https://docs.bugsnag.com/platforms/ruby/rails/#avoiding-re-notifying-exceptions

begin
  raise 'Something went wrong!'
rescue => exception
  Bugsnag.notify(exception)
  exception.instance_eval { def skip_bugsnag; true; end }

  # Now this won't be sent a second time by the exception handlers
  raise exception
end
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?