LoginSignup
52
48

More than 5 years have passed since last update.

Railsのwebアプリの500エラーをslackに自動で通知する方法

Last updated at Posted at 2015-04-15

方法

  • exception_notification
  • slack_notifier

を利用

実装方法

(1) gemfileに以下を追加

gem 'exception_notification', :github => 'smartinez87/exception_notification'
gem 'slack-notifier'

(2) bundle install

bundle exec rails g exception_notification:install create config/initializers/exception_notification.rb

(3)slackよりwebhook URLの発行
* 以下URLにアクセス
https://"your_slack_name"slack.com/services/new
* Incoming WebHooksで検索して「+Add」をクリック
* 「choose your channel」からエラー情報流したいchannelを選択
* 「Add incoming webhooks integration」をクリック
* Webhook URL(https://hooks.slack.com/services/*****)をmemo

(4) 2で追加したexception_notification.rbに以下を追加

config.add_notifier :slack, {
 :webhook_url => "(3)でメモしたwebhooks url",
 :channel => "(3)のchoose your channelで選択したchannnel"
}

(5) production環境以外では実行させないようにする

config.ignore_if do |exception, options|
not Rails.env.production?
end

これを書かないと全ての環境で通知が実行されてしまう

(6) 500を実行するmethodを以下のように追記

def render_500(e)
ExceptionNotifier.notify_exception(e, :env => request.env, :data => {:message => "your error message"})
render template: 'errors/error_500', status: 500
end

(7) テスト
500エラーを起こして、上記指定したslackのchannelに流れてきたら成功!
(ローカルでテストの場合は再起動を)

その他

  • 以下コードでクローラー無視出来る(ex.google bot / bing bot)
 :ignore_crawlers => %w{Googlebot bingbot},

ただ現状は上記コードかかずクローラーの場合でもエラーが出るようにしている。
理由はエラーを察知出来るため。

運用方法例

  • sys-errorというchannelを作ってそこはエラーログがたまるのみ
  • sys-handleというchannelを作ってそこはエラーの対応状況を記載するのみ

少人数だとこれで問題無し。
気づく人を増やすって意味では複数サービスを同じ所で管理しても良いかな。

参考

exception_notificationでrailsの例外をslackに送る

52
48
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
52
48