statsd/examples/python_example.py

85 строки
2.5 KiB
Python
Исходник Обычный вид История

# python_example.py
# Steve Ivy <steveivy@gmail.com>
# http://monkinetic.com
2012-08-30 21:04:47 +04:00
from __future__ import print_function
from random import random
from socket import socket, AF_INET, SOCK_DGRAM
# Sends statistics to the stats daemon over UDP
class StatsdClient(object):
def __init__(self, host='localhost', port=8125):
2012-12-10 01:00:36 +04:00
self.addr = (host, port)
def timing(self, stat, time, sample_rate=1):
2011-02-16 08:26:43 +03:00
"""
Log timing information
2012-12-10 00:57:57 +04:00
>>> from python_example import StatsdClient
>>> client = StatsdClient()
>>> client.timing('some.time', 500)
2011-02-16 08:26:43 +03:00
"""
stats = {}
2012-12-23 15:13:19 +04:00
stats[stat] = "{0}|ms".format(time)
self.send(stats, sample_rate)
def increment(self, stats, sample_rate=1):
2011-02-16 08:26:43 +03:00
"""
Increments one or more stats counters
2012-12-10 00:57:57 +04:00
>>> client = StatsdClient()
>>> client.increment('some.int')
2012-12-10 01:00:36 +04:00
>>> client.increment('some.int', 0.5)
2011-02-16 08:26:43 +03:00
"""
self.update_stats(stats, 1, sample_rate)
def decrement(self, stats, sample_rate=1):
2011-02-16 08:26:43 +03:00
"""
Decrements one or more stats counters
2012-12-10 00:57:57 +04:00
>>> client = StatsdClient()
>>> client.decrement('some.int')
2011-02-16 08:26:43 +03:00
"""
self.update_stats(stats, -1, sample_rate)
2012-08-30 21:04:47 +04:00
def update_stats(self, stats, delta=1, sampleRate=1):
2011-02-16 08:26:43 +03:00
"""
Updates one or more stats counters by arbitrary amounts
2012-12-10 00:57:57 +04:00
>>> client = StatsdClient()
2012-12-10 01:00:36 +04:00
>>> client.update_stats('some.int', 10)
2011-02-16 08:26:43 +03:00
"""
if not isinstance(stats, list):
stats = [stats]
data = {}
for stat in stats:
2012-12-23 15:13:19 +04:00
data[stat] = "{0}|c".format(delta)
self.send(data, sampleRate)
2012-08-30 21:04:47 +04:00
def send(self, data, sample_rate=1):
2011-02-16 08:26:43 +03:00
"""
Squirt the metrics over UDP
"""
2011-02-16 08:50:22 +03:00
sampled_data = {}
2012-08-30 21:04:47 +04:00
2012-12-10 01:00:36 +04:00
if (sample_rate < 1):
if random() <= sample_rate:
2012-12-10 00:49:34 +04:00
for stat, value in data.items():
2012-12-23 15:13:19 +04:00
sampled_data[stat] = "{0}|@{1}".format(value, sample_rate)
else:
2012-12-10 01:00:36 +04:00
sampled_data = data
2012-08-30 21:04:47 +04:00
udp_sock = socket(AF_INET, SOCK_DGRAM)
try:
2012-12-10 00:49:34 +04:00
for stat, value in sampled_data.items():
2012-12-23 15:13:19 +04:00
send_data = "{0}:{1}".format(stat, value)
udp_sock.sendto(send_data.encode('utf-8'), self.addr)
except Exception:
import sys
2012-12-10 00:44:48 +04:00
import traceback
print("Unexpected error: ", traceback.format_exc(), file=sys.stderr)
return False
return True
if __name__=="__main__":
c = StatsdClient()
c.increment('example.python')