Add datetime.timedelta support to timing.

This commit is contained in:
Dave Shawley 2021-07-18 11:23:33 -04:00
parent 1c6ba8f80e
commit 65745010ad
No known key found for this signature in database
GPG key ID: F41A8A99298F8EED
3 changed files with 15 additions and 1 deletions

View file

@ -2,6 +2,8 @@ Next release
------------ ------------
- Added ``Connector.timer`` method (addresses :issue:`8`) - Added ``Connector.timer`` method (addresses :issue:`8`)
- Implement ``Timer`` abstraction from python-statsd - Implement ``Timer`` abstraction from python-statsd
- ``Connector.timing`` now accepts :class:`datetime.timedelta` instances in addition
to :class:`float` instances
:tag:`0.1.0 <0.0.1...0.1.0>` (10-May-2021) :tag:`0.1.0 <0.0.1...0.1.0>` (10-May-2021)
------------------------------------------ ------------------------------------------

View file

@ -1,4 +1,5 @@
import asyncio import asyncio
import datetime
import logging import logging
import socket import socket
import time import time
@ -174,13 +175,16 @@ class AbstractConnector:
payload = str(value) payload = str(value)
self.inject_metric(f'gauges.{path}', payload, 'g') self.inject_metric(f'gauges.{path}', payload, 'g')
def timing(self, path: str, seconds: float) -> None: def timing(self, path: str,
seconds: typing.Union[float, datetime.timedelta]) -> None:
"""Send a timer metric. """Send a timer metric.
:param path: timer to append a value to :param path: timer to append a value to
:param seconds: number of **seconds** to record :param seconds: number of **seconds** to record
""" """
if isinstance(seconds, datetime.timedelta):
seconds = seconds.total_seconds()
self.inject_metric(f'timers.{path}', str(seconds * 1000.0), 'ms') self.inject_metric(f'timers.{path}', str(seconds * 1000.0), 'ms')
def timer(self, path) -> Timer: def timer(self, path) -> Timer:

View file

@ -1,4 +1,5 @@
import asyncio import asyncio
import datetime
import logging import logging
import socket import socket
import time import time
@ -337,6 +338,13 @@ class ConnectorTests(ProcessorTestCase):
self.assert_metrics_equal(self.statsd_server.metrics[0], self.assert_metrics_equal(self.statsd_server.metrics[0],
'timers.simple.timer', 12340.0, 'ms') 'timers.simple.timer', 12340.0, 'ms')
async def test_sending_timer_using_timedelta(self):
secs = datetime.timedelta(seconds=12, milliseconds=340)
self.connector.timing('simple.timer', secs)
await self.wait_for(self.statsd_server.message_received.acquire())
self.assert_metrics_equal(self.statsd_server.metrics[0],
'timers.simple.timer', 12340.0, 'ms')
async def test_timing_context_manager(self): async def test_timing_context_manager(self):
with unittest.mock.patch( with unittest.mock.patch(
'sprockets_statsd.statsd.time.time') as time_function: 'sprockets_statsd.statsd.time.time') as time_function: