DRY-up logging and metrics for sending SMS

This avoids duplicating it as we add a new provider and means we
can test it all in one place (although it wasn't tested before).

I'm not sure why the previous code did "super(..)__init__" in a
non-init function - it's a bit late! - so I've just replaced it
with a call to the new "init_app" function in the parent class.
This commit is contained in:
Ben Thorner
2022-03-25 13:05:23 +00:00
parent 84578e8a1d
commit 3b082477f0
6 changed files with 112 additions and 66 deletions

View File

@@ -1,3 +1,5 @@
from time import monotonic
from app.clients import Client, ClientException
@@ -18,6 +20,10 @@ class SmsClient(Client):
Base Sms client for sending smss.
'''
def init_app(self, current_app, statsd_client):
self.current_app = current_app
self.statsd_client = statsd_client
def record_outcome(self, success):
log_message = "Provider request for {} {}".format(
self.name,
@@ -31,7 +37,23 @@ class SmsClient(Client):
self.statsd_client.incr(f"clients.{self.name}.error")
self.current_app.logger.warning(log_message)
def send_sms(self, *args, **kwargs):
def send_sms(self, to, content, reference, international, sender=None):
start_time = monotonic()
try:
response = self.try_send_sms(to, content, reference, international, sender)
self.record_outcome(True)
except SmsClientResponseException as e:
self.record_outcome(False)
raise e
finally:
elapsed_time = monotonic() - start_time
self.statsd_client.timing(f"clients.{self.name}.request-time", elapsed_time)
self.current_app.logger.info("Reach request for {} finished in {}".format(reference, elapsed_time))
return response
def try_send_sms(self, *args, **kwargs):
raise NotImplementedError('TODO Need to implement.')
@property