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