forked from statsd/statsd
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_example.py
More file actions
Latest commit
89 lines (77 loc) · 2.52 KB
/
Copy pathpython_example.py
File metadata and controls
89 lines (77 loc) · 2.52 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
# python_example.py
# Steve Ivy <steveivy@gmail.com>
# http://monkinetic.com
# this file expects local_settings.py to be in the same dir, with statsd host and port information:
#
# statsd_host = 'localhost'
# statsd_port = 8125
# Sends statistics to the stats daemon over UDP
classStatsd(object):
@staticmethod
deftiming(stats, time, sample_rate=1):
"""
Log timing information
>>> from python_example import Statsd
>>> Statsd.timing('some.time','500|ms')
"""
Statsd.update_stats(stats, time, sample_rate)
@staticmethod
defincrement(stats, sample_rate=1):
"""
Increments one or more stats counters
>>> Statsd.increment('some.int')
>>> Statsd.increment('some.int',0.5)
"""
Statsd.update_stats(stats, 1, sample_rate)
@staticmethod
defdecrement(stats, sample_rate=1):
"""
Decrements one or more stats counters
>>> Statsd.decrement('some.int')
"""
Statsd.update_stats(stats, -1, sample_rate)
@staticmethod
defupdate_stats(stats, delta=1, sampleRate=1):
"""
Updates one or more stats counters by arbitrary amounts
>>> Statsd.update_stats('some.int',10)
"""
if (type(stats) isnotlist):
stats= [stats]
data= {}
forstatinstats:
data[stat] ="%s|c"%delta
Statsd.send(data, sampleRate)
@staticmethod
defsend(data, sample_rate=1):
"""
Squirt the metrics over UDP
"""
try:
importlocal_settingsassettings
host=settings.statsd_host
port=settings.statsd_port
addr=(host, port)
exceptError:
exit(1)
sampled_data= {}
if(sample_rate<1):
importrandom
ifrandom.random() <=sample_rate:
forstatindata.keys():
value=data[stat]
sampled_data[stat] ="%s|@%s"%(value, sample_rate)
else:
sampled_data=data
fromsocketimport*
udp_sock=socket(AF_INET, SOCK_DGRAM)
try:
forstatinsampled_data.keys():
value=data[stat]
send_data="%s:%s"% (stat, value)
udp_sock.sendto(send_data, addr)
except:
importsys
frompprintimportpprint
print"Unexpected error:", pprint(sys.exc_info())
pass# we don't care