fluentdをつかってrubyのログをmongoDBへ保存
まずは,rubyでログを吐いてそのログをfluentdで拾ってみる.
その後,mongoDBに保存する方法を書く.
準備
bundlerを使って管理するので以下を実行.
$ mkdir sample
$ cd sample
$ bundle init
bundle init
で作成された./Gemfile
に以下を追加.
gem 'fluentd' gem 'fluent-logger' gem 'fluent-plugin-mongo' gem 'bson_ext'
その後$ bundle insall --path vendor/bundle
する.
fluentdの設定ファイルを作る
# カレントディレクトリに設定ファイル作成
$ bundle exec fluentd --setup ./fluent
./fluent/fluent.conf
に以下の設定を追加.
portが8082でfluentd.test.**
に該当する標準入力があったら標準出力に出す.
<source>
type forward #標準入力
port 8082 #監視するポート
</source>
<match fluentd.test.**>
type stdout #標準出力
</match>
fluetndの起動
$ bundel exec fluentd -c ./fluent/fluent.conf -vv &
rubyでログを吐く.
./std.rb
に以下を追加
require 'fluent-logger' Fluent::Logger::FluentLogger.open(nil, host: 'localhost', port: 8082) Fluent::Logger.post("fluentd.test.follow", {"from"=>"userA", "to"=>"userB"})
bundle ruby std.rb
で実行する.
これで動くはず.
mongoDBに保存
上記だけではmongoDBに保存されないので続いて./fluent/fluent.conf
に以下を追加.
<match mongo.test>
type mongo
database test
collection mongo
host localhost
</match>
そして新しくmongo.rb
を作って以下を追加
require 'fluent-logger' Fluent::Logger::FluentLogger.open(nil, host: 'localhost', port: 8082) Fluent::Logger.post("mongo.test", {"from"=>"userA", "to"=>"userB"})
postの時の名前が変わってるだけです.
そしてbundle ruby mongo.rb
で実行する.
mongoで確認
$mongo
> db.test.find()
{ "_id" : ObjectId("52620cfeeb9049253a000001"), "from" : "userA", "to" : "userB", "time" : ISODate("2013-10-19T04:38:30Z") }
以上です.
参考URL
Store Apache Logs into MongoDB
Data Import from Ruby Applications
fluentdの簡単な使い方、設定方法一覧