LoginSignup
62
62

More than 5 years have passed since last update.

RailsのログをFluentdでtailしてslackへ通知

Posted at

td-agentのインストール

関連プラグインのインストール

/usr/sbin/td-agent-gem install fluent-plugin-slack
/usr/sbin/td-agent-gem install fluent-plugin-rewrite-tag-filter

ログのtail

ログフォーマットはRailsのフォーマッターで出力される標準のものです。

config/environments/production.rb
config.log_formatter = ::Logger::Formatter.new
log/production.log
E, [2015-09-04T07:03:14.772738 #18058] ERROR -- : undefined method `hoge' for nil:NilClass

FATALエラーとかでトレース情報が複数行出力されることがあるので、multilineでtailします。

/etc/td-agent/td-agent.conf
<source>
  type tail
  path /rails-root/log/production.log
  pos_file /var/log/td-agent/production.log.pos
  tag rails.raw
  format multiline
  format_firstline /^.,/
  format1 /^., \[(?<time>[^\.]+).+\][ ]+(?<level>[^ ]+) -- :(?<message>.*)$/
  time_format %Y-%m-%dT%H:%M:%S
</source>

format_firstlineに最初の行を判定する正規表現を指定し、format1以降に各行の条件を指定します。
multilineの詳しい使い方は公式ドキュメントにも載ってます。
http://docs.fluentd.org/articles/in_tail

今回はファイルに吐き出したログをtailしていますが、以下のgemを用いたほうがいいかもですね。
https://github.com/actindi/act-fluent-logger-rails

ログの選別

fluent-plugin-rewrite-tag-filterを用いてERRORとFATALのみ通知するようにします。
https://github.com/fluent/fluent-plugin-rewrite-tag-filter

/etc/td-agent/td-agent.conf
<match rails.raw>
  type rewrite_tag_filter
  rewriterule1 level ERROR rails.error
  rewriterule2 level FATAL rails.error
  rewriterule3 level INFO  rails.info
  rewriterule4 level .+  clear
</match>
<match clear>
  type null
</match>

slackへ通知

fluent-plugin-rewrite-tag-filterでエラーのラベルが付いたものをslackへ通知します。
https://github.com/sowawa/fluent-plugin-slack

IncomingWebHookのキー発行は以下から。
https://xxx.slack.com/services/new

/etc/td-agent/td-agent.conf
<match rails.error>
  type slack
  webhook_url https://hooks.slack.com/services/*********/********/*********
  channel alert
  username Alert
  icon_emoji :ghost:
  flush_interval 60s
  message_keys level,message
  message "[%s] %s"
</match>
62
62
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
62
62