LoginSignup
16
15

More than 5 years have passed since last update.

Apache のエラーログを slack に送る

Last updated at Posted at 2015-09-18

はじめに

ようやく slack を使い始めたので,手始めに Apache のエラーログを転送してみる.ほぼ ここ にある通りで動作するが,多少変更した部分もあるので備忘録も兼ねてまとめておく.

準備

ログの収集・転送には fluentd を使う.fluentd はインストールされているものとして,今回必要となるプラグインをそれぞれインストールする.

$ sudo td-agent-gem install fluent-plugin-slack
$ sudo td-agent-gem install fluent-plugin-rewrite-tag-filter
$ sudo td-agent-gem install fluent-plugin-record-reformer

また,apache のログが置かれている /var/log/apache2 へのアクセスは root 権限が必要になっている.
そのため,fluentdの実行ユーザを root に変更しておく.Ubuntu の場合,/etc/init.d/td-agent を開き td-agent から変更する(参考).

td-agent
# TD_AGENT_USER=td-agent
# TD_AGENT_GROUP=td-agent
TD_AGENT_USER=root
TD_AGENT_GROUP=root

CentOS の場合,/etc/sysconfig/td-agent に下記を追加する.

td-agent
TD_AGENT_USER=root
TD_AGENT_GROUP=root

fluentd の設定

次に fluentd の設定を行う.使った設定は下記の通り.

td-agent.conf
####
## Source descriptions:
##

## apache error log.
<source>
  type tail
  format /^\[(?<time>[^\]]*)\] \[(?<level>[^\]]*)\] \[client (?<client>[^\]]*)\] (?<message>.*)$/
  time_format %a %b %d %H:%M:%S %Y
  pos_file /tmp/td-agent/httpd_error_log.pos
  path /var/log/httpd/error_log
  tag httpd.error_log
</source>

####
## Edit descriptions:
##
<match httpd.error_log>
  type rewrite_tag_filter
  rewriterule1 level error slack.${tag}
</match>

<match slack.**>
  type record_reformer
  tag reformed.${tag}
  <record>
    source_id ${tag_suffix[1]}
  </record>
</match>

####
## Output descriptions:
##
<match reformed.slack.**>
  type slack
  webhook_url <slack の設定からコピー>
  channel admin
  username fluentd
  title_keys source_id
  title %s
  color danger
  flush_interval 5s
</match>

どのサーバから来たエラーなのかタイトルに入れて表示しようと思い,初めはホスト名をタグに含めてタグからタイトルを構成しようとしていた.だが,slack プラグインはタグのプレースホルダに対応していないようなので,record_reformer プラグインで source_id を追加することにした.

あと,ログと日付のフォーマットは環境によって異なるので,拾ってきた値をそのまま使うとエラーの原因になる.

format /^\[(?<time>[^\]]*)\] \[(?<level>[^\]]*)\] \[client (?<client>[^\]]*)\] (?<message>.*)$/
time_format %a %b %d %H:%M:%S %Y

エラーが出る場合は上記の設定を適切なものに変更する.

16
15
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
16
15