Fluent::Logger(Perl)をFluentd 0.14のSub-second timeに対応した

Fluentd 0.14 がリリースされましたね。

Fluentd v0.14.0 has been released | Fluentd

新機能が盛りだくさんですが、そのうちの一つ Sub-second time (秒未満の解像度のtimestamp) に Fluent::Logger 0.18で対応しました。

<source>
  type forward
</source>

<match **>
  @type file
  path  ./test
  time_format %Y-%m-%dT%H:%M:%S.%N
</match>

このような fluentd.conf で fluentd 0.14 で起動して、以下のように event_time オプションを真にした Fluent::Logger から送信すると、

#!/usr/bin/env perl
use 5.12.0;
use Fluent::Logger;
use Time::HiRes;
my $logger = Fluent::Logger->new( event_time => 1 );
$logger->post(
    test => { foo => "bar" },
);
$logger->post_with_time(
    test => { foo => "baz" },
    1464845619.12345, # floatで指定
);

以下のように秒以下の精度を持った時刻でログを送信できます。

2016-06-02T14:40:52.251250982    test    {"foo":"bar"}
2016-06-02T14:33:39.123450040    test    {"foo":"baz"}

Perl側のinterfaceは浮動小数点数なので、正確にはnanosecond単位の精度はありません。もし精度が必要なら、floatではない値で指定できるような方法を検討するのでお知らせください。時刻指定なしの post() では内部で Time::HiRes::time() を呼び出してその時刻を送信しています。

ちなみに送信先が fluentd 0.12 の場合に event_time => 1 で送信するとエラーが発生しますのでご注意ください。(クラッシュはしないようですが)

[error]: forward error error=#<MessagePack::MalformedFormatError: invalid byte>
error_class=MessagePack::MalformedFormatError

Enjoy!