From 6eb13b2cef8eb89ca747818f49aad4953d423663 Mon Sep 17 00:00:00 2001 From: Aviram Hassan Date: Wed, 9 Dec 2020 15:42:58 +0200 Subject: [PATCH] [feat] add threshold_ms for conditional timing metrics --- aiodogstatsd/client.py | 3 +++ examples/timeit.py | 1 + tests/test_client.py | 8 ++++++++ 3 files changed, 12 insertions(+) diff --git a/aiodogstatsd/client.py b/aiodogstatsd/client.py index 980bbaa..77c52ec 100644 --- a/aiodogstatsd/client.py +++ b/aiodogstatsd/client.py @@ -257,6 +257,7 @@ def timeit( *, tags: Optional[typedefs.MTags] = None, sample_rate: Optional[typedefs.MSampleRate] = None, + threshold_ms: Optional[typedefs.MValue] = None, ) -> Iterator[None]: """ Context manager for easily timing methods. @@ -268,6 +269,8 @@ def timeit( yield finally: value = (loop.time() - started_at) * 1000 + if threshold_ms and value < threshold_ms: + return self.timing(name, value=int(value), tags=tags, sample_rate=sample_rate) diff --git a/examples/timeit.py b/examples/timeit.py index 225943b..609d2b7 100644 --- a/examples/timeit.py +++ b/examples/timeit.py @@ -9,6 +9,7 @@ async def main(): ) await client.connect() + # Use threshold_ms for setting a threshold for sending the timing metric. with client.timeit("fire"): # Do action we want to time pass diff --git a/tests/test_client.py b/tests/test_client.py index f605aaf..7a26004 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -153,6 +153,14 @@ async def test_timeit(self, statsd_client, statsd_server, wait_for, mocker): loop.return_value.time.return_value = 1.0 with statsd_client.timeit("test_timer", tags={"and": "robin"}): loop.return_value.time.return_value = 2.0 + + # This shouldn't be logged. + loop.return_value.time.return_value = 1.0 + with statsd_client.timeit( + "test_timer", tags={"and": "robin"}, threshold_ms=3000.0 + ): + loop.return_value.time.return_value = 2.0 + async with udp_server: await wait_for(collected) assert collected == [b"test_timer:1000|ms|#whoami:batman,and:robin"]