Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add opentelemetry requests hook to trace HTTP headers #795

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion services/common/rs_server_common/utils/opentelemetry.py
vprivat-ads marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
Expand All @@ -38,6 +39,22 @@
FROM_PYTEST = False


def request_hook(span, request):
"""
HTTP requests intrumentation
"""
if span:
span.set_attribute("http.request.headers", str(request.headers))


def response_hook(span, request, response): # pylint: disable=W0613
"""
HTTP responses intrumentation
"""
if span:
span.set_attribute("http.response.headers", str(response.headers))


def init_traces(app: fastapi.FastAPI, service_name: str):
"""
Init instrumentation of OpenTelemetry traces.
Expand Down Expand Up @@ -115,7 +132,13 @@ def init_traces(app: fastapi.FastAPI, service_name: str):
if callable(_instrument):

_class_instance = _class()
if not _class_instance.is_instrumented_by_opentelemetry:
if _class == RequestsInstrumentor and os.getenv("OTEL_PYTHON_REQUESTS_TRACE_HEADERS"):
_class_instance.instrument(
tracer_provider=otel_tracer,
request_hook=request_hook,
response_hook=response_hook,
)
elif not _class_instance.is_instrumented_by_opentelemetry:
_class_instance.instrument(tracer_provider=otel_tracer)
# name = f"{module_str}.{_class.__name__}".removeprefix(prefix)
# logger.debug(f"OpenTelemetry instrumentation of {name!r}")
Loading