-
Notifications
You must be signed in to change notification settings - Fork 1
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
[#2] Add option to log request response body #4
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6ed8a4c
add logging of request + response body
pi-sigma 68e8020
add tests for logging request + response body
pi-sigma 5008ad8
update README and docs
pi-sigma 6bae3ef
process PR feedback
pi-sigma 09a0c0f
:wrench: Turn naive datetime warnings into errors in tests
sergei-maertens 6e7755d
:bug: Use timezone aware datetimes in test
sergei-maertens 0f843fd
:art: Clean up implementation and types
sergei-maertens 2290817
:recycle: Support Django 4.2, copy parse_header_parameters from DRF
sergei-maertens b8d6edb
:recycle: Reduce code duplication
sergei-maertens 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 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 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 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 |
---|---|---|
|
@@ -58,6 +58,17 @@ Installation | |
} | ||
|
||
LOG_OUTGOING_REQUESTS_DB_SAVE = True # save logs enabled/disabled based on the boolean value | ||
LOG_OUTGOING_REQUESTS_DB_SAVE_BODY = True # save request/response body | ||
LOG_OUTGOING_REQUESTS_EMIT_BODY = True # log request/response body | ||
LOG_OUTGOING_REQUESTS_CONTENT_TYPES = [ | ||
"text/*", | ||
"application/json", | ||
"application/xml", | ||
"application/soap+xml", | ||
] # save request/response bodies with matching content type | ||
LOG_OUTGOING_REQUESTS_MAX_CONTENT_LENGTH = 524_288 # maximal size (in bytes) for the request/response body | ||
LOG_OUTGOING_REQUESTS_LOG_BODY_TO_STDOUT = True | ||
|
||
Comment on lines
+61
to
+71
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. I think the library is currently missing a proper default settings mechanism, so I created #6 for this. |
||
|
||
#. Run ``python manage.py migrate`` to create the necessary database tables. | ||
|
||
|
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import django | ||
|
||
# Taken from djangorestframework, see | ||
# https://github.com/encode/django-rest-framework/blob/376a5cbbba3f8df9c9db8c03a7c8fa2a6e6c05f4/rest_framework/compat.py#LL156C1-L177C10 | ||
# | ||
# License: | ||
# | ||
# Copyright © 2011-present, [Encode OSS Ltd](https://www.encode.io/). | ||
# All rights reserved. | ||
# | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are met: | ||
# | ||
# * Redistributions of source code must retain the above copyright notice, this | ||
# list of conditions and the following disclaimer. | ||
# | ||
# * Redistributions in binary form must reproduce the above copyright notice, | ||
# this list of conditions and the following disclaimer in the documentation | ||
# and/or other materials provided with the distribution. | ||
# | ||
# * Neither the name of the copyright holder nor the names of its | ||
# contributors may be used to endorse or promote products derived from | ||
# this software without specific prior written permission. | ||
# | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | ||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | ||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
||
if django.VERSION >= (4, 2): | ||
# Django 4.2+: use the stock parse_header_parameters function | ||
# Note: Django 4.1 also has an implementation of parse_header_parameters | ||
# which is slightly different from the one in 4.2, it needs | ||
# the compatibility shim as well. | ||
from django.utils.http import parse_header_parameters # type: ignore | ||
else: | ||
# Django <= 4.1: create a compatibility shim for parse_header_parameters | ||
from django.http.multipartparser import parse_header | ||
|
||
def parse_header_parameters(line): | ||
# parse_header works with bytes, but parse_header_parameters | ||
# works with strings. Call encode to convert the line to bytes. | ||
main_value_pair, params = parse_header(line.encode()) | ||
return main_value_pair, { | ||
# parse_header will convert *some* values to string. | ||
# parse_header_parameters converts *all* values to string. | ||
# Make sure all values are converted by calling decode on | ||
# any remaining non-string values. | ||
k: v if isinstance(v, str) else v.decode() | ||
for k, v in params.items() | ||
} | ||
|
||
|
||
__all__ = ["parse_header_parameters"] |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
from django.db import models | ||
from django.utils.translation import gettext_lazy as _ | ||
|
||
|
||
class SaveLogsChoice(models.TextChoices): | ||
use_default = "use_default", _("Use default") | ||
yes = "yes", _("Yes") | ||
no = "no", _("No") |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
""" | ||
Datastructure(s) for use in settings.py | ||
|
||
Note: do not place any Django-specific imports in this file, as | ||
it must be imported in settings.py. | ||
""" | ||
|
||
from dataclasses import dataclass | ||
from typing import Union | ||
|
||
|
||
@dataclass | ||
class ContentType: | ||
""" | ||
Data class for keeping track of content types and associated default encodings | ||
""" | ||
|
||
pattern: str | ||
default_encoding: str | ||
|
||
|
||
@dataclass | ||
class ProcessedBody: | ||
allow_saving_to_db: bool | ||
content: Union[bytes, str] | ||
content_type: str | ||
encoding: str |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,42 @@ | ||
import logging | ||
import textwrap | ||
|
||
from django.conf import settings | ||
|
||
|
||
class HttpFormatter(logging.Formatter): | ||
def _formatHeaders(self, d): | ||
return "\n".join(f"{k}: {v}" for k, v in d.items()) | ||
|
||
def _formatBody(self, content: str, request_or_response: str) -> str: | ||
if settings.LOG_OUTGOING_REQUESTS_EMIT_BODY: | ||
return f"\n{request_or_response} body:\n{content}" | ||
return "" | ||
|
||
def formatMessage(self, record): | ||
result = super().formatMessage(record) | ||
if record.name == "requests": | ||
result += textwrap.dedent( | ||
""" | ||
---------------- request ---------------- | ||
{req.method} {req.url} | ||
{reqhdrs} | ||
|
||
---------------- response ---------------- | ||
{res.status_code} {res.reason} {res.url} | ||
{reshdrs} | ||
if record.name != "requests": | ||
return result | ||
|
||
result += textwrap.dedent( | ||
""" | ||
).format( | ||
req=record.req, | ||
res=record.res, | ||
reqhdrs=self._formatHeaders(record.req.headers), | ||
reshdrs=self._formatHeaders(record.res.headers), | ||
) | ||
---------------- request ---------------- | ||
{req.method} {req.url} | ||
{reqhdrs} {request_body} | ||
|
||
---------------- response ---------------- | ||
{res.status_code} {res.reason} {res.url} | ||
{reshdrs} {response_body} | ||
|
||
""" | ||
).format( | ||
req=record.req, | ||
res=record.res, | ||
reqhdrs=self._formatHeaders(record.req.headers), | ||
reshdrs=self._formatHeaders(record.res.headers), | ||
request_body=self._formatBody(record.req.body, "Request"), | ||
response_body=self._formatBody(record.res.content, "Response"), | ||
) | ||
|
||
return result |
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.
as discussed in the office - this would probably benefit from a dataclass so you can do things like:
then algorithm-wise you:
settings.LOG_OUTGOING_REQUESTS_CONTENT_TYPES
ContentType.default_encoding
Somewhere in between there's also the check if settings/configuration and the body size
We also discussed that you might provide a setting/escape hatch to derive the encoding, something along the lines of:
so the default setting value should be the library function, but projects can provide their own function. In the case of XML for example, you'd want to parse the first line and get the value from the
<?xml encoding="...">
part, but that's for projects to figure out.