Repository navigation
Add HTTP body capture for WSGI #5272
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
Open
anuraaga
wants to merge
2
commits into
open-telemetry:main
Choose a base branch
from
anuraaga:body-capture
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+668
−2
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| `opentelemetry-util-http`, `opentelemetry-instrumentation-wsgi`: add opt-in request body capture as `http.request.body.content` |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -207,6 +207,27 @@ def response_hook( | |
| Note: | ||
| The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. | ||
|
|
||
| Capture HTTP request body | ||
| ************************* | ||
| To capture the HTTP request body in the ``http.request.body.content`` span attribute, pass | ||
| ``captured_request_body_size``, the maximum number of bytes of the body to capture. Default is ``0``, | ||
| meaning capture is disabled. | ||
|
|
||
| .. code-block:: python | ||
|
|
||
| from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware | ||
|
|
||
| OpenTelemetryMiddleware(app, captured_request_body_size=4096) | ||
|
|
||
| Only the bytes the application reads from ``wsgi.input`` are captured, and only on SERVER spans. The body is | ||
| recorded as a string for textual content types, else as bytes. Bodies with a ``Content-Encoding`` are not captured. | ||
|
|
||
| The body is not captured when ``OTEL_SEMCONV_STABILITY_OPT_IN`` is set to ``http``, since the attribute is not stable. | ||
|
|
||
| Note: | ||
| The request body may contain sensitive data. This feature and the attribute are experimental, and thus are | ||
| subject to change. | ||
|
|
||
| Sanitizing methods | ||
| ****************** | ||
| In order to prevent unbound cardinality for HTTP methods by default nonstandard ones are labeled as ``NONSTANDARD``. | ||
|
|
@@ -284,6 +305,12 @@ def response_hook( | |
| redact_url, | ||
| sanitize_method, | ||
| ) | ||
| from opentelemetry.util.http.body_capture import ( | ||
| HTTP_REQUEST_BODY_CONTENT, | ||
| BodyBuffer, | ||
| CapturingStream, | ||
| create_body_buffer, | ||
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| from wsgiref.types import StartResponse, WSGIApplication, WSGIEnvironment | ||
|
|
@@ -573,6 +600,9 @@ class OpenTelemetryMiddleware: | |
| globally configured one is used. | ||
| meter_provider: Optional meter provider to use. If omitted the current | ||
| globally configured one is used. | ||
| captured_request_body_size: Maximum number of bytes of the request body | ||
| to capture as a span attribute. | ||
| ``0`` disables capture. | ||
| """ | ||
|
|
||
| def __init__( | ||
|
|
@@ -582,6 +612,7 @@ def __init__( | |
| response_hook: ResponseHook | None = None, | ||
| tracer_provider: TracerProvider | None = None, | ||
| meter_provider: MeterProvider | None = None, | ||
| captured_request_body_size: int = 0, | ||
| ): | ||
| # initialize semantic conventions opt-in if needed | ||
| _OpenTelemetrySemanticConventionStability._initialize() | ||
|
|
@@ -626,6 +657,24 @@ def __init__( | |
| self.request_hook = request_hook | ||
| self.response_hook = response_hook | ||
| self._sem_conv_opt_in_mode = sem_conv_opt_in_mode | ||
| self._captured_request_body_size = ( | ||
| 0 if sem_conv_opt_in_mode == _StabilityMode.HTTP else captured_request_body_size | ||
| ) | ||
|
|
||
| def _wrap_request_body(self, span: trace.Span, environ: WSGIEnvironment) -> BodyBuffer | None: | ||
| if not (self._captured_request_body_size > 0 and span.is_recording() and span.kind == trace.SpanKind.SERVER): | ||
| return None | ||
| stream = environ.get("wsgi.input") | ||
| if stream is None: | ||
| return None | ||
| body_buffer = create_body_buffer( | ||
| self._captured_request_body_size, | ||
| environ.get("CONTENT_TYPE"), | ||
| environ.get("HTTP_CONTENT_ENCODING"), | ||
| ) | ||
| if body_buffer is not None: | ||
| environ["wsgi.input"] = CapturingStream(stream, body_buffer) | ||
| return body_buffer | ||
|
|
||
| @staticmethod | ||
| def _create_start_response( | ||
|
|
@@ -688,6 +737,7 @@ def __call__(self, environ: WSGIEnvironment, start_response: StartResponse): | |
| context_getter=wsgi_getter, | ||
| attributes=req_attrs, | ||
| ) | ||
| body_buffer = self._wrap_request_body(span, environ) | ||
|
|
||
| if self.request_hook: | ||
| self.request_hook(span, environ) | ||
|
|
@@ -708,13 +758,14 @@ def __call__(self, environ: WSGIEnvironment, start_response: StartResponse): | |
| self._sem_conv_opt_in_mode, | ||
| ) | ||
| iterable = self.wsgi(environ, start_response) | ||
| return _end_span_after_iterating(iterable, span, token) | ||
| return _end_span_after_iterating(iterable, span, token, body_buffer) | ||
| except Exception as ex: | ||
| if _report_new(self._sem_conv_opt_in_mode): | ||
| req_attrs[ERROR_TYPE] = type(ex).__qualname__ | ||
| if span.is_recording(): | ||
| span.set_attribute(ERROR_TYPE, type(ex).__qualname__) | ||
| span.set_status(Status(StatusCode.ERROR, str(ex))) | ||
| _set_request_body_attribute(span, body_buffer) | ||
| span.end() | ||
| if token is not None: | ||
| context.detach(token) | ||
|
|
@@ -739,17 +790,31 @@ def __call__(self, environ: WSGIEnvironment, start_response: StartResponse): | |
| self.active_requests_counter.add(-1, active_requests_count_attrs) | ||
|
|
||
|
|
||
| def _set_request_body_attribute(span: trace.Span, body_buffer: BodyBuffer | None) -> None: | ||
| if body_buffer is None: | ||
| return | ||
| body = body_buffer.to_attribute_value() | ||
| if body is not None: | ||
| span.set_attribute(HTTP_REQUEST_BODY_CONTENT, body) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we also try to set the content type and content-encoding here? These are opt-in but otherwise it would be pretty hard for backends to know how to handle the data for non-text data. This would probably require an update on the semconv side as well. |
||
|
|
||
|
|
||
| # Put this in a subfunction to not delay the call to the wrapped | ||
| # WSGI application (instrumentation should change the application | ||
| # behavior as little as possible). | ||
| def _end_span_after_iterating(iterable: Iterable[T], span: trace.Span, token: object) -> Iterable[T]: | ||
| def _end_span_after_iterating( | ||
| iterable: Iterable[T], | ||
| span: trace.Span, | ||
| token: object, | ||
| body_buffer: BodyBuffer | None, | ||
| ) -> Iterable[T]: | ||
| try: | ||
| with trace.use_span(span): | ||
| yield from iterable | ||
| finally: | ||
| close = getattr(iterable, "close", None) | ||
| if close: | ||
| close() | ||
| _set_request_body_attribute(span, body_buffer) | ||
| span.end() | ||
| if token is not None: | ||
| context.detach(token) | ||
|
|
||
This file contains hidden or 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
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should be handled by #5323