forked from DataDog/dogstatsd-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatsd.py
More file actions
182 lines (147 loc) · 5.89 KB
/
statsd.py
File metadata and controls
182 lines (147 loc) · 5.89 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""
DogStatsd is a Python client for DogStatsd, a Statsd fork for Datadog.
"""
import logging
from random import random
from time import time
import socket
try:
from itertools import imap
except ImportError:
imap = map
log = logging.getLogger('dogstatsd')
class DogStatsd(object):
def __init__(self, host='localhost', port=8125):
"""
Initialize a DogStatsd object.
>>> statsd = DogStatsd()
:param host: the host of the DogStatsd server.
:param port: the port of the DogStatsd server.
"""
self._host = None
self._port = None
self.socket = None
self.connect(host, port)
def connect(self, host, port):
"""
Connect to the statsd server on the given host and port.
"""
self._host = host
self._port = int(port)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.connect((self._host, self._port))
def gauge(self, metric, value, tags=None, sample_rate=1):
"""
Record the value of a gauge, optionally setting a list of tags and a
sample rate.
>>> statsd.gauge('users.online', 123)
>>> statsd.gauge('active.connections', 1001, tags=["protocol:http"])
"""
return self._send(metric, 'g', value, tags, sample_rate)
def increment(self, metric, value=1, tags=None, sample_rate=1):
"""
Increment a counter, optionally setting a value, tags and a sample
rate.
>>> statsd.increment('page.views')
>>> statsd.increment('files.transferred', 124)
"""
self._send(metric, 'c', value, tags, sample_rate)
def decrement(self, metric, value=1, tags=None, sample_rate=1):
"""
Decrement a counter, optionally setting a value, tags and a sample
rate.
>>> statsd.decrement('files.remaining')
>>> statsd.decrement('active.connections', 2)
"""
self._send(metric, 'c', -value, tags, sample_rate)
def histogram(self, metric, value, tags=None, sample_rate=1):
"""
Sample a histogram value, optionally setting tags and a sample rate.
>>> statsd.histogram('uploaded.file.size', 1445)
>>> statsd.histogram('album.photo.count', 26, tags=["gender:female"])
"""
self._send(metric, 'h', value, tags, sample_rate)
def timing(self, metric, value, tags=None, sample_rate=1):
"""
Record a timing, optionally setting tags and a sample rate.
>>> statsd.timing("query.response.time", 1234)
"""
self._send(metric, 'ms', value, tags, sample_rate)
def timed(self, metric, tags=None, sample_rate=1):
"""
A decorator that will measure the distribution of a function's run time.
Optionally specify a list of tag or a sample rate.
::
@statsd.timed('user.query.time', sample_rate=0.5)
def get_user(user_id):
# Do what you need to ...
pass
# Is equivalent to ...
start = time.time()
try:
get_user(user_id)
finally:
statsd.timing('user.query.time', time.time() - start)
"""
def wrapper(func):
def wrapped(*args, **kwargs):
start = time()
result = func(*args, **kwargs)
self.timing(metric, time() - start, tags=tags, sample_rate=sample_rate)
return result
wrapped.__name__ = func.__name__
wrapped.__doc__ = func.__doc__
wrapped.__dict__.update(func.__dict__)
return wrapped
return wrapper
def set(self, metric, value, tags=None, sample_rate=1):
"""
Sample a set value.
>>> statsd.set('visitors.uniques', 999)
"""
self._send(metric, 's', value, tags, sample_rate)
def _send(self, metric, metric_type, value, tags, sample_rate):
if sample_rate != 1 and random() > sample_rate:
return
payload = [metric, ":", value, "|", metric_type]
if sample_rate != 1:
payload.extend(["|@", sample_rate])
if tags:
payload.extend(["|#", ",".join(tags)])
try:
self.socket.send("".join(imap(str, payload)))
except socket.error:
log.exception("Error submitting metric")
def _escape_event_content(self, string):
return string.replace('\n', '\\n')
def event(self, title, text, alert_type=None, aggregation_key=None, source_type_name=None, date_happened=None, priority=None, tags=None, hostname=None):
"""
Send an event. Attributes are the same as the Event API.
http://docs.datadoghq.com/api/
>>> statsd.event('Man down!', 'This server needs assistance.')
>>> statsd.event('The web server restarted', 'The web server is up again', alert_type='success')
"""
title = self._escape_event_content(title)
text = self._escape_event_content(text)
string = u'_e{%d,%d}:%s|%s' % (len(title), len(text), title, text)
if date_happened:
string = '%s|d:%d' % (string, date_happened)
if hostname:
string = '%s|h:%s' % (string, hostname)
if aggregation_key:
string = '%s|k:%s' % (string, aggregation_key)
if priority:
string = '%s|p:%s' % (string, priority)
if source_type_name:
string = '%s|s:%s' % (string, source_type_name)
if alert_type:
string = '%s|t:%s' % (string, alert_type)
if tags:
string = '%s|#%s' % (string, ','.join(tags))
if len(string) > 8 * 1024:
raise Exception(u'Event "%s" payload is too big (more that 8KB), event discarded' % title)
try:
self.socket.send(string)
except Exception:
log.exception(u'Error submitting event "%s"' % title)
statsd = DogStatsd()