| 1 | # ABSTRACT: File backend for Net::Statsd::Server | ||
| 2 | |||
| 3 | package Net::Statsd::Server::Backend::File; | ||
| 4 | $Net::Statsd::Server::Backend::File::VERSION = '0.20'; | ||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | use base qw(Net::Statsd::Server::Backend); | ||
| 8 | use Time::HiRes (); | ||
| 9 | |||
| 10 | sub init { | ||
| 11 | my ($self, $startup_time, $config) = @_; | ||
| 12 | |||
| 13 | $self->{out_file} = $config->{file} && $config->{file}->{name}; | ||
| 14 | $self->{enabled} = defined $self->{out_file} ? 1 : 0; | ||
| 15 | |||
| 16 | return; | ||
| 17 | } | ||
| 18 | |||
| 19 | sub flush { | ||
| 20 | my ($self, $timestamp, $metrics) = @_; | ||
| 21 | |||
| 22 | return unless $self->{enabled}; | ||
| 23 | |||
| 24 | my $str = ""; | ||
| 25 | |||
| 26 | for (keys %{ $metrics->{counters} }) { | ||
| 27 | next if m{^statsd\.}; | ||
| 28 | $str .= sprintf "c\t%s\t%d\n", $_, $metrics->{counters}->{$_}; | ||
| 29 | } | ||
| 30 | |||
| 31 | for (keys %{ $metrics->{timers} }) { | ||
| 32 | next if m{^statsd\.}; | ||
| 33 | $str .= sprintf "t\t%s\t%.6f\n", $_, $metrics->{timers}->{$_}; | ||
| 34 | } | ||
| 35 | |||
| 36 | for (keys %{ $metrics->{gauges} }) { | ||
| 37 | next if m{^statsd\.}; | ||
| 38 | $str .= sprintf "g\t%s\t%.6f\n", $_, $metrics->{gauges}->{$_}; | ||
| 39 | } | ||
| 40 | |||
| 41 | for (keys %{ $metrics->{sets} }) { | ||
| 42 | next if m{^statsd\.}; | ||
| 43 | my $set_as_string = join(";", keys %{ $metrics->{sets}->{$_} }); | ||
| 44 | $str .= sprintf "s\t%s\t%s\n", $_, $set_as_string; | ||
| 45 | } | ||
| 46 | |||
| 47 | if ($str) { | ||
| 48 | if (open my $fh, '>>', $self->{out_file}) { | ||
| 49 | $fh->printflush($str) or do { | ||
| 50 | $self->{lastException} = [Time::HiRes::gettimeofday]; | ||
| 51 | }; | ||
| 52 | $fh->close; | ||
| 53 | } | ||
| 54 | } | ||
| 55 | |||
| 56 | $self->{lastFlush} = [Time::HiRes::gettimeofday]; | ||
| 57 | |||
| 58 | } | ||
| 59 | |||
| 60 | sub status { | ||
| 61 | my ($self) = @_; | ||
| 62 | return { | ||
| 63 | last_flush => $self->since($self->{lastFlush}), | ||
| 64 | last_exception => $self->since($self->{lastException}), | ||
| 65 | }; | ||
| 66 | } | ||
| 67 | |||
| 68 | 1; |