UNPKG

2.73 kBapplication/x-perlView Raw
1package Etsy::StatsD;
2use strict;
3use warnings;
4use IO::Socket;
5use Carp;
6
7our $VERSION = 1.000002;
8
9=head1 NAME
10
11Etsy::StatsD - Object-Oriented Client for Etsy's StatsD Server
12
13=head1 DESCRIPTION
14
15=cut
16
17=over
18
19=item new (HOST, PORT, SAMPLE_RATE)
20
21Create a new instance.
22
23=cut
24
25sub new {
26 my ( $class, $host, $port, $sample_rate ) = @_;
27 $host = 'localhost' unless defined $host;
28 $port = 8125 unless defined $port;
29
30 my $sock = new IO::Socket::INET(
31 PeerAddr => $host,
32 PeerPort => $port,
33 Proto => 'udp',
34 ) or croak "Failed to initialize socket: $!";
35
36 bless { socket => $sock, sample_rate => $sample_rate }, $class;
37}
38
39=item timing(STAT, TIME, SAMPLE_RATE)
40
41Log timing information
42
43=cut
44
45sub timing {
46 my ( $self, $stat, $time, $sample_rate ) = @_;
47 $self->send( { $stat => "$time|ms" }, $sample_rate );
48}
49
50=item increment(STATS, SAMPLE_RATE)
51
52Increment one of more stats counters.
53
54=cut
55
56sub increment {
57 my ( $self, $stats, $sample_rate ) = @_;
58 $self->update( $stats, 1, $sample_rate );
59}
60
61=item decrement(STATS, SAMPLE_RATE)
62
63Decrement one of more stats counters.
64
65=cut
66
67sub decrement {
68 my ( $self, $stats, $sample_rate ) = @_;
69 $self->update( $stats, -1, $sample_rate );
70}
71
72=item update(STATS, DELTA, SAMPLE_RATE)
73
74Update one of more stats counters by arbitrary amounts.
75
76=cut
77
78sub update {
79 my ( $self, $stats, $delta, $sample_rate ) = @_;
80 $delta = 1 unless defined $delta;
81 my %data;
82 if ( ref($stats) eq 'ARRAY' ) {
83 %data = map { $_ => "$delta|c" } @$stats;
84 }
85 else {
86 %data = ( $stats => "$delta|c" );
87 }
88 $self->send( \%data, $sample_rate );
89}
90
91=item send(DATA, SAMPLE_RATE)
92
93Sending logging data; implicitly called by most of the other methods.
94
95=back
96
97=cut
98
99sub send {
100 my ( $self, $data, $sample_rate ) = @_;
101 $sample_rate = $self->{sample_rate} unless defined $sample_rate;
102
103 my $sampled_data;
104 if ( defined($sample_rate) and $sample_rate < 1 ) {
105 while ( my ( $stat, $value ) = each %$data ) {
106 $sampled_data->{$stat} = "$value|\@$sample_rate" if rand() <= $sample_rate;
107 }
108 }
109 else {
110 $sampled_data = $data;
111 }
112
113 return '0 but true' unless keys %$sampled_data;
114
115 #failures in any of this can be silently ignored
116 my $count = 0;
117 my $socket = $self->{socket};
118 while ( my ( $stat, $value ) = each %$sampled_data ) {
119 _send_to_sock($socket, "$stat:$value\n");
120 ++$count;
121 }
122 return $count;
123}
124
125sub _send_to_sock( $$ ) {
126 my ($sock,$msg) = @_;
127 CORE::send( $sock, $msg, 0 );
128}
129
130=head1 SEE ALSO
131
132L<http://codeascraft.etsy.com/2011/02/15/measure-anything-measure-everything/>
133
134=head1 AUTHOR
135
136Steve Sanbeg L<http://www.buzzfeed.com/stv>
137
138=cut
139
1401;