EC2にfluentdをいれてapacheのアクセスログをs3に保存してみる。
ruby1.9.2以降の環境を作る
fluentdにはruby1.9.2以上が必要らしいのでruby1.9.xをインストール。
rvmで1.9.3をインストールしました。
ちなみにこの記事を書いてる時点でのAmazon Linuxのrubyは1.8.7。
rvmでruby環境をインストールする場合、fluentdのプラグインに必要なライブラリを、
事前にOSにインストールしておかないまずい。今回の場合、以下のライブラリが必要。
libxml2-devel, libxslt, openssl
$ curl -L get.rvm.io | bash -s stable $ export PATH=$PATH:~/.rvm/bin $ source ~/.rvm/scripts/rvm $ rvm install 1.9.3 $ rvm use 1.9.3 $ ruby -v ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
fluentdのインストール
gemをつかってfluentdをインストール
gem install fluentd . . . Successfully installed msgpack-0.4.7 Successfully installed json-1.7.5 Successfully installed yajl-ruby-1.1.0 Successfully installed iobuffer-1.1.2 Successfully installed cool.io-1.1.0 Successfully installed http_parser.rb-0.5.3 Successfully installed fluentd-0.10.25
いろいろ一緒にインストールされた。
ひとまず動かしてみる
$ fluentd --setup ./fluent # configファイルが作成される Installed ./fluent/fluent.conf. $ fluentd -c ./fluent/fluent.conf -vv & # これでfluentdが起動する $ echo '{"json":"hello fluentd"}' | fluent-cat debug.text 2012-09-20 08:00:34 +0000: plugin/in_forward.rb:139:initialize: accepted fluent socket object_id=19099020 2012-09-20 08:00:34 +0000 debug.text: {"json":"hello fluentd"} 2012-09-20 08:00:34 +0000: plugin/in_forward.rb:180:on_close: closed fluent socket object_id=19099020
configファイルを見ると下記のような記述になっているので、上記のように標準出力にjsonが表示されてるのでOKとおもわれる。
## match tag=debug.** and dump to console <match debug.**> type stdout </match>
あと、こんなconfigファイルの記述があったのでhttp経由でのログ出力もためしてみた。
# HTTP input # http://localhost:8888/<tag>?json=<json> <source> type http port 8888 </source>
こんな感じ。
$ curl http://localhost:8888/debug?json=%7b%22title%22%3a%22hello%20fluentd%22%7d 2012-09-20 08:12:56 +0000 debug: {"title":"hello fluentd"}
fluentdでapacheのアクセスログを監視するように設定する
fluentd-plugin-s3をインストール
$ gem install fluent-plugin-s3 . . . Successfully installed uuidtools-2.1.3 Successfully installed multi_json-1.3.6 Successfully installed multi_xml-0.5.1 Successfully installed httparty-0.9.0 Successfully installed nokogiri-1.5.5 Successfully installed aws-sdk-1.1.4 Successfully installed fluent-plugin-s3-0.2.2 7 gems installed . . .
いろいろインストールされた。
次にfluentdのconfigファイルを書く
<source> type tail format apache path /var/log/httpd/access_log tag apache.access </source> <match apache.access> type s3 aws_key_id YOUR_AWS_ACCESS_KEY aws_sec_key YOUR_AWS_SECRET_KEY s3_bucket factory-fluentd s3_endpoint s3-ap-northeast-1.amazonaws.com path / buffer_path /tmp/fluentd_s3 time_slice_format %Y%m%d-%H time_slice_wait 10m #flush_interval 5s これを書くと、timesliceを無視して指定したインターバルごとにs3にflushされる。 utc </match>
これでapacheにアクセスしてログを吐かせるとs3にちゃんとオブジェクト(ファイル)ができあがってました。便利。
ログも1行ずつs3に書きに行くわけではなくてある程度バッファして書き込んでいってくれるのでs3のAPI叩きすぎてクラウド破産、なんてことにはならずに済みそうですね。
あとは、転送失敗時の処理とか、バッファファイルのためのディスク領域が足りなくなっちゃった時の対処とか気になるところですが今回はこれでおしまいということで。