fluent-plugin-mysql で time を insert する

UNIX/Linux歴が浅い自分にとって、awk等でログ解析をするのは結構壁が高い。ということで、Fluentdとそのプラグイン(GitHub - tagomoris/fluent-plugin-mysql)に飛びついたのだが、一つ残念だったのが

TODO: implement 'time' and 'tag' in key_names

なところ。
これを何とかしてみた。

1. MySQLに取り込める形で日時を出力する

標準の"%t"はFluentdに(?)先に取られてしまってどうにもならないので、MySQL出力用に「もう一つ」日時を出力しておく。datetime型に突っ込むことを想定して、フォーマットを指定しているところ("%{[%Y-%m-%d %H:%M:%S]}t")がポイント。

  LogFormat "\"%{X-Forwarded-For}i\" %l %u %t %{[%Y-%m-%d %H:%M:%S]}t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined-elb
  CustomLog log/acces_log combined-elb

2. td-agent.confの修正

送信側
# vi /etc/td-agent/td-agent.conf

<source>
  type tail
  path /usr/local/apache2/logs/access_log
format /^(?<host>[^ ]*) [^ ]* (?<user>[^ ]*) \[(?<time>[^\]]*)\] \[(?<strtime>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^ ]*) +\S*)?" (?<code>[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)")?$/
time_format %d/%b/%Y:%H:%M:%S %z
#  format apache
  tag apache.access
  pos_file /var/log/td-agent/apache.pos
</source>

(参考資料:http://fluentd.org/doc/plugin.html?#tail)

受信側
# vi /etc/td-agent/td-agent.conf

<match>
  type copy
  <store>
    type file
    path /var/log/apache/access_log
  </store>

  <store>
    type mysql
    host localhost
    database your_db_name
    username your_user_name
    password your_password
    key_names host,user,method,path,code,size,referer,agent,strtime
    table access_log
    columns host,user,method,path,code,size,referer,agent,created
# not used    flush_intervals 5s
  </store>
</match>

上記設定中に出てくる"created"はdatetime型。

このやり方で、無事アクセス日時の保存に成功^^