LoginSignup
15
18

More than 5 years have passed since last update.

FluentdでRuby DSLを使う

Last updated at Posted at 2014-12-14

Ruby DSLとは?

fluentdの設定のRuby DSL的な記法。

--use-v1-configでRubyのコードを設定に書くことが出来ますが、さらに柔軟な記法が可能になる。

以前調べていたことがあるので、まとめてみる。

実行方法

設定ファイルの拡張子がrbであればDSLモードで起動する

$ fluentd -c fluent.rb

どう書く?

これが、

fluent.conf
<match {foo,bar}.**>
  type stdout
</match>

<match hoge.**>
  type copy
  <store>
    type stdout
  </store>
  <store>
    type file
    path /tmp/hoge.txt
  </store>
</match>

<source>
  type forward
</source>

こうなる。

fluent.rb
match ('{foo,bar}.**') {
  type :stdout
}

match ('hoge.**') {
  type :copy
  store {
    type :stdout
  }
  store {
    type :file
    path "/tmp/hoge.txt"
  }
}

source {
  type :forward
}

eachを使う

これだけだとちょっとメリットがわかりづらいので。

もうちょっとわかりやすく。

これが、

fluent.conf
<match foo1.**>
  type stdout
</match>

<match foo2.**>
  type stdout
</match>

<match foo3.**>
  type stdout
</match>

<match foo4.**>
  type stdout
</match>

こうなる。

fluent.rb
(1..4).each do |i|
  match ("foo#{i}.**") {
    type :stdout
  }
end

ifで分岐

web系のサーバではtailするとか

fluent.rb
source {
  type :forward
}

hostname = ruby.open('|hostname').read.strip

if hostname.include?('web')
  source {
      type :tail
      path "/var/log/httpd/access_log.ltsv"
      format 'ltsv'
      time_key 'time'
      time_format "%d/%b/%Y:%H:%M:%S %z"
      pos_file "/tmp/access.pos"
      tag "hogehoge.batch"
  }
end

三項演算子とか

hostname = ruby.open('|hostname').read.strip
match ('hoge.**') {
  type :file
  path hostname.include?('web') ? "/tmp/web.txt" : "/tmp/batch.txt"
}

外部ライブラリ読み込む

dotenv使ってHIPCHATのtokenを隠蔽するとか

fluent.rb

ruby.require 'dotenv'
Dotenv.load!
ruby.puts ENV['HIPCHAT_API_TOKEN']

match ('hipchat.**') do
  type :hipchat
  default_room '000000'
  api_token ENV['HIPCHAT_API_TOKEN']
  default_from 'fluentd'
  default_color 'red'
  default_notify 0
  default_format 'html'
end

openとかputsとかrequireなどのrubyの処理を記述する際は、prefixにrubyをつける必要がある。

pluginのパラメータにArrayやHashを使う

plugin側が対応している必要があるが、ArrayやHashも使える。

fluent.rb
name = 'user3'
match ('hoge.**') do
  type :hoge
  tags [ "java", "ruby" ]
  user  id: 3, name: name
  users [
    { id: 1, name: 'user1' },
    { id: 2, name: 'user2' }
  ]
end
  • 上記の例ではtagsはArray、userはHash。
  • usersの例のように改行して記述できる。(v1記法でも可能)

td-agentで使う場合

/usr/sbin/td-agentを書き換える

/usr/sbin/td-agent
-ENV["FLUENT_CONF"]="/etc/td-agent/td-agent.conf"
+ENV["FLUENT_CONF"]="/etc/td-agent/td-agent.rb"
  • 拡張子が.rbだったらdslで設定が読み込まれる。(参考)

備考

  • includeは現状は使えないが、ここにissueが上がっている。
    • rubyなのでevalでゴニョゴニョやれば出来るかもしれない。。(未確認)
15
18
0

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
15
18