httpcore
httpcore copied to clipboard
Add context to trace functions
This PR adds context to the traces, giving us more control over them and providing context for particular events. It allows us to store variables specifically for that event and access them through the started, complete, or failed stages.
Originally, I tried to add metrics for the httpx client to measure how much time the SSL handshake took. I thought it would be amazing to have some context for the trace functions.
Here is the example of usecase, from the documentation:
import httpcore
import time
def log(event_name, info, context):
_, event_name, stage = event_name.split(".")
if event_name == "start_tls":
if stage == "started":
context["start_time"] = time.monotonic()
elif stage == "complete":
elapsed = time.monotonic() - context["start_time"]
print(f"TLS handshake took {elapsed:.2f} seconds")
r = httpcore.request("GET", "https://www.encode.io/", extensions={"trace": log})