アクトインディ開発者ブログ

子供とお出かけ情報「いこーよ」を運営する、アクトインディ株式会社の開発者ブログです

Rails ログを MongoDB と S3 につっこむ

こんにちは、tahara です。

そろそろデータマイニングなんか初めてみたいな、と思っている今日このごろです。 その前段階として、Fluentd を使って Rails のログを MongoDB と S3 に格納するようにしてみました。

で、そのために act-fluent-logger-rails を作りました。 Rails から fluent-logger-ruby を使う gem です。

Gemfile に gem 'act-fluent-logger-rails' を追加して bundle install を実行し、 config/environments/production.rb などで ActFluentLoggerRails::Logger を使うように指定します。

config.log_level = :info
config.logger = ActFluentLoggerRails::Logger.new

config/fluent-logger.yml を作ります。

development:
  fluent_host:   '127.0.0.1'
  fluent_port:   24224
  tag:           'foo'
  messages_type: 'string'

test:
  fluent_host:   '127.0.0.1'
  fluent_port:   24224
  tag:           'foo'
  messages_type: 'string'

production:
  fluent_host:   '127.0.0.1'
  fluent_port:   24224
  tag:           'foo'
  messages_type: 'string'

act-fluent-logger-rails は1リクエスト中の全ログ出力を、1つのログイベントとして Fluentd に出力します。 messages_type: 'string' の時はこんな感じで各ログメッセージを join("\n") して String で

2013-01-18T15:04:50+09:00 foo {"messages":"Started GET \"/\" for 127.0.0.1 at 2013-01-18 15:04:49 +0900\nProcessing by TopController#index as HTML\nCompleted 200 OK in 635ms (Views: 479.3ms | ActiveRecord: 39.6ms)"],"level":"INFO"}

messages_type: 'array' にした時はこんな感じで各ログメッセージを Array で出力します。

2013-01-18T15:04:50+09:00 foo {"messages":["Started GET \"/\" for 127.0.0.1 at 2013-01-18 15:04:49 +0900","Processing by TopController#index as HTML","Completed 200 OK in 635ms (Views: 479.3ms | ActiveRecord: 39.6ms)"],"level":"INFO"}

Rails の動くサーバに td-agent をインストールして次の設定を行ないログサーバにログをフォワードします。

/etc/td-agent/td-agent.conf

<match foo>
  type forward

  <server>
    name log
    host log.example.com
    port 24224
  </server>

  buffer_type file
  buffer_path /foo/bar/fluent
  buffer_chunk_limit 8m
  buffer_queue_limit 256
</match>

ログサーバ log.example.com にも td-agent をインストールして次の設定を行ない S3 と MongoDB にログをつっこみます。

<source>
  type forward
</source>

<match foo>
  type copy

  #### s3
  <store>
    type s3

    aws_key_id XXXXXXXXXXXXXXXX
    aws_sec_key xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    s3_bucket iko-yo.net
    s3_endpoint s3-ap-northeast-1.amazonaws.com
    path logs/app/

    time_slice_format %Y%m%d
    time_slice_wait 10m

    buffer_type file
    buffer_path /opt/fluent/buffer/s3
    buffer_chunk_limit 256m
    buffer_queue_limit 8
  </store>

  #### mongoDB
  <store>
    type mongo_outing

    database outing
    collection logs.app
    nodes xxx.ap-northeast-1.compute.amazonaws.com:27017,yyy.ap-northeast-1.compute.amazonaws.com:27018

    # for capped collection
    capped
    capped_size 4096m

    # flush
    flush_interval 10s

    buffer_type file
    buffer_path /opt/fluent/buffer/mongo
    buffer_chunk_limit 8m
    buffer_queue_limit 256
  </store>
</match>

さて、データマイニングがんばります!