LoginSignup
39

More than 5 years have passed since last update.

Mac OS X に Fluentd をインストールして Ruby からログ出力してみる

Last updated at Posted at 2012-11-28

Fluentd とは

"Fluentd" is a lightweight and flexible log collector. Fluentd receives logs as JSON streams, buffers them, and sends them to other systems like Amazon S3, MongoDB, Hadoop, or other Fluends.

前提

Ruby >= 1.9.2 が必要です。
ここでは RVM で入れた 1.9.3 を使って行いました。

$ ruby -v
ruby 1.9.3p327 (2012-11-10 revision 37606) [x86_64-darwin12.2.0]

インストール & セットアップ

gem を使って fluentd をインストールします。

$ gem install fluentd

設定ファイルを作成します。

$ fluentd --setup ./fluent
Installed ./fluent/fluent.conf.

これで ./fluent/fluent.conf に設定ファイルができました。

デフォルトでは、TCP(24224), HTTP(8888) の入力を受けつけ、debug.** というタグを持ったメッセージを標準出力に出力するように設定されています。

fluent.conf
## built-in TCP input
## $ echo <json> | fluent-cat <tag>
<source>
  type forward
</source>

# HTTP input
# http://localhost:8888/<tag>?json=<json>
<source>
  type http
  port 8888
</source>

## match tag=debug.** and dump to console
<match debug.**>
  type stdout
</match>

起動して試してみる

$ fluentd -c ./fluent/fluent.conf

とすると Fluentd が起動します。

2012-11-28 12:39:28 +0900: starting fluentd-0.10.29
2012-11-28 12:39:28 +0900: reading config file path="./fluent/fluent.conf"
2012-11-28 12:39:28 +0900: adding source type="forward"
2012-11-28 12:39:28 +0900: adding source type="http"
2012-11-28 12:39:28 +0900: adding source type="debug_agent"
2012-11-28 12:39:28 +0900: adding match pattern="debug.**" type="stdout"
2012-11-28 12:39:28 +0900: listening fluent socket on 0.0.0.0:24224
2012-11-28 12:39:28 +0900: listening dRuby uri="druby://0.0.0.0:24230" object="Engine"

試しに、別のシェルから

$ echo '{"hoge":"fuga"}' | fluent-cat debug.forward

とすると、元のシェルの方に

2012-11-28 12:40:47 +0900 debug.forward: {"hoge":"fuga"}

というようにログが出力されるかと思います。
これが、debug.forward というタグと、{"hoge":"fuga"} というメッセージを持った Fluentd のログになります。

HTTP でも投げてみましょう。

$ curl http://localhost:8888/debug.http -F 'json={"foo":"bar"}'

とすれば、

2012-11-28 12:42:51 +0900 debug.http: {"foo":"bar"}

のように出力が確認できると思います。

Ruby からログ出力してみる

まず、gem で fluent-logger をインストールしておきます。

$ gem install fluent-logger

それでは irb からログ出力をしてみます。

> require 'fluent-logger'
> Fluent::Logger::FluentLogger.open(nil, host: 'localhost', port: 24224)
> Fluent::Logger.post('debug.ruby', { hoge: 'fuga', foo: 'bar' })

これで、Fluend を動かしているシェルに

2012-11-28 11:58:22 +0900 debug.ruby: {"hoge":"fuga","foo":"bar"}

というようなログが出力されました。

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
39