Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 127 lines (88 sloc) 2.285 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
package Etsy::StatsD;
use strict;
use warnings;
use IO::Socket;
use Carp;

=head1 NAME

Etsy::StatsD

=head1 DESCRIPTION

=cut

=over

=item new (HOST, PORT, SAMPLE_RATE)

Create a new instance.

=cut

sub new {
my ($class, $host, $port, $sample_rate) = @_;
$host = 'localhost' unless defined $host;
$port = 8125 unless defined $port;

my $sock = new IO::Socket::INET(
PeerAddr => $host,
PeerPort => $port,
Proto => 'udp',
) or croak "Failed to initialize socket: $!";

bless {socket=>$sock, sample_rate=>$sample_rate}, $class;
}

=item timing(STAT, TIME, SAMPLE_RATE)

Log timing information

=cut

sub timing {
my ($self, $stat, $time, $sample_rate) = @_;
$self->send({$stat => "$time|ms"}, $sample_rate);
}

=item increment(STATS, SAMPLE_RATE)

Increment one of more stats counters.

=cut

sub increment {
my ($self, $stats, $sample_rate) = @_;
$self->update($stats, 1, $sample_rate);
}

=item decrement(STATS, SAMPLE_RATE)

Decrement one of more stats counters.

=cut

sub decrement {
my ($self, $stats, $sample_rate) = @_;
$self->update($stats, -1, $sample_rate);
}

=item update(STATS, DELTA, SAMPLE_RATE)

Update one of more stats counters by arbitrary amounts.

=cut

sub update {
my ($self, $stats, $delta, $sample_rate) = @_;
$delta = 1 unless defined $delta;
my %data;
if (ref($stats) eq 'ARRAY') {
%data = map {$_ => "$delta|c"} @$stats;
} else {
%data = ($stats => "$delta|c");
}
$self->send(\%data, $sample_rate);
}

=item send(DATA, SAMPLE_RATE)

Sending logging data; implicitly called by most of the other methods.

=back

=cut

sub send {
my ($self, $data, $sample_rate) = @_;
$sample_rate = $self->{sample_rate} unless defined $sample_rate;

my $sampled_data;
if ( defined($sample_rate) and $sample_rate < 1 ){
while (my($stat,$value) = each %$data) {
$sampled_data->{$stat} = "$value|\@$sample_rate" if rand() <= $sample_rate;
}
} else {
$sampled_data = $data;
}

return '0 but true' unless keys %$sampled_data;

#failures in any of this can be silently ignored
my $count=0;
my $socket = $self->{socket};
while (my($stat,$value) = each %$sampled_data) {
print $socket "$stat:$value\n";
++$count;
}
return $count;
}

=head1 AUTHOR

Steve Sanbeg L<http://www.buzzfeed.com/stv>

=cut

1;
Something went wrong with that request. Please try again.