class LowLevelStatsdClient(object): def __init__(self, host, port, packet_size=512, flush_interval=0.5): self.host = host self.port = port self.collector = MetricCollector(packet_size) self._udp_client = None self._running = False self._done = asyncio.Future() self.flush_interval = flush_interval def send_timer(self, name, value, rate): self.collector.push_timer(name, value, rate) def send_gauge(self, name, value, rate): self.collector.push_gauge(name, value, rate) def send_counter(self, name, value, rate): self.collector.push_counter(name, value, rate) async def run(self): self._udp_client = UDPClient(self.host, self.port) work = [self._udp_client.run()] self._running = True async def ticker(): while self._running: await asyncio.sleep(self.flush_interval) messages = self.collector.flush() for msg in messages: self._udp_client.send_nowait(msg) work.append(ticker()) await asyncio.gather(*work) self._done.set_result(True) async def stop(self): self._running = False await self._udp_client.stop() await self._done
def encode_counter(name, val, rate=1.0): collector = MetricCollector() collector.push_counter(name, val, rate) result = list(collector.flush()) assert len(result) == 1 return result[0]