higehikiのブログ

iPhoneアプリ「ログ雀」の中の人です。

EC2にfluentdとmongodbをいれて動かしてみた。

DynamoDBと格闘の末、mongoDBで頑張ってみる結論を出しました。
開発環境にとりあえず全部突っ込んでみる。

構築ログ (Root権限で作業)

# リポジトリ追加
vim /etc/yum.repos.d/td.repo
[treasuredata]
name=TreasureData
baseurl=http://packages.treasure-data.com/redhat/$basearch
gpgcheck=0

# td-agent インストール
yum install td-agent

# リポジトリ追加
vim /etc/yum.repos.d/10gen.repo
[10gen]
name=10gen Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64
gpgcheck=0

# mongodb インストール
yum -y install mongo-10gen-server --enablerepo=10gen
# 下記コマンドだとconflictが起きる…
# yum install  mongo-10gen* --enablerepo=10gen 

# mongodb起動
/etc/init.d/mongod start

# fluentでの log backupディレクトリ作成
mkdir /var/log/fluent
chown td-agent:td-agent /var/log/fluent

# fluentの設定ファイル修正
vim /etc/td-agent/td-agent.conf
別途記載

# mongodb用fluentプラグイン インストール
/usr/lib64/fluent/ruby/bin/fluent-gem install fluent-plugin-mongo

# ログリライト fluentプラグイン インストール
/usr/lib64/fluent/ruby/bin/fluent-gem install fluent-plugin-rewrite

# fluentd 起動
service td-agent start

流れはこんな感じ。

fluentの設定ファイルで制御するようで、プラグインを突っ込んでいけば、けっこう色々対応することができるのは便利です、便利過ぎます。

今回入れた fluent-plugin-rewrite は、かなり人気のプラグインのようで、今回の利用用途は公式サイトのサンプルでもある特定のアクセスのみをログに出したいという要件を実現するため。
アクセスログの解析に画像やCSS,JSなんてどうでもいいや!って場合、すごい便利。
そんな設定は以下。

<source>
  type tail
  format apache
  path /var/log/httpd/access_log
  pos_file /var/log/td-agent/access_log.pos
  tag apache.access
</source>

# log rewrite filter
<match apache.access>
  type rewrite
  remove_prefix apache.access
  add_prefix filtered
  <rule>
    key     path
    pattern ^\/(?:image|css|js|assets|wordpress)
    ignore  true
  </rule>
  <rule>
    key     code
    pattern ^(?!200)\\d+$
    ignore  true
  </rule>
</match>

# 別ディレクトリとmongoDBにそれぞれ出力する
<match filtered.**>
  type copy
  <store>
    type file
    path /var/log/fluent/access_log
  </store>
  <store>
    # 出力先
    type mongo
    # DB名とコレクション名
    database apache
    collection access
    # MongoDB接続先とポート
    host localhost
    port 27017
    # インターバル
    flush_interval 10s
  </store>
</match>

これで、mongodbに突っ込みつつlocalの別ディレクトリへ吐き出すことが出来ました。

次は別ホストへ転送してみよう。