Skip to content

Instantly share code, notes, and snippets.

@pfreixes
Last active October 19, 2017 10:58
Show Gist options
  • Save pfreixes/e0e3b3f98339d6689b031027ed6fa4b8 to your computer and use it in GitHub Desktop.
Save pfreixes/e0e3b3f98339d6689b031027ed6fa4b8 to your computer and use it in GitHub Desktop.
Example of how the new RequestTracing might be used to send the proper metrics at each request and interpose some header
class MetricsClient(ClientSession):
def __init__(self, metric_name, region, **kwargs):
self(MetricsClient, self).__init__(
self,
*args,
request_tracing=True,
request_tracing_ctx=dict
**kwargs)
self.metric_name = metric_name
self.region = region
self.on_request_start.add(self._request_started)
self.on_request_stop.add(self._request_finished)
self.on_request_exception.add(self._request_error)
async def _request_started(self, session, trace_context, method, host, port, headers):
trace_context.started = self._loop.time()
# save some information related to request that will be used
# to send as tags along the metrics
trace_context.host = host
trace_context.port = port
trace_context.method = method
# modify heades to forward request_id
headers['request_id'] = aiotask_context.get('request_id')
async def _request_finished(self, session, trace_context, response):
elapsed = self._loop.time() - trace_context.started
await metric.increment(
self.metric_name,
# tags composed from different sources
status_code=resopnse.status_code,
region=self.region,
query=trace_context.query
)
await metric.time(
self.metric_name,
elapsed,
# tags time series
status_code=resopnse.status_code,
region=self.region,
host=trace_context.host,
port=trace_context.port,
method=trace_context.method,
query=trace_context.query
)
async def _request_exception(self, session, trace_context, exc):
status_code = 503 if isinstance(exc, asyncio.TimeoutError) else 500
await metric.increment(
self.metric_name,
status_code=status_code,
)
session = MetricClient('foo_metric', 'eu-west-1')
async def foo():
resp = await session.get(
"http://microservice_foo.local/search?q=people",
trace_trace_context=SimpleNamespace(query='people')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment