Last active
November 5, 2021 15:38
-
-
Save n1ckdm/5e274cf57f2ae3f70e8c3e005581ace0 to your computer and use it in GitHub Desktop.
Context manager that yeilds a requests session and starts a span that already has the headers injected with the span's context so that this is passed into the request for tracing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from typing import Generator | |
from contextlib import contextmanager | |
from dataclasses import dataclass | |
@dataclass | |
class Context: | |
span: opentracing.Span | |
session: requests.Session | |
@contextmanager | |
def make_traced_request(url: str) -> Generator[Context]: | |
""" | |
Yeilds a requests session and starts a span that already has the | |
headers injected with the span's context so that this is passed | |
into the request for tracing | |
""" | |
with opentracing.tracer.start_active_span(url) as scope: | |
session = requests.session() | |
headers = {} | |
opentracing.tracer.inject( | |
scope.span, | |
opentracing.Format.HTTP_HEADERS, | |
headers | |
) | |
session.headers.update(headers) | |
yield Context(scope.span, session) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment